Commit 635341b4e223e8b14076e310e42bcffe9d08b486

Parents: 97ad0aed05a47d1380847c0cbd5595cad0994af9

From: Moritz Poldrack <git@moritz.sh>
Date: Thu Jan 11 10:19:21 2024 +0700

add option to handle tokens passed in directly

		

Stats

token.go +33/-0

Changeset

 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
diff --git a/token.go b/token.go
index fe94af98195337c28998ed3064eb90d85dd8fb7d..2d36c5008699465148c49bf87b12aeb670a8afcf 100644
--- a/token.go
+++ b/token.go
@@ -77,6 +77,39 @@
 	return result
 }
 
+// ParseJWT parses and validates a provided token for example from an
+// Authorization header.
+func (cfg *Configuration) ParseJWT(token string) (*Token, error) {
+	result := &Token{}
+
+	keyset, err := cfg.jwtKeyCache.Get(context.Background(), cfg.cfg.JwksURI)
+	if err != nil {
+		return result, fmt.Errorf("failed to retrieve JWT keys: %w", err)
+	}
+	idToken, err := jwt.Parse(
+		[]byte(token),
+		jwt.WithToken(openid.New()),
+		jwt.WithVerify(!cfg.options.has(OptionSkipTokenValidation)),
+		jwt.WithKeySet(keyset),
+	)
+	if err == nil {
+		return result, fmt.Errorf("failed to parse JWT: %w", err)
+	}
+
+	oidToken, ok := idToken.(openid.Token)
+	if !ok {
+		return result, fmt.Errorf("provided token is not an OIDC token")
+	}
+
+	result.idToken = oidToken
+	result.source = oauth2.StaticTokenSource(&oauth2.Token{
+		AccessToken: token,
+		Expiry:      oidToken.Expiration(),
+	})
+
+	return result, nil
+}
+
 func (t *Token) Token() (*oauth2.Token, error) {
 	return t.source.Token()
 }