-
Notifications
You must be signed in to change notification settings - Fork 13
/
authentication_handler.go
56 lines (45 loc) · 1.45 KB
/
authentication_handler.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
package server
import (
"net/http"
"strings"
"github.com/cloudfoundry/bosh-utils/errors"
)
type authenticationHandler struct {
tokenValidator TokenValidator
nextHandler http.Handler
}
func NewAuthenticationHandler(tokenValidator TokenValidator, nextHandler http.Handler) http.Handler {
return authenticationHandler{
tokenValidator: tokenValidator,
nextHandler: nextHandler,
}
}
func (handler authenticationHandler) ServeHTTP(resWriter http.ResponseWriter, req *http.Request) {
if err := handler.authenticate(req); err != nil {
http.Error(resWriter, NewErrorResponse(err).GenerateErrorMsg(), http.StatusUnauthorized)
} else {
handler.nextHandler.ServeHTTP(resWriter, req)
}
}
func (handler authenticationHandler) authenticate(req *http.Request) error {
authHeader := req.Header.Get("Authorization")
if len(authHeader) == 0 {
return errors.Error("Missing authorization token")
}
jwtToken, err := handler.checkTokenFormat(authHeader)
if err != nil {
return err
}
return handler.tokenValidator.Validate(jwtToken)
}
func (handler authenticationHandler) checkTokenFormat(token string) (string, error) {
tokenParts := strings.Split(token, " ")
if len(tokenParts) != 2 {
return "", errors.Error("Invalid authorization token format")
}
tokenType, userToken := tokenParts[0], tokenParts[1]
if !strings.EqualFold(tokenType, "bearer") {
return "", errors.Error("Invalid authorization token type: " + tokenType)
}
return userToken, nil
}