Mercurial > gemma
view auth/middleware.go @ 125:a98a282f00e1
Wired token generator and connection pool to token server.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Thu, 28 Jun 2018 12:21:36 +0200 |
parents | 29e56c342c9f |
children | 441a8ee637c5 |
line wrap: on
line source
package auth import ( "context" "fmt" "net/http" "regexp" ) var extractToken = regexp.MustCompile(`\s*Bearer\s+(\S+)`) type contextType int const ( claimsKey contextType = iota tokenKey ) func GetClaims(req *http.Request) (*Claims, bool) { claims, ok := req.Context().Value(claimsKey).(*Claims) return claims, ok } func GetToken(req *http.Request) (string, bool) { token, ok := req.Context().Value(tokenKey).(string) return token, ok } func JWTMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { auth := req.Header.Get("Authorization") token := extractToken.FindStringSubmatch(auth) if len(token) != 2 { http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } claims, err := TokenToClaims(token[1]) if err != nil { http.Error(rw, fmt.Sprintf("error: %v", err), http.StatusUnauthorized) return } ctx := req.Context() ctx = context.WithValue(ctx, claimsKey, claims) ctx = context.WithValue(ctx, tokenKey, token[1]) req = req.WithContext(ctx) next.ServeHTTP(rw, req) }) }