/
authentication_provider.go
61 lines (50 loc) · 1.92 KB
/
authentication_provider.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
package security
import (
"strings"
"aahframework.org/config.v0"
"aahframework.org/essentials.v0"
"aahframework.org/log.v0"
"aahframework.org/security.v0/authc"
"github.com/dgrijalva/jwt-go"
)
var _ authc.Authenticator = (*AuthenticationProvider)(nil)
// AuthenticationProvider struct implements `authc.Authenticator` interface.
type AuthenticationProvider struct{}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// AuthenticationProvider methods
//___________________________________
// Init method initializes the AuthenticationProvider, this method gets called
// during server start up.
func (a *AuthenticationProvider) Init(cfg *config.Config) error {
return nil
}
// GetAuthenticationInfo method is `authc.Authenticator` interface. It is called by Security Manager.
func (a *AuthenticationProvider) GetAuthenticationInfo(authcToken *authc.AuthenticationToken) (*authc.AuthenticationInfo, error) {
// authcToken.Identity is complete value of "Authorization" HTTP header or
// configured `security.auth_schemes.jwt_auth.header.identity` header value
//
// values[0] ==> Bearer
// values[1] ==> JWT token
values := strings.Fields(authcToken.Identity)
if len(values) != 2 || ess.IsStrEmpty(values[1]) {
log.Error("Token is not provided")
return nil, authc.ErrAuthenticationFailed
}
// Validate the JWT token
token, err := jwt.Parse(values[1], jwtKeyFunc)
if err != nil || !token.Valid {
log.Errorf("Error occurred '%v' or token is not valid", err)
return nil, authc.ErrAuthenticationFailed
}
claims := token.Claims.(jwt.MapClaims)
// User found and token validated.
// Now create authentication info and return to the framework
authcInfo := authc.NewAuthenticationInfo()
authcInfo.Principals = append(authcInfo.Principals,
&authc.Principal{
Value: claims["username"].(string),
IsPrimary: true,
Realm: "inmemory",
})
return authcInfo, nil
}