You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/rest/handler/authhandler.go

123 lines
3.1 KiB
Go

4 years ago
package handler
4 years ago
import (
"context"
"errors"
4 years ago
"net/http"
"net/http/httputil"
"github.com/golang-jwt/jwt/v4"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/internal/response"
"github.com/zeromicro/go-zero/rest/token"
4 years ago
)
const (
jwtAudience = "aud"
jwtExpire = "exp"
jwtId = "jti"
jwtIssueAt = "iat"
jwtIssuer = "iss"
jwtNotBefore = "nbf"
jwtSubject = "sub"
noDetailReason = "no detail reason"
)
var (
errInvalidToken = errors.New("invalid auth token")
errNoClaims = errors.New("no auth params")
4 years ago
)
type (
// A AuthorizeOptions is authorize options.
4 years ago
AuthorizeOptions struct {
PrevSecret string
Callback UnauthorizedCallback
}
// UnauthorizedCallback defines the method of unauthorized callback.
4 years ago
UnauthorizedCallback func(w http.ResponseWriter, r *http.Request, err error)
// AuthorizeOption defines the method to customize an AuthorizeOptions.
AuthorizeOption func(opts *AuthorizeOptions)
4 years ago
)
// Authorize returns an authorization middleware.
4 years ago
func Authorize(secret string, opts ...AuthorizeOption) func(http.Handler) http.Handler {
var authOpts AuthorizeOptions
for _, opt := range opts {
opt(&authOpts)
}
parser := token.NewTokenParser()
4 years ago
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tok, err := parser.ParseToken(r, secret, authOpts.PrevSecret)
4 years ago
if err != nil {
unauthorized(w, r, err, authOpts.Callback)
return
}
if !tok.Valid {
unauthorized(w, r, errInvalidToken, authOpts.Callback)
4 years ago
return
}
claims, ok := tok.Claims.(jwt.MapClaims)
4 years ago
if !ok {
unauthorized(w, r, errNoClaims, authOpts.Callback)
4 years ago
return
}
ctx := r.Context()
for k, v := range claims {
switch k {
case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject:
// ignore the standard claims
default:
ctx = context.WithValue(ctx, k, v)
}
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// WithPrevSecret returns an AuthorizeOption with setting previous secret.
4 years ago
func WithPrevSecret(secret string) AuthorizeOption {
return func(opts *AuthorizeOptions) {
opts.PrevSecret = secret
}
}
// WithUnauthorizedCallback returns an AuthorizeOption with setting unauthorized callback.
4 years ago
func WithUnauthorizedCallback(callback UnauthorizedCallback) AuthorizeOption {
return func(opts *AuthorizeOptions) {
opts.Callback = callback
}
}
func detailAuthLog(r *http.Request, reason string) {
// discard dump error, only for debug purpose
details, _ := httputil.DumpRequest(r, true)
logx.Errorf("authorize failed: %s\n=> %+v", reason, string(details))
}
func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback UnauthorizedCallback) {
writer := response.NewHeaderOnceResponseWriter(w)
4 years ago
if err != nil {
detailAuthLog(r, err.Error())
} else {
detailAuthLog(r, noDetailReason)
}
// let callback go first, to make sure we respond with user-defined HTTP header
4 years ago
if callback != nil {
callback(writer, r, err)
}
// if user not setting HTTP header, we set header with 401
writer.WriteHeader(http.StatusUnauthorized)
4 years ago
}