-
Notifications
You must be signed in to change notification settings - Fork 15
/
storage.go
648 lines (590 loc) · 22.9 KB
/
storage.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
package storage
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/binary"
"fmt"
"math/big"
"sync"
"time"
"unsafe"
"github.com/google/uuid"
"gopkg.in/square/go-jose.v2"
"github.com/zitadel/oidc/pkg/oidc"
"github.com/zitadel/oidc/pkg/op"
)
// serviceKey1 is a public key which will be used for the JWT Profile Authorization Grant
// the corresponding private key is in the service-key1.json (for demonstration purposes)
var serviceKey1 = &rsa.PublicKey{
N: func() *big.Int {
n, _ := new(big.Int).SetString("00f6d44fb5f34ac2033a75e73cb65ff24e6181edc58845e75a560ac21378284977bb055b1a75b714874e2a2641806205681c09abec76efd52cf40984edcf4c8ca09717355d11ac338f280d3e4c905b00543bdb8ee5a417496cb50cb0e29afc5a0d0471fd5a2fa625bd5281f61e6b02067d4fe7a5349eeae6d6a4300bcd86eef331", 16)
return n
}(),
E: 65537,
}
// var _ op.Storage = &storage{}
// var _ op.ClientCredentialsStorage = &storage{}
// Storage implements the op.Storage interface
// typically you would implement this as a layer on top of your database
// for simplicity this example keeps everything in-memory
type Storage struct {
lock sync.Mutex
authRequests map[string]*AuthRequest
codes map[string]string
tokens map[string]*Token
clients map[string]*Client
userStore UserStore
services map[string]Service
refreshTokens map[string]*RefreshToken
signingKey signingKey
}
type signingKey struct {
ID string
Algorithm string
Key *rsa.PrivateKey
}
func IntToByteArray(num int64) []byte {
size := int(unsafe.Sizeof(num))
arr := make([]byte, size)
for i := 0; i < size; i++ {
byt := *(*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(&num)) + uintptr(i)))
arr[i] = byt
}
return arr
}
func NewStorage(userStore UserStore) *Storage {
key, _ := rsa.GenerateKey(rand.Reader, 2048)
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.LittleEndian, IntToByteArray(int64(key.E)))
if err != nil {
panic(err)
}
err = binary.Write(buf, binary.LittleEndian, key.N.Bytes())
if err != nil {
panic(err)
}
sha1Sum := sha1.Sum(buf.Bytes())
kid := fmt.Sprintf("%x", sha1Sum)
return &Storage{
authRequests: make(map[string]*AuthRequest),
codes: make(map[string]string),
tokens: make(map[string]*Token),
refreshTokens: make(map[string]*RefreshToken),
clients: clients,
userStore: userStore,
services: map[string]Service{
userStore.ExampleClientID(): {
keys: map[string]*rsa.PublicKey{
"key1": serviceKey1,
},
},
},
signingKey: signingKey{
ID: kid,
Algorithm: "RS256",
Key: key,
},
}
}
func (s *Storage) ClientCredentialsTokenRequest(ctx context.Context, clientID string, scopes []string) (op.TokenRequest, error) {
client, err := s.GetClientByClientID(ctx, clientID)
if err != nil {
return nil, err
}
for _, scope := range scopes {
if scope == oidc.ScopeOpenID {
continue
}
if !client.IsScopeAllowed(scope) {
return nil, fmt.Errorf("scope %s is not allowed for client", scope)
}
}
tokenRequest := &oidc.JWTTokenRequest{
Issuer: "",
Subject: clientID,
Scopes: scopes,
Audience: []string{
clientID,
"openziti",
},
IssuedAt: oidc.Time(time.Now()),
ExpiresAt: oidc.Time(time.Now().Add(30 * time.Minute)),
}
return tokenRequest, nil
}
// CheckUsernamePassword implements the `authenticate` interface of the login
func (s *Storage) CheckUsernamePassword(username, password, id string) (*interface{}, error) {
s.lock.Lock()
defer s.lock.Unlock()
request, ok := s.authRequests[id]
if !ok {
return nil, fmt.Errorf("request not found")
}
// for demonstration purposes we'll check we'll have a simple user store and
// a plain text password. For real world scenarios, be sure to have the password
// hashed and salted (e.g. using bcrypt)
user := s.userStore.GetUserByUsername(username)
if user != nil && user.Password == password {
// be sure to set user id into the auth request after the user was checked,
// so that you'll be able to get more information about the user after the login
request.UserID = user.ID
// you will have to change some state on the request to guide the user through possible multiple steps of the login process
// in this example we'll simply check the username / password and set a boolean to true
// therefore we will also just check this boolean if the request / login has been finished
request.passwordChecked = true
return nil, nil
}
return nil, fmt.Errorf("username or password wrong")
}
// CreateAuthRequest implements the op.Storage interface
// it will be called after parsing and validation of the authentication request
func (s *Storage) CreateAuthRequest(ctx context.Context, authReq *oidc.AuthRequest, userID string) (op.AuthRequest, error) {
s.lock.Lock()
defer s.lock.Unlock()
// typically, you'll fill your storage / storage model with the information of the passed object
request := authRequestToInternal(authReq, userID)
// you'll also have to create a unique id for the request (this might be done by your database; we'll use a uuid)
request.ID = uuid.NewString()
// and save it in your database (for demonstration purposed we will use a simple map)
s.authRequests[request.ID] = request
// finally, return the request (which implements the AuthRequest interface of the OP
return request, nil
}
// AuthRequestByID implements the op.Storage interface
// it will be called after the Login UI redirects back to the OIDC endpoint
func (s *Storage) AuthRequestByID(ctx context.Context, id string) (op.AuthRequest, error) {
s.lock.Lock()
defer s.lock.Unlock()
request, ok := s.authRequests[id]
if !ok {
return nil, fmt.Errorf("request not found")
}
return request, nil
}
// AuthRequestByCode implements the op.Storage interface
// it will be called after parsing and validation of the token request (in an authorization code flow)
func (s *Storage) AuthRequestByCode(ctx context.Context, code string) (op.AuthRequest, error) {
// for this example we read the id by code and then get the request by id
requestID, ok := func() (string, bool) {
s.lock.Lock()
defer s.lock.Unlock()
requestID, ok := s.codes[code]
return requestID, ok
}()
if !ok {
return nil, fmt.Errorf("code invalid or expired")
}
return s.AuthRequestByID(ctx, requestID)
}
// SaveAuthCode implements the op.Storage interface
// it will be called after the authentication has been successful and before redirecting the user agent to the redirect_uri
// (in an authorization code flow)
func (s *Storage) SaveAuthCode(ctx context.Context, id string, code string) error {
// for this example we'll just save the authRequestID to the code
s.lock.Lock()
defer s.lock.Unlock()
s.codes[code] = id
return nil
}
// DeleteAuthRequest implements the op.Storage interface
// it will be called after creating the token response (id and access tokens) for a valid
// - authentication request (in an implicit flow)
// - token request (in an authorization code flow)
func (s *Storage) DeleteAuthRequest(ctx context.Context, id string) error {
// you can simply delete all reference to the auth request
s.lock.Lock()
defer s.lock.Unlock()
delete(s.authRequests, id)
for code, requestID := range s.codes {
if id == requestID {
delete(s.codes, code)
return nil
}
}
return nil
}
// CreateAccessToken implements the op.Storage interface
// it will be called for all requests able to return an access token (Authorization Code Flow, Implicit Flow, JWT Profile, ...)
func (s *Storage) CreateAccessToken(ctx context.Context, request op.TokenRequest) (string, time.Time, error) {
var applicationID string
// if authenticated for an app (auth code / implicit flow) we must save the client_id to the token
authReq, ok := request.(*AuthRequest)
if ok {
applicationID = authReq.ApplicationID
}
token, err := s.accessToken(applicationID, "", request.GetSubject(), request.GetAudience(), request.GetScopes())
if err != nil {
return "", time.Time{}, err
}
return token.ID, token.Expiration, nil
}
// CreateAccessAndRefreshTokens implements the op.Storage interface
// it will be called for all requests able to return an access and refresh token (Authorization Code Flow, Refresh Token Request)
func (s *Storage) CreateAccessAndRefreshTokens(ctx context.Context, request op.TokenRequest, currentRefreshToken string) (accessTokenID string, newRefreshToken string, expiration time.Time, err error) {
// get the information depending on the request type / implementation
applicationID, authTime, amr := getInfoFromRequest(request)
// if currentRefreshToken is empty (Code Flow) we will have to create a new refresh token
if currentRefreshToken == "" {
refreshTokenID := uuid.NewString()
accessToken, err := s.accessToken(applicationID, refreshTokenID, request.GetSubject(), request.GetAudience(), request.GetScopes())
if err != nil {
return "", "", time.Time{}, err
}
refreshToken, err := s.createRefreshToken(accessToken, amr, authTime)
if err != nil {
return "", "", time.Time{}, err
}
return accessToken.ID, refreshToken, accessToken.Expiration, nil
}
// if we get here, the currentRefreshToken was not empty, so the call is a refresh token request
// we therefore will have to check the currentRefreshToken and renew the refresh token
refreshToken, refreshTokenID, err := s.renewRefreshToken(currentRefreshToken)
if err != nil {
return "", "", time.Time{}, err
}
accessToken, err := s.accessToken(applicationID, refreshTokenID, request.GetSubject(), request.GetAudience(), request.GetScopes())
if err != nil {
return "", "", time.Time{}, err
}
return accessToken.ID, refreshToken, accessToken.Expiration, nil
}
// TokenRequestByRefreshToken implements the op.Storage interface
// it will be called after parsing and validation of the refresh token request
func (s *Storage) TokenRequestByRefreshToken(ctx context.Context, refreshToken string) (op.RefreshTokenRequest, error) {
s.lock.Lock()
defer s.lock.Unlock()
token, ok := s.refreshTokens[refreshToken]
if !ok {
return nil, fmt.Errorf("invalid refresh_token")
}
return RefreshTokenRequestFromBusiness(token), nil
}
// TerminateSession implements the op.Storage interface
// it will be called after the user signed out, therefore the access and refresh token of the user of this client must be removed
func (s *Storage) TerminateSession(ctx context.Context, userID string, clientID string) error {
s.lock.Lock()
defer s.lock.Unlock()
for _, token := range s.tokens {
if token.ApplicationID == clientID && token.Subject == userID {
delete(s.tokens, token.ID)
delete(s.refreshTokens, token.RefreshTokenID)
}
}
return nil
}
// RevokeToken implements the op.Storage interface
// it will be called after parsing and validation of the token revocation request
func (s *Storage) RevokeToken(ctx context.Context, tokenIDOrToken string, userID string, clientID string) *oidc.Error {
// a single token was requested to be removed
s.lock.Lock()
defer s.lock.Unlock()
accessToken, ok := s.tokens[tokenIDOrToken] // tokenID
if ok {
if accessToken.ApplicationID != clientID {
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client")
}
// if it is an access token, just remove it
// you could also remove the corresponding refresh token if really necessary
delete(s.tokens, accessToken.ID)
return nil
}
refreshToken, ok := s.refreshTokens[tokenIDOrToken] // token
if !ok {
// if the token is neither an access nor a refresh token, just ignore it, the expected behaviour of
// being not valid (anymore) is achieved
return nil
}
if refreshToken.ApplicationID != clientID {
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client")
}
// if it is a refresh token, you will have to remove the access token as well
delete(s.refreshTokens, refreshToken.ID)
for _, accessToken := range s.tokens {
if accessToken.RefreshTokenID == refreshToken.ID {
delete(s.tokens, accessToken.ID)
return nil
}
}
return nil
}
// GetSigningKey implements the op.Storage interface
// it will be called when creating the OpenID Provider
func (s *Storage) GetSigningKey(ctx context.Context, keyCh chan<- jose.SigningKey) {
// in this example the signing key is a static rsa.PrivateKey and the algorithm used is RS256
// you would obviously have a more complex implementation and store / retrieve the key from your database as well
//
// the idea of the signing key channel is, that you can (with what ever mechanism) rotate your signing key and
// switch the key of the signer via this channel
keyCh <- jose.SigningKey{
Algorithm: jose.SignatureAlgorithm(s.signingKey.Algorithm), // always tell the signer with algorithm to use
Key: jose.JSONWebKey{
KeyID: s.signingKey.ID, // always give the key an id so, that it will include it in the token header as `kid` claim
Key: s.signingKey.Key,
},
}
}
// GetKeySet implements the op.Storage interface
// it will be called to get the current (public) keys, among others for the keys_endpoint or for validating access_tokens on the userinfo_endpoint, ...
func (s *Storage) GetKeySet(ctx context.Context) (*jose.JSONWebKeySet, error) {
// as mentioned above, this example only has a single signing key without key rotation,
// so it will directly use its public key
//
// when using key rotation you typically would store the public keys alongside the private keys in your database
// and give both of them an expiration date, with the public key having a longer lifetime (e.g. rotate private key every
return &jose.JSONWebKeySet{
Keys: []jose.JSONWebKey{
{
KeyID: s.signingKey.ID,
Algorithm: s.signingKey.Algorithm,
Use: oidc.KeyUseSignature,
Key: &s.signingKey.Key.PublicKey,
},
},
}, nil
}
// GetClientByClientID implements the op.Storage interface
// it will be called whenever information (type, redirect_uris, ...) about the client behind the client_id is needed
func (s *Storage) GetClientByClientID(ctx context.Context, clientID string) (op.Client, error) {
s.lock.Lock()
defer s.lock.Unlock()
client, ok := s.clients[clientID]
if !ok {
return nil, fmt.Errorf("client not found")
}
return client, nil
}
// AuthorizeClientIDSecret implements the op.Storage interface
// it will be called for validating the client_id, client_secret on token or introspection requests
func (s *Storage) AuthorizeClientIDSecret(ctx context.Context, clientID, clientSecret string) error {
s.lock.Lock()
defer s.lock.Unlock()
client, ok := s.clients[clientID]
if !ok {
return fmt.Errorf("client not found")
}
// for this example we directly check the secret
// obviously you would not have the secret in plain text, but rather hashed and salted (e.g. using bcrypt)
if client.secret != clientSecret {
return fmt.Errorf("invalid secret")
}
return nil
}
// SetUserinfoFromScopes implements the op.Storage interface
// it will be called for the creation of an id_token, so we'll just pass it to the private function without any further check
func (s *Storage) SetUserinfoFromScopes(ctx context.Context, userinfo oidc.UserInfoSetter, userID, clientID string, scopes []string) error {
return s.setUserinfo(ctx, userinfo, userID, clientID, scopes)
}
// SetUserinfoFromToken implements the op.Storage interface
// it will be called for the userinfo endpoint, so we read the token and pass the information from that to the private function
func (s *Storage) SetUserinfoFromToken(ctx context.Context, userinfo oidc.UserInfoSetter, tokenID, subject, origin string) error {
token, ok := func() (*Token, bool) {
s.lock.Lock()
defer s.lock.Unlock()
token, ok := s.tokens[tokenID]
return token, ok
}()
if !ok {
return fmt.Errorf("token is invalid or has expired")
}
// the userinfo endpoint should support CORS. If it's not possible to specify a specific origin in the CORS handler,
// and you have to specify a wildcard (*) origin, then you could also check here if the origin which called the userinfo endpoint here directly
// note that the origin can be empty (if called by a web client)
//
// if origin != "" {
// client, ok := s.clients[token.ApplicationID]
// if !ok {
// return fmt.Errorf("client not found")
// }
// if err := checkAllowedOrigins(client.allowedOrigins, origin); err != nil {
// return err
// }
//}
return s.setUserinfo(ctx, userinfo, token.Subject, token.ApplicationID, token.Scopes)
}
// SetIntrospectionFromToken implements the op.Storage interface
// it will be called for the introspection endpoint, so we read the token and pass the information from that to the private function
func (s *Storage) SetIntrospectionFromToken(ctx context.Context, introspection oidc.IntrospectionResponse, tokenID, subject, clientID string) error {
token, ok := func() (*Token, bool) {
s.lock.Lock()
defer s.lock.Unlock()
token, ok := s.tokens[tokenID]
return token, ok
}()
if !ok {
return fmt.Errorf("token is invalid or has expired")
}
// check if the client is part of the requested audience
for _, aud := range token.Audience {
if aud == clientID {
// the introspection response only has to return a boolean (active) if the token is active
// this will automatically be done by the library if you don't return an error
// you can also return further information about the user / associated token
// e.g. the userinfo (equivalent to userinfo endpoint)
err := s.setUserinfo(ctx, introspection, subject, clientID, token.Scopes)
if err != nil {
return err
}
//...and also the requested scopes...
introspection.SetScopes(token.Scopes)
//...and the client the token was issued to
introspection.SetClientID(token.ApplicationID)
return nil
}
}
return fmt.Errorf("token is not valid for this client")
}
// GetPrivateClaimsFromScopes implements the op.Storage interface
// it will be called for the creation of a JWT access token to assert claims for custom scopes
func (s *Storage) GetPrivateClaimsFromScopes(ctx context.Context, userID, clientID string, scopes []string) (claims map[string]interface{}, err error) {
for _, scope := range scopes {
switch scope {
case CustomScope:
claims = appendClaim(claims, CustomClaim, customClaim(clientID))
}
}
return claims, nil
}
// GetKeyByIDAndUserID implements the op.Storage interface
// it will be called to validate the signatures of a JWT (JWT Profile Grant and Authentication)
func (s *Storage) GetKeyByIDAndUserID(ctx context.Context, keyID, clientID string) (*jose.JSONWebKey, error) {
s.lock.Lock()
defer s.lock.Unlock()
service, ok := s.services[clientID]
if !ok {
return nil, fmt.Errorf("clientID not found")
}
key, ok := service.keys[keyID]
if !ok {
return nil, fmt.Errorf("key not found")
}
return &jose.JSONWebKey{
KeyID: keyID,
Use: "sig",
Key: key,
}, nil
}
// ValidateJWTProfileScopes implements the op.Storage interface
// it will be called to validate the scopes of a JWT Profile Authorization Grant request
func (s *Storage) ValidateJWTProfileScopes(ctx context.Context, userID string, scopes []string) ([]string, error) {
allowedScopes := make([]string, 0)
for _, scope := range scopes {
if scope == oidc.ScopeOpenID {
allowedScopes = append(allowedScopes, scope)
}
}
return allowedScopes, nil
}
// Health implements the op.Storage interface
func (s *Storage) Health(ctx context.Context) error {
return nil
}
// createRefreshToken will store a refresh_token in-memory based on the provided information
func (s *Storage) createRefreshToken(accessToken *Token, amr []string, authTime time.Time) (string, error) {
s.lock.Lock()
defer s.lock.Unlock()
token := &RefreshToken{
ID: accessToken.RefreshTokenID,
Token: accessToken.RefreshTokenID,
AuthTime: authTime,
AMR: amr,
ApplicationID: accessToken.ApplicationID,
UserID: accessToken.Subject,
Audience: accessToken.Audience,
Expiration: time.Now().Add(5 * time.Hour),
Scopes: accessToken.Scopes,
}
s.refreshTokens[token.ID] = token
return token.Token, nil
}
// renewRefreshToken checks the provided refresh_token and creates a new one based on the current
func (s *Storage) renewRefreshToken(currentRefreshToken string) (string, string, error) {
s.lock.Lock()
defer s.lock.Unlock()
refreshToken, ok := s.refreshTokens[currentRefreshToken]
if !ok {
return "", "", fmt.Errorf("invalid refresh token")
}
// deletes the refresh token and all access tokens which were issued based on this refresh token
delete(s.refreshTokens, currentRefreshToken)
for _, token := range s.tokens {
if token.RefreshTokenID == currentRefreshToken {
delete(s.tokens, token.ID)
break
}
}
// creates a new refresh token based on the current one
token := uuid.NewString()
refreshToken.Token = token
refreshToken.ID = token
s.refreshTokens[token] = refreshToken
return token, refreshToken.ID, nil
}
// accessToken will store an access_token in-memory based on the provided information
func (s *Storage) accessToken(applicationID, refreshTokenID, subject string, audience, scopes []string) (*Token, error) {
s.lock.Lock()
defer s.lock.Unlock()
token := &Token{
ID: uuid.NewString(),
ApplicationID: applicationID,
RefreshTokenID: refreshTokenID,
Subject: subject,
Audience: audience,
Expiration: time.Now().Add(5 * time.Minute),
Scopes: scopes,
}
s.tokens[token.ID] = token
return token, nil
}
// setUserinfo sets the info based on the user, scopes and if necessary the clientID
func (s *Storage) setUserinfo(ctx context.Context, userInfo oidc.UserInfoSetter, userID, clientID string, scopes []string) (err error) {
s.lock.Lock()
defer s.lock.Unlock()
user := s.userStore.GetUserByID(userID)
if user == nil {
return fmt.Errorf("user not found")
}
for _, scope := range scopes {
switch scope {
case oidc.ScopeOpenID:
userInfo.SetSubject(user.ID)
case oidc.ScopeProfile:
userInfo.SetPreferredUsername(user.Username)
userInfo.SetName(user.FirstName + " " + user.LastName)
userInfo.SetFamilyName(user.LastName)
userInfo.SetGivenName(user.FirstName)
case CustomScope:
// you can also have a custom scope and assert public or custom claims based on that
userInfo.AppendClaims(CustomClaim, customClaim(clientID))
}
}
return nil
}
// getInfoFromRequest returns the clientID, authTime and amr depending on the op.TokenRequest type / implementation
func getInfoFromRequest(req op.TokenRequest) (clientID string, authTime time.Time, amr []string) {
authReq, ok := req.(*AuthRequest) // Code Flow (with scope offline_access)
if ok {
return authReq.ApplicationID, authReq.authTime, authReq.GetAMR()
}
refreshReq, ok := req.(*RefreshTokenRequest) // Refresh Token Request
if ok {
return refreshReq.ApplicationID, refreshReq.AuthTime, refreshReq.AMR
}
return "", time.Time{}, nil
}
// customClaim demonstrates how to return custom claims based on provided information
func customClaim(clientID string) map[string]interface{} {
return map[string]interface{}{
"client": clientID,
"other": "stuff",
}
}
func appendClaim(claims map[string]interface{}, claim string, value interface{}) map[string]interface{} {
if claims == nil {
claims = make(map[string]interface{})
}
claims[claim] = value
return claims
}