-
Notifications
You must be signed in to change notification settings - Fork 0
/
granttype_client_credentials_exchange.go
71 lines (69 loc) · 2.04 KB
/
granttype_client_credentials_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package oidc
import (
"context"
"github.com/google/uuid"
"github.com/xslasd/x-oidc/constant"
"github.com/xslasd/x-oidc/ecode"
"github.com/xslasd/x-oidc/model"
"github.com/xslasd/x-oidc/storage"
"github.com/xslasd/x-oidc/util"
"strings"
"time"
)
func (o *OpenIDProvider) clientCredentialsExchange(ctx context.Context, req *TokenExchangeReq) (*model.AccessTokenRes, error) {
client, err := o.cfg.Storage.GetClientByClientID(ctx, req.ClientID)
if err != nil {
return nil, err
}
if client.GetClientSecret() != req.ClientSecret {
return nil, ecode.ClientIDOrSecretInvalid
}
if !util.ArrayContains(client.GrantTypes(), constant.GrantTypeClientCredentials) {
return nil, ecode.UnauthorizedClientGrantType
}
scopes := req.unmarshalScopes()
var unScopes string
for _, scope := range scopes {
if !util.ArrayContains(client.Scopes(), scope) {
if unScopes == "" {
unScopes = scope
} else {
unScopes += "," + scope
}
}
}
if unScopes != "" {
return nil, ecode.ScopesInvalid.SetDescriptionf(unScopes)
}
authReq := storage.AuthRequest{
RequestID: uuid.NewString(),
Scopes: scopes,
ResponseType: constant.ResponseTypeToken,
ClientID: req.ClientID,
RedirectURI: req.RedirectURI,
}
err = o.cfg.Storage.SaveAuthRequest(ctx, authReq)
if err != nil {
return nil, err
}
accessToken, newRefreshToken, validity, err := o.CreateAccessToken(ctx, &authReq, client, func() (*storage.TokenModel, error) {
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(),
}
err = o.cfg.Storage.SaveTokenModel(ctx, res)
return &res, err
})
if err != nil {
return nil, err
}
return &model.AccessTokenRes{
AccessToken: accessToken,
TokenType: client.AccessTokenTransferType(),
RefreshToken: newRefreshToken,
ExpiresIn: uint64(validity),
}, nil
}