-
Notifications
You must be signed in to change notification settings - Fork 69
/
auth.go
67 lines (57 loc) · 2.06 KB
/
auth.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
55
56
57
58
59
60
61
62
63
64
65
66
67
package chatter
import (
"context"
jwt "github.com/dgrijalva/jwt-go"
chattersvc "goa.design/examples/streaming/gen/chatter"
"goa.design/goa/security"
)
var (
// ErrUnauthorized is the error returned by Login when the request credentials
// are invalid.
ErrUnauthorized error = chattersvc.Unauthorized("invalid username and password combination")
// ErrInvalidToken is the error returned when the JWT token is invalid.
ErrInvalidToken error = chattersvc.Unauthorized("invalid token")
// ErrInvalidTokenScopes is the error returned when the scopes provided in
// the JWT token claims are invalid.
ErrInvalidTokenScopes error = chattersvc.InvalidScopes("invalid scopes in token")
// Key is the key used in JWT authentication
Key = []byte("secret")
)
// BasicAuth implements the authorization logic for service "chatter"
// for the "basic" security scheme.
func (s *chatterSvc) BasicAuth(ctx context.Context, user, pass string, scheme *security.BasicScheme) (context.Context, error) {
if user != "goa" {
return ctx, ErrUnauthorized
}
if pass != "rocks" {
return ctx, ErrUnauthorized
}
return ctx, nil
}
// JWTAuth implements the authorization logic for service "chatter" for
// the "jwt" security scheme.
func (s *chatterSvc) JWTAuth(ctx context.Context, token string, scheme *security.JWTScheme) (context.Context, error) {
claims := make(jwt.MapClaims)
// authorize request
// 1. parse JWT token, token key is hardcoded to "secret" in this example
_, err := jwt.ParseWithClaims(token, claims, func(_ *jwt.Token) (interface{}, error) { return Key, nil })
if err != nil {
return ctx, ErrInvalidToken
}
// 2. validate provided "scopes" claim
if claims["scopes"] == nil {
return ctx, ErrInvalidTokenScopes
}
scopes, ok := claims["scopes"].([]interface{})
if !ok {
return ctx, ErrInvalidTokenScopes
}
scopesInToken := make([]string, len(scopes))
for _, scp := range scopes {
scopesInToken = append(scopesInToken, scp.(string))
}
if err := scheme.Validate(scopesInToken); err != nil {
return ctx, chattersvc.InvalidScopes(err.Error())
}
return ctx, nil
}