-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthentication_provider_gitlab.go
More file actions
72 lines (60 loc) · 1.8 KB
/
authentication_provider_gitlab.go
File metadata and controls
72 lines (60 loc) · 1.8 KB
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
68
69
70
71
72
package vignet
import (
"context"
"fmt"
"net/http"
netUrl "net/url"
"strings"
"github.com/MicahParks/keyfunc"
"github.com/golang-jwt/jwt/v4"
)
type GitLabAuthenticationProvider struct {
jwks *keyfunc.JWKS
}
var _ AuthenticationProvider = &GitLabAuthenticationProvider{}
// NewGitLabAuthenticationProvider creates a new GitLabAuthenticationProvider.
//
// It takes the GitLab instance URL as an argument.
// The context is used to cancel the refreshing of keys.
func NewGitLabAuthenticationProvider(ctx context.Context, url string) (*GitLabAuthenticationProvider, error) {
parsedURL, err := netUrl.Parse(url)
if err != nil {
return nil, fmt.Errorf("invalid URL: %w", err)
}
parsedURL.Path = "/oauth/discovery/keys"
jwks, err := keyfunc.Get(parsedURL.String(), keyfunc.Options{
Ctx: ctx,
})
if err != nil {
return nil, fmt.Errorf("loading JWKS: %w", err)
}
p := &GitLabAuthenticationProvider{
jwks: jwks,
}
return p, nil
}
func (p *GitLabAuthenticationProvider) AuthCtxFromRequest(r *http.Request) (AuthCtx, error) {
authorizationHeader := r.Header.Get("Authorization")
if authorizationHeader == "" {
return AuthCtx{
Error: fmt.Errorf("missing Authorization header"),
}, nil
}
const bearerPrefix = "Bearer "
if !strings.HasPrefix(authorizationHeader, bearerPrefix) {
return AuthCtx{
Error: fmt.Errorf("invalid Bearer scheme in Authorization header"),
}, nil
}
encodedJWT := authorizationHeader[len(bearerPrefix):]
token, err := jwt.ParseWithClaims(encodedJWT, &GitLabClaims{}, p.jwks.Keyfunc, jwt.WithValidMethods([]string{"RS256"}))
if err != nil {
return AuthCtx{
Error: fmt.Errorf("parsing JWT: %w", err),
}, nil
}
claims := token.Claims.(*GitLabClaims)
return AuthCtx{
GitLabClaims: claims,
}, nil
}