-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
54 lines (44 loc) · 1.45 KB
/
context.go
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package authentication
import (
"context"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
)
// contextKey is a value for use with context.WithValue. It's used as
// a pointer so it fits in an interface{} without allocation. This technique
// for defining context keys was copied from Go 1.7's new use of context in net/http.
type contextKey struct {
name string
}
// Context keys
var (
TokenCtxKey = &contextKey{"Token"}
AccessClaimsCtxKey = &contextKey{"AccessClaims"}
ErrorCtxKey = &contextKey{"Error"}
)
// TokenFromContext extracts the JWT token from the request context
func TokenFromContext(ctx context.Context) (*jwt.Token, jwt.MapClaims, error) {
token, _ := ctx.Value(TokenCtxKey).(*jwt.Token)
var claims jwt.MapClaims
if token != nil {
if tokenClaims, ok := token.Claims.(jwt.MapClaims); ok {
claims = tokenClaims
} else {
panic(fmt.Sprintf("jwtauth: unknown type of Claims: %T", token.Claims))
}
} else {
claims = jwt.MapClaims{}
}
err, _ := ctx.Value(ErrorCtxKey).(error)
return token, claims, err
}
// NewContext creates a new context with JWT token and error
func NewContext(ctx context.Context, t *jwt.Token, err error) context.Context {
ctx = context.WithValue(ctx, TokenCtxKey, t)
ctx = context.WithValue(ctx, ErrorCtxKey, err)
return ctx
}
// AppClaimsFromCtx retrieves the parsed AppClaims from request context.
func AppClaimsFromCtx(ctx context.Context) AppClaims {
return ctx.Value(AccessClaimsCtxKey).(AppClaims)
}