在go框架中,中间件认证和授权用于在请求处理前验证用户身份和访问权限。认证通过检查令牌或凭据验证用户身份,而授权则通过检查角色或属性确定用户访问特定资源的权限。authware和authorizer中间件可用于实施认证和授权,从而轻松地将这些功能添加到应用程序中。
Go框架中的中间件认证和授权
在Go框架中,中间件用于在HTTP请求到达处理程序之前对其进行处理。这使得我们可以轻松地为应用程序添加跨控制器和路由的通用功能,比如认证和授权。
认证
认证负责验证用户的身份。我们可以使用中间件来检查传入请求是否存在有效的身份验证令牌或其他凭据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import (
"context"
"fmt"
"net/http"
middleware "<a style=color:f60; text-decoration:underline; href="https://www.php.cn/zt/15841.html" target="_blank">git</a>hub.com/go-chi/chi/middleware"
)
// Authware ...
type Authware struct {
Verifier interface{}
}
// NewAuthware ...
func NewAuthware(verifier interface{}) Authware {
return &Authware{Verifier: verifier}
}
func (a Authware) Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
middleware.Render(w, r, http.StatusUnauthorized, nil)
return
}
ctx := r.Context()
verifier := a.Verifier.(func(context.Context, http.Request, string) (interface{}, error))
user, err := verifier(ctx, r, token)
if err != nil {
middleware.Render(w, r, http.StatusBadRequest, fmt.Sprintf("Unable to verify token: %v", err))
return
}
r = r.WithContext(context.WithValue(ctx, "user", user))
next.ServeHTTP(w, r)
})
}
授权
授权负责检查用户是否有权访问特定资源。我们可以通过检查用户在认证期间获得的角色或其他属性来实现授权。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import (
"context"
"fmt"
"net/http"
middleware "github.com/go-chi/chi/middleware"
)
// Authorizer ...
type Authorizer struct {
Authorizer interface{}
}
// NewAuthorizer ...
func NewAuthorizer(authorizer interface{}) Authorizer {
return &Authorizer{Authorizer: authorizer}
}
func (a Authorizer) Authorize(role string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r http.Request) {
user := r.Context().Value("user")
ctx := r.Context()
authorizer := a.Authorizer.(func(context.Context, interface{}, string) error)
err := authorizer(ctx, user, role)
if err != nil {
middleware.Render(w, r, http.StatusForbidden, fmt.Sprintf("Access denied: %v", err))
return
}
next.ServeHTTP(w, r)
})
}
实战案例
我们可以使用Authware和Authorizer中间件来实现用户管理API。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import (
//...
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
a := NewAuthware(verifier)
auth := a.Auth(next)
b := NewAuthorizer(authorizer)
admin := b.Authorize("admin", next)
r.GET("/protected", auth, func(c gin.Context) {
// ...
})
r.GET("/admin", auth, admin, func(c gin.Context) {
// ...
})
}
通过这种方式,我们可以轻松地将认证和授权逻辑添加到Go应用程序中,从而确保只有经过授权的用户才能访问特定资源。
以上就是中间件如何在Golang框架中实现认证和授权?的详细内容,更多请关注其它相关文章!