-
-
Notifications
You must be signed in to change notification settings - Fork 364
/
helper.go
98 lines (81 loc) · 2.62 KB
/
helper.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package openid
import (
"bytes"
"context"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"strconv"
"time"
"github.com/ory/fosite"
)
type IDTokenHandleHelper struct {
IDTokenStrategy OpenIDConnectTokenStrategy
}
func (i *IDTokenHandleHelper) GetAccessTokenHash(ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder) string {
token := responder.GetAccessToken()
// The session should always be a openid.Session but best to safely cast
if session, ok := requester.GetSession().(Session); ok {
val, err := i.ComputeHash(ctx, session, token)
if err != nil {
// this should never happen
panic(err)
}
return val
}
buffer := bytes.NewBufferString(token)
hash := sha256.New()
// sha256.digest.Write() always returns nil for err, the panic should never happen
_, err := hash.Write(buffer.Bytes())
if err != nil {
panic(err)
}
hashBuf := bytes.NewBuffer(hash.Sum([]byte{}))
return base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:hashBuf.Len()/2])
}
func (i *IDTokenHandleHelper) generateIDToken(ctx context.Context, lifespan time.Duration, fosr fosite.Requester) (token string, err error) {
token, err = i.IDTokenStrategy.GenerateIDToken(ctx, lifespan, fosr)
if err != nil {
return "", err
}
return token, nil
}
func (i *IDTokenHandleHelper) IssueImplicitIDToken(ctx context.Context, lifespan time.Duration, ar fosite.Requester, resp fosite.AuthorizeResponder) error {
token, err := i.generateIDToken(ctx, lifespan, ar)
if err != nil {
return err
}
resp.AddParameter("id_token", token)
return nil
}
func (i *IDTokenHandleHelper) IssueExplicitIDToken(ctx context.Context, lifespan time.Duration, ar fosite.Requester, resp fosite.AccessResponder) error {
token, err := i.generateIDToken(ctx, lifespan, ar)
if err != nil {
return err
}
resp.SetExtra("id_token", token)
return nil
}
// ComputeHash computes the hash using the alg defined in the id_token header
func (i *IDTokenHandleHelper) ComputeHash(ctx context.Context, sess Session, token string) (string, error) {
var err error
hash := sha256.New()
if alg, ok := sess.IDTokenHeaders().Get("alg").(string); ok && len(alg) > 2 {
if hashSize, err := strconv.Atoi(alg[2:]); err == nil {
if hashSize == 384 {
hash = sha512.New384()
} else if hashSize == 512 {
hash = sha512.New()
}
}
}
buffer := bytes.NewBufferString(token)
_, err = hash.Write(buffer.Bytes())
if err != nil {
return "", err
}
hashBuf := bytes.NewBuffer(hash.Sum([]byte{}))
return base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:hashBuf.Len()/2]), nil
}