-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgranttype_jwtbearer_exchange.go
55 lines (53 loc) · 1.88 KB
/
granttype_jwtbearer_exchange.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
package oidc
import (
"context"
"encoding/json"
"github.com/go-jose/go-jose/v3"
"github.com/google/uuid"
"github.com/xslasd/x-oidc/constant"
"github.com/xslasd/x-oidc/model"
"github.com/xslasd/x-oidc/storage"
"github.com/xslasd/x-oidc/util"
"strings"
"time"
)
func (o *OpenIDProvider) jwtBearerExchange(ctx context.Context, req *TokenExchangeReq) (*model.AccessTokenRes, error) {
jws, err := jose.ParseSigned(req.Assertion)
if err != nil {
return nil, err
}
payload := jws.UnsafePayloadWithoutVerification()
claims := new(model.JWTClientTokenClaims)
err = json.Unmarshal(payload, claims)
client, err := o.cfg.Storage.GetClientByClientID(ctx, claims.Issuer)
if err != nil {
return nil, err
}
_, err = jws.Verify(client.JoseVerificationKey(constant.JWTAssertion))
if err != nil {
return nil, err
}
authReq, err := o.cfg.Storage.AuthRequestByJWTClientToken(ctx, client, *claims)
if err != nil {
return nil, err
}
return o.CreateAccessTokenAndIDToken(ctx, authReq, client, func() (*storage.TokenModel, error) {
createRefreshToken := false
if util.ArrayContains(authReq.Scopes, constant.ScopeOfflineAccess) && authReq.ResponseType == constant.ResponseTypeCode && util.ArrayContains(client.GrantTypes(), constant.GrantTypeRefreshToken) {
createRefreshToken = true
}
res := storage.TokenModel{
RequestID: authReq.RequestID,
TokenID: strings.ReplaceAll(uuid.NewString(), "-", ""),
UserID: authReq.UserID,
AccessTokenExpiration: time.Now().UTC().Add(client.AccessTokenLifetime()).Add(client.ClockSkew()),
AuthTime: time.Now().UTC(),
}
if createRefreshToken {
res.RefreshToken = strings.ReplaceAll(uuid.NewString(), "-", "")
res.RefreshTokenExpiration = time.Now().UTC().Add(client.RefreshTokenLifetime()).Add(client.ClockSkew())
}
err = o.cfg.Storage.SaveTokenModel(ctx, res)
return &res, err
})
}