forked from vmware-archive/atc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
accessor_factory.go
57 lines (47 loc) · 1.11 KB
/
accessor_factory.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
package accessor
import (
"crypto/rsa"
"errors"
"fmt"
"net/http"
"strings"
jwt "github.com/dgrijalva/jwt-go"
)
//go:generate counterfeiter . AccessFactory
type AccessFactory interface {
Create(*http.Request) Access
}
type accessFactory struct {
publicKey *rsa.PublicKey
}
func NewAccessFactory(key *rsa.PublicKey) AccessFactory {
return &accessFactory{
publicKey: key,
}
}
func (a *accessFactory) Create(r *http.Request) Access {
var token *jwt.Token
var err error
token, err = a.parseToken(r)
if err != nil {
token = &jwt.Token{}
}
return &access{
token,
}
}
func (a *accessFactory) parseToken(r *http.Request) (*jwt.Token, error) {
fun := func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return a.publicKey, nil
}
if ah := r.Header.Get("Authorization"); ah != "" {
// Should be a bearer token
if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" {
return jwt.Parse(ah[7:], fun)
}
}
return nil, errors.New("unable to parse authorization header")
}