| 1 |
package storage |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/rand" |
| 6 |
"crypto/rsa" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"math/big" |
| 10 |
"strings" |
| 11 |
"sync" |
| 12 |
"time" |
| 13 |
|
| 14 |
jose "github.com/go-jose/go-jose/v4" |
| 15 |
"github.com/google/uuid" |
| 16 |
|
| 17 |
"github.com/zitadel/oidc/v3/pkg/oidc" |
| 18 |
"github.com/zitadel/oidc/v3/pkg/op" |
| 19 |
) |
| 20 |
|
| 21 |
// serviceKey1 is a public key which will be used for the JWT Profile Authorization Grant |
| 22 |
// the corresponding private key is in the service-key1.pem (for demonstration purposes) |
| 23 |
var serviceKey1 = &rsa.PublicKey{ |
| 24 |
N: func() *big.Int { |
| 25 |
n, _ := new(big.Int).SetString("00f6d44fb5f34ac2033a75e73cb65ff24e6181edc58845e75a560ac21378284977bb055b1a75b714874e2a2641806205681c09abec76efd52cf40984edcf4c8ca09717355d11ac338f280d3e4c905b00543bdb8ee5a417496cb50cb0e29afc5a0d0471fd5a2fa625bd5281f61e6b02067d4fe7a5349eeae6d6a4300bcd86eef331", 16) |
| 26 |
return n |
| 27 |
}(), |
| 28 |
E: 65537, |
| 29 |
} |
| 30 |
|
| 31 |
var ( |
| 32 |
_ op.Storage = &Storage{} |
| 33 |
_ op.ClientCredentialsStorage = &Storage{} |
| 34 |
) |
| 35 |
|
| 36 |
// storage implements the op.Storage interface |
| 37 |
// typically you would implement this as a layer on top of your database |
| 38 |
// for simplicity this example keeps everything in-memory |
| 39 |
type Storage struct { |
| 40 |
lock sync.Mutex |
| 41 |
authRequests map[string]*AuthRequest |
| 42 |
codes map[string]string |
| 43 |
tokens map[string]*Token |
| 44 |
clients map[string]*Client |
| 45 |
userStore UserStore |
| 46 |
services map[string]Service |
| 47 |
refreshTokens map[string]*RefreshToken |
| 48 |
signingKey signingKey |
| 49 |
deviceCodes map[string]deviceAuthorizationEntry |
| 50 |
userCodes map[string]string |
| 51 |
serviceUsers map[string]*Client |
| 52 |
} |
| 53 |
|
| 54 |
type signingKey struct { |
| 55 |
id string |
| 56 |
algorithm jose.SignatureAlgorithm |
| 57 |
key *rsa.PrivateKey |
| 58 |
} |
| 59 |
|
| 60 |
func (s *signingKey) SignatureAlgorithm() jose.SignatureAlgorithm { |
| 61 |
return s.algorithm |
| 62 |
} |
| 63 |
|
| 64 |
func (s *signingKey) Key() any { |
| 65 |
return s.key |
| 66 |
} |
| 67 |
|
| 68 |
func (s *signingKey) ID() string { |
| 69 |
return s.id |
| 70 |
} |
| 71 |
|
| 72 |
type publicKey struct { |
| 73 |
signingKey |
| 74 |
} |
| 75 |
|
| 76 |
func (s *publicKey) ID() string { |
| 77 |
return s.id |
| 78 |
} |
| 79 |
|
| 80 |
func (s *publicKey) Algorithm() jose.SignatureAlgorithm { |
| 81 |
return s.algorithm |
| 82 |
} |
| 83 |
|
| 84 |
func (s *publicKey) Use() string { |
| 85 |
return "sig" |
| 86 |
} |
| 87 |
|
| 88 |
func (s *publicKey) Key() any { |
| 89 |
return &s.key.PublicKey |
| 90 |
} |
| 91 |
|
| 92 |
func NewStorage(userStore UserStore) *Storage { |
| 93 |
return NewStorageWithClients(userStore, clients) |
| 94 |
} |
| 95 |
|
| 96 |
func NewStorageWithClients(userStore UserStore, clients map[string]*Client) *Storage { |
| 97 |
key, _ := rsa.GenerateKey(rand.Reader, 2048) |
| 98 |
return &Storage{ |
| 99 |
authRequests: make(map[string]*AuthRequest), |
| 100 |
codes: make(map[string]string), |
| 101 |
tokens: make(map[string]*Token), |
| 102 |
refreshTokens: make(map[string]*RefreshToken), |
| 103 |
clients: clients, |
| 104 |
userStore: userStore, |
| 105 |
services: map[string]Service{ |
| 106 |
userStore.ExampleClientID(): { |
| 107 |
keys: map[string]*rsa.PublicKey{ |
| 108 |
ServiceUserKeyID: serviceKey1, |
| 109 |
}, |
| 110 |
}, |
| 111 |
}, |
| 112 |
signingKey: signingKey{ |
| 113 |
id: uuid.NewString(), |
| 114 |
algorithm: jose.RS256, |
| 115 |
key: key, |
| 116 |
}, |
| 117 |
deviceCodes: make(map[string]deviceAuthorizationEntry), |
| 118 |
userCodes: make(map[string]string), |
| 119 |
serviceUsers: map[string]*Client{ |
| 120 |
"sid1": { |
| 121 |
id: "sid1", |
| 122 |
secret: "verysecret", |
| 123 |
grantTypes: []oidc.GrantType{ |
| 124 |
oidc.GrantTypeClientCredentials, |
| 125 |
}, |
| 126 |
accessTokenType: op.AccessTokenTypeBearer, |
| 127 |
}, |
| 128 |
}, |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
// CheckUsernamePassword implements the `authenticate` interface of the login |
| 133 |
func (s *Storage) CheckUsernamePassword(username, password, id string) error { |
| 134 |
s.lock.Lock() |
| 135 |
defer s.lock.Unlock() |
| 136 |
request, ok := s.authRequests[id] |
| 137 |
if !ok { |
| 138 |
return fmt.Errorf("request not found") |
| 139 |
} |
| 140 |
|
| 141 |
// for demonstration purposes we'll check we'll have a simple user store and |
| 142 |
// a plain text password. For real world scenarios, be sure to have the password |
| 143 |
// hashed and salted (e.g. using bcrypt) |
| 144 |
user := s.userStore.GetUserByUsername(username) |
| 145 |
if user != nil && user.Password == password { |
| 146 |
// be sure to set user id into the auth request after the user was checked, |
| 147 |
// so that you'll be able to get more information about the user after the login |
| 148 |
request.UserID = user.ID |
| 149 |
|
| 150 |
// you will have to change some state on the request to guide the user through possible multiple steps of the login process |
| 151 |
// in this example we'll simply check the username / password and set a boolean to true |
| 152 |
// therefore we will also just check this boolean if the request / login has been finished |
| 153 |
request.done = true |
| 154 |
|
| 155 |
request.authTime = time.Now() |
| 156 |
|
| 157 |
return nil |
| 158 |
} |
| 159 |
return fmt.Errorf("username or password wrong") |
| 160 |
} |
| 161 |
|
| 162 |
func (s *Storage) CheckUsernamePasswordSimple(username, password string) error { |
| 163 |
s.lock.Lock() |
| 164 |
defer s.lock.Unlock() |
| 165 |
|
| 166 |
user := s.userStore.GetUserByUsername(username) |
| 167 |
if user != nil && user.Password == password { |
| 168 |
return nil |
| 169 |
} |
| 170 |
return fmt.Errorf("username or password wrong") |
| 171 |
} |
| 172 |
|
| 173 |
// CreateAuthRequest implements the op.Storage interface |
| 174 |
// it will be called after parsing and validation of the authentication request |
| 175 |
func (s *Storage) CreateAuthRequest(ctx context.Context, authReq *oidc.AuthRequest, userID string) (op.AuthRequest, error) { |
| 176 |
s.lock.Lock() |
| 177 |
defer s.lock.Unlock() |
| 178 |
|
| 179 |
if len(authReq.Prompt) == 1 && authReq.Prompt[0] == "none" { |
| 180 |
// With prompt=none, there is no way for the user to log in |
| 181 |
// so return error right away. |
| 182 |
return nil, oidc.ErrLoginRequired() |
| 183 |
} |
| 184 |
|
| 185 |
// typically, you'll fill your storage / storage model with the information of the passed object |
| 186 |
request := authRequestToInternal(authReq, userID) |
| 187 |
|
| 188 |
// you'll also have to create a unique id for the request (this might be done by your database; we'll use a UUID) |
| 189 |
request.ID = uuid.NewString() |
| 190 |
|
| 191 |
// and save it in your database (for demonstration purposed we will use a simple map) |
| 192 |
s.authRequests[request.ID] = request |
| 193 |
|
| 194 |
// finally, return the request (which implements the AuthRequest interface of the OP |
| 195 |
return request, nil |
| 196 |
} |
| 197 |
|
| 198 |
// AuthRequestByID implements the op.Storage interface |
| 199 |
// it will be called after the Login UI redirects back to the OIDC endpoint |
| 200 |
func (s *Storage) AuthRequestByID(ctx context.Context, id string) (op.AuthRequest, error) { |
| 201 |
s.lock.Lock() |
| 202 |
defer s.lock.Unlock() |
| 203 |
request, ok := s.authRequests[id] |
| 204 |
if !ok { |
| 205 |
return nil, fmt.Errorf("request not found") |
| 206 |
} |
| 207 |
return request, nil |
| 208 |
} |
| 209 |
|
| 210 |
// AuthRequestByCode implements the op.Storage interface |
| 211 |
// it will be called after parsing and validation of the token request (in an authorization code flow) |
| 212 |
func (s *Storage) AuthRequestByCode(ctx context.Context, code string) (op.AuthRequest, error) { |
| 213 |
// for this example we read the id by code and then get the request by id |
| 214 |
requestID, ok := func() (string, bool) { |
| 215 |
s.lock.Lock() |
| 216 |
defer s.lock.Unlock() |
| 217 |
requestID, ok := s.codes[code] |
| 218 |
return requestID, ok |
| 219 |
}() |
| 220 |
if !ok { |
| 221 |
return nil, fmt.Errorf("code invalid or expired") |
| 222 |
} |
| 223 |
return s.AuthRequestByID(ctx, requestID) |
| 224 |
} |
| 225 |
|
| 226 |
// SaveAuthCode implements the op.Storage interface |
| 227 |
// it will be called after the authentication has been successful and before redirecting the user agent to the redirect_uri |
| 228 |
// (in an authorization code flow) |
| 229 |
func (s *Storage) SaveAuthCode(ctx context.Context, id string, code string) error { |
| 230 |
// for this example we'll just save the authRequestID to the code |
| 231 |
s.lock.Lock() |
| 232 |
defer s.lock.Unlock() |
| 233 |
s.codes[code] = id |
| 234 |
return nil |
| 235 |
} |
| 236 |
|
| 237 |
// DeleteAuthRequest implements the op.Storage interface |
| 238 |
// it will be called after creating the token response (id and access tokens) for a valid |
| 239 |
// - authentication request (in an implicit flow) |
| 240 |
// - token request (in an authorization code flow) |
| 241 |
func (s *Storage) DeleteAuthRequest(ctx context.Context, id string) error { |
| 242 |
// you can simply delete all reference to the auth request |
| 243 |
s.lock.Lock() |
| 244 |
defer s.lock.Unlock() |
| 245 |
delete(s.authRequests, id) |
| 246 |
for code, requestID := range s.codes { |
| 247 |
if id == requestID { |
| 248 |
delete(s.codes, code) |
| 249 |
return nil |
| 250 |
} |
| 251 |
} |
| 252 |
return nil |
| 253 |
} |
| 254 |
|
| 255 |
// CreateAccessToken implements the op.Storage interface |
| 256 |
// it will be called for all requests able to return an access token (Authorization Code Flow, Implicit Flow, JWT Profile, ...) |
| 257 |
func (s *Storage) CreateAccessToken(ctx context.Context, request op.TokenRequest) (string, time.Time, error) { |
| 258 |
var applicationID string |
| 259 |
switch req := request.(type) { |
| 260 |
case *AuthRequest: |
| 261 |
// if authenticated for an app (auth code / implicit flow) we must save the client_id to the token |
| 262 |
applicationID = req.ApplicationID |
| 263 |
case op.TokenExchangeRequest: |
| 264 |
applicationID = req.GetClientID() |
| 265 |
} |
| 266 |
|
| 267 |
token, err := s.accessToken(applicationID, "", request.GetSubject(), request.GetAudience(), request.GetScopes()) |
| 268 |
if err != nil { |
| 269 |
return "", time.Time{}, err |
| 270 |
} |
| 271 |
return token.ID, token.Expiration, nil |
| 272 |
} |
| 273 |
|
| 274 |
// CreateAccessAndRefreshTokens implements the op.Storage interface |
| 275 |
// it will be called for all requests able to return an access and refresh token (Authorization Code Flow, Refresh Token Request) |
| 276 |
func (s *Storage) CreateAccessAndRefreshTokens(ctx context.Context, request op.TokenRequest, currentRefreshToken string) (accessTokenID string, newRefreshToken string, expiration time.Time, err error) { |
| 277 |
// generate tokens via token exchange flow if request is relevant |
| 278 |
if teReq, ok := request.(op.TokenExchangeRequest); ok { |
| 279 |
return s.exchangeRefreshToken(ctx, teReq) |
| 280 |
} |
| 281 |
|
| 282 |
// get the information depending on the request type / implementation |
| 283 |
applicationID, authTime, amr := getInfoFromRequest(request) |
| 284 |
|
| 285 |
// if currentRefreshToken is empty (Code Flow) we will have to create a new refresh token |
| 286 |
if currentRefreshToken == "" { |
| 287 |
refreshTokenID := uuid.NewString() |
| 288 |
accessToken, err := s.accessToken(applicationID, refreshTokenID, request.GetSubject(), request.GetAudience(), request.GetScopes()) |
| 289 |
if err != nil { |
| 290 |
return "", "", time.Time{}, err |
| 291 |
} |
| 292 |
refreshToken, err := s.createRefreshToken(accessToken, amr, authTime) |
| 293 |
if err != nil { |
| 294 |
return "", "", time.Time{}, err |
| 295 |
} |
| 296 |
return accessToken.ID, refreshToken, accessToken.Expiration, nil |
| 297 |
} |
| 298 |
|
| 299 |
// if we get here, the currentRefreshToken was not empty, so the call is a refresh token request |
| 300 |
// we therefore will have to check the currentRefreshToken and renew the refresh token |
| 301 |
|
| 302 |
newRefreshToken = uuid.NewString() |
| 303 |
|
| 304 |
accessToken, err := s.accessToken(applicationID, newRefreshToken, request.GetSubject(), request.GetAudience(), request.GetScopes()) |
| 305 |
if err != nil { |
| 306 |
return "", "", time.Time{}, err |
| 307 |
} |
| 308 |
|
| 309 |
if err := s.renewRefreshToken(currentRefreshToken, newRefreshToken, accessToken.ID); err != nil { |
| 310 |
return "", "", time.Time{}, err |
| 311 |
} |
| 312 |
|
| 313 |
return accessToken.ID, newRefreshToken, accessToken.Expiration, nil |
| 314 |
} |
| 315 |
|
| 316 |
func (s *Storage) exchangeRefreshToken(ctx context.Context, request op.TokenExchangeRequest) (accessTokenID string, newRefreshToken string, expiration time.Time, err error) { |
| 317 |
applicationID := request.GetClientID() |
| 318 |
authTime := request.GetAuthTime() |
| 319 |
|
| 320 |
refreshTokenID := uuid.NewString() |
| 321 |
accessToken, err := s.accessToken(applicationID, refreshTokenID, request.GetSubject(), request.GetAudience(), request.GetScopes()) |
| 322 |
if err != nil { |
| 323 |
return "", "", time.Time{}, err |
| 324 |
} |
| 325 |
|
| 326 |
refreshToken, err := s.createRefreshToken(accessToken, nil, authTime) |
| 327 |
if err != nil { |
| 328 |
return "", "", time.Time{}, err |
| 329 |
} |
| 330 |
|
| 331 |
return accessToken.ID, refreshToken, accessToken.Expiration, nil |
| 332 |
} |
| 333 |
|
| 334 |
// TokenRequestByRefreshToken implements the op.Storage interface |
| 335 |
// it will be called after parsing and validation of the refresh token request |
| 336 |
func (s *Storage) TokenRequestByRefreshToken(ctx context.Context, refreshToken string) (op.RefreshTokenRequest, error) { |
| 337 |
s.lock.Lock() |
| 338 |
defer s.lock.Unlock() |
| 339 |
token, ok := s.refreshTokens[refreshToken] |
| 340 |
if !ok { |
| 341 |
return nil, fmt.Errorf("invalid refresh_token") |
| 342 |
} |
| 343 |
return RefreshTokenRequestFromBusiness(token), nil |
| 344 |
} |
| 345 |
|
| 346 |
// TerminateSession implements the op.Storage interface |
| 347 |
// it will be called after the user signed out, therefore the access and refresh token of the user of this client must be removed |
| 348 |
func (s *Storage) TerminateSession(ctx context.Context, userID string, clientID string) error { |
| 349 |
s.lock.Lock() |
| 350 |
defer s.lock.Unlock() |
| 351 |
for _, token := range s.tokens { |
| 352 |
if token.ApplicationID == clientID && token.Subject == userID { |
| 353 |
delete(s.tokens, token.ID) |
| 354 |
delete(s.refreshTokens, token.RefreshTokenID) |
| 355 |
} |
| 356 |
} |
| 357 |
return nil |
| 358 |
} |
| 359 |
|
| 360 |
// GetRefreshTokenInfo looks up a refresh token and returns the token id and user id. |
| 361 |
// If given something that is not a refresh token, it must return error. |
| 362 |
func (s *Storage) GetRefreshTokenInfo(ctx context.Context, clientID string, token string) (userID string, tokenID string, err error) { |
| 363 |
refreshToken, ok := s.refreshTokens[token] |
| 364 |
if !ok { |
| 365 |
return "", "", op.ErrInvalidRefreshToken |
| 366 |
} |
| 367 |
return refreshToken.UserID, refreshToken.ID, nil |
| 368 |
} |
| 369 |
|
| 370 |
// RevokeToken implements the op.Storage interface |
| 371 |
// it will be called after parsing and validation of the token revocation request |
| 372 |
func (s *Storage) RevokeToken(ctx context.Context, tokenIDOrToken string, userID string, clientID string) *oidc.Error { |
| 373 |
// a single token was requested to be removed |
| 374 |
s.lock.Lock() |
| 375 |
defer s.lock.Unlock() |
| 376 |
accessToken, ok := s.tokens[tokenIDOrToken] // tokenID |
| 377 |
if ok { |
| 378 |
if accessToken.ApplicationID != clientID { |
| 379 |
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client") |
| 380 |
} |
| 381 |
// if it is an access token, just remove it |
| 382 |
// you could also remove the corresponding refresh token if really necessary |
| 383 |
delete(s.tokens, accessToken.ID) |
| 384 |
return nil |
| 385 |
} |
| 386 |
refreshToken, ok := s.refreshTokens[tokenIDOrToken] // token |
| 387 |
if !ok { |
| 388 |
// if the token is neither an access nor a refresh token, just ignore it, the expected behaviour of |
| 389 |
// being not valid (anymore) is achieved |
| 390 |
return nil |
| 391 |
} |
| 392 |
if refreshToken.ApplicationID != clientID { |
| 393 |
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client") |
| 394 |
} |
| 395 |
delete(s.refreshTokens, refreshToken.ID) |
| 396 |
// if it is a refresh token, you will have to remove the access token as well |
| 397 |
delete(s.tokens, refreshToken.AccessToken) |
| 398 |
return nil |
| 399 |
} |
| 400 |
|
| 401 |
// SigningKey implements the op.Storage interface |
| 402 |
// it will be called when creating the OpenID Provider |
| 403 |
func (s *Storage) SigningKey(ctx context.Context) (op.SigningKey, error) { |
| 404 |
// in this example the signing key is a static rsa.PrivateKey and the algorithm used is RS256 |
| 405 |
// you would obviously have a more complex implementation and store / retrieve the key from your database as well |
| 406 |
return &s.signingKey, nil |
| 407 |
} |
| 408 |
|
| 409 |
// SignatureAlgorithms implements the op.Storage interface |
| 410 |
// it will be called to get the sign |
| 411 |
func (s *Storage) SignatureAlgorithms(context.Context) ([]jose.SignatureAlgorithm, error) { |
| 412 |
return []jose.SignatureAlgorithm{s.signingKey.algorithm}, nil |
| 413 |
} |
| 414 |
|
| 415 |
// KeySet implements the op.Storage interface |
| 416 |
// 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, ... |
| 417 |
func (s *Storage) KeySet(ctx context.Context) ([]op.Key, error) { |
| 418 |
// as mentioned above, this example only has a single signing key without key rotation, |
| 419 |
// so it will directly use its public key |
| 420 |
// |
| 421 |
// when using key rotation you typically would store the public keys alongside the private keys in your database |
| 422 |
// and give both of them an expiration date, with the public key having a longer lifetime |
| 423 |
return []op.Key{&publicKey{s.signingKey}}, nil |
| 424 |
} |
| 425 |
|
| 426 |
// GetClientByClientID implements the op.Storage interface |
| 427 |
// it will be called whenever information (type, redirect_uris, ...) about the client behind the client_id is needed |
| 428 |
func (s *Storage) GetClientByClientID(ctx context.Context, clientID string) (op.Client, error) { |
| 429 |
s.lock.Lock() |
| 430 |
defer s.lock.Unlock() |
| 431 |
client, ok := s.clients[clientID] |
| 432 |
if !ok { |
| 433 |
return nil, fmt.Errorf("client not found") |
| 434 |
} |
| 435 |
return RedirectGlobsClient(client), nil |
| 436 |
} |
| 437 |
|
| 438 |
// AuthorizeClientIDSecret implements the op.Storage interface |
| 439 |
// it will be called for validating the client_id, client_secret on token or introspection requests |
| 440 |
func (s *Storage) AuthorizeClientIDSecret(ctx context.Context, clientID, clientSecret string) error { |
| 441 |
s.lock.Lock() |
| 442 |
defer s.lock.Unlock() |
| 443 |
client, ok := s.clients[clientID] |
| 444 |
if !ok { |
| 445 |
return fmt.Errorf("client not found") |
| 446 |
} |
| 447 |
// for this example we directly check the secret |
| 448 |
// obviously you would not have the secret in plain text, but rather hashed and salted (e.g. using bcrypt) |
| 449 |
if client.secret != clientSecret { |
| 450 |
return fmt.Errorf("invalid secret") |
| 451 |
} |
| 452 |
return nil |
| 453 |
} |
| 454 |
|
| 455 |
// SetUserinfoFromScopes implements the op.Storage interface. |
| 456 |
// Provide an empty implementation and use SetUserinfoFromRequest instead. |
| 457 |
func (s *Storage) SetUserinfoFromScopes(ctx context.Context, userinfo *oidc.UserInfo, userID, clientID string, scopes []string) error { |
| 458 |
return nil |
| 459 |
} |
| 460 |
|
| 461 |
// SetUserinfoFromRequests implements the op.CanSetUserinfoFromRequest interface. In the |
| 462 |
// next major release, it will be required for op.Storage. |
| 463 |
// 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 |
| 464 |
func (s *Storage) SetUserinfoFromRequest(ctx context.Context, userinfo *oidc.UserInfo, token op.IDTokenRequest, scopes []string) error { |
| 465 |
return s.setUserinfo(ctx, userinfo, token.GetSubject(), token.GetClientID(), scopes) |
| 466 |
} |
| 467 |
|
| 468 |
// SetUserinfoFromToken implements the op.Storage interface |
| 469 |
// it will be called for the userinfo endpoint, so we read the token and pass the information from that to the private function |
| 470 |
func (s *Storage) SetUserinfoFromToken(ctx context.Context, userinfo *oidc.UserInfo, tokenID, subject, origin string) error { |
| 471 |
token, ok := func() (*Token, bool) { |
| 472 |
s.lock.Lock() |
| 473 |
defer s.lock.Unlock() |
| 474 |
token, ok := s.tokens[tokenID] |
| 475 |
return token, ok |
| 476 |
}() |
| 477 |
if !ok { |
| 478 |
return fmt.Errorf("token is invalid or has expired") |
| 479 |
} |
| 480 |
// the userinfo endpoint should support CORS. If it's not possible to specify a specific origin in the CORS handler, |
| 481 |
// and you have to specify a wildcard (*) origin, then you could also check here if the origin which called the userinfo endpoint here directly |
| 482 |
// note that the origin can be empty (if called by a web client) |
| 483 |
// |
| 484 |
// if origin != "" { |
| 485 |
// client, ok := s.clients[token.ApplicationID] |
| 486 |
// if !ok { |
| 487 |
// return fmt.Errorf("client not found") |
| 488 |
// } |
| 489 |
// if err := checkAllowedOrigins(client.allowedOrigins, origin); err != nil { |
| 490 |
// return err |
| 491 |
// } |
| 492 |
//} |
| 493 |
if token.Expiration.Before(time.Now()) { |
| 494 |
return fmt.Errorf("token is expired") |
| 495 |
} |
| 496 |
return s.setUserinfo(ctx, userinfo, token.Subject, token.ApplicationID, token.Scopes) |
| 497 |
} |
| 498 |
|
| 499 |
// SetIntrospectionFromToken implements the op.Storage interface |
| 500 |
// it will be called for the introspection endpoint, so we read the token and pass the information from that to the private function |
| 501 |
func (s *Storage) SetIntrospectionFromToken(ctx context.Context, introspection *oidc.IntrospectionResponse, tokenID, subject, clientID string) error { |
| 502 |
token, ok := func() (*Token, bool) { |
| 503 |
s.lock.Lock() |
| 504 |
defer s.lock.Unlock() |
| 505 |
token, ok := s.tokens[tokenID] |
| 506 |
return token, ok |
| 507 |
}() |
| 508 |
if !ok { |
| 509 |
return fmt.Errorf("token is invalid") |
| 510 |
} |
| 511 |
|
| 512 |
introspection.Expiration = oidc.FromTime(token.Expiration) |
| 513 |
if token.Expiration.Before(time.Now()) { |
| 514 |
return fmt.Errorf("token is expired") |
| 515 |
} |
| 516 |
// check if the client is part of the requested audience |
| 517 |
for _, aud := range token.Audience { |
| 518 |
if aud == clientID { |
| 519 |
// The introspection response only has to return a boolean (active) if the token is active. |
| 520 |
// This will automatically be done by the library if you don't return an error. |
| 521 |
// You can also return further information about the user / associated token. |
| 522 |
// e.g. the userinfo (equivalent to userinfo endpoint) |
| 523 |
|
| 524 |
userInfo := new(oidc.UserInfo) |
| 525 |
err := s.setUserinfo(ctx, userInfo, subject, clientID, token.Scopes) |
| 526 |
if err != nil { |
| 527 |
return err |
| 528 |
} |
| 529 |
introspection.SetUserInfo(userInfo) |
| 530 |
//...and also the requested scopes... |
| 531 |
introspection.Scope = token.Scopes |
| 532 |
//...and the client the token was issued to |
| 533 |
introspection.ClientID = token.ApplicationID |
| 534 |
return nil |
| 535 |
} |
| 536 |
} |
| 537 |
return fmt.Errorf("token is not valid for this client") |
| 538 |
} |
| 539 |
|
| 540 |
// GetPrivateClaimsFromScopes implements the op.Storage interface |
| 541 |
// it will be called for the creation of a JWT access token to assert claims for custom scopes |
| 542 |
func (s *Storage) GetPrivateClaimsFromScopes(ctx context.Context, userID, clientID string, scopes []string) (claims map[string]any, err error) { |
| 543 |
return s.getPrivateClaimsFromScopes(ctx, userID, clientID, scopes) |
| 544 |
} |
| 545 |
|
| 546 |
func (s *Storage) getPrivateClaimsFromScopes(ctx context.Context, userID, clientID string, scopes []string) (claims map[string]any, err error) { |
| 547 |
for _, scope := range scopes { |
| 548 |
switch scope { |
| 549 |
case CustomScope: |
| 550 |
claims = appendClaim(claims, CustomClaim, customClaim(clientID)) |
| 551 |
} |
| 552 |
} |
| 553 |
return claims, nil |
| 554 |
} |
| 555 |
|
| 556 |
// GetKeyByIDAndClientID implements the op.Storage interface |
| 557 |
// it will be called to validate the signatures of a JWT (JWT Profile Grant and Authentication) |
| 558 |
func (s *Storage) GetKeyByIDAndClientID(ctx context.Context, keyID, clientID string) (*jose.JSONWebKey, error) { |
| 559 |
s.lock.Lock() |
| 560 |
defer s.lock.Unlock() |
| 561 |
service, ok := s.services[clientID] |
| 562 |
if !ok { |
| 563 |
return nil, fmt.Errorf("clientID not found") |
| 564 |
} |
| 565 |
key, ok := service.keys[keyID] |
| 566 |
if !ok { |
| 567 |
return nil, fmt.Errorf("key not found") |
| 568 |
} |
| 569 |
return &jose.JSONWebKey{ |
| 570 |
KeyID: keyID, |
| 571 |
Use: "sig", |
| 572 |
Key: key, |
| 573 |
}, nil |
| 574 |
} |
| 575 |
|
| 576 |
// ValidateJWTProfileScopes implements the op.Storage interface |
| 577 |
// it will be called to validate the scopes of a JWT Profile Authorization Grant request |
| 578 |
func (s *Storage) ValidateJWTProfileScopes(ctx context.Context, userID string, scopes []string) ([]string, error) { |
| 579 |
allowedScopes := make([]string, 0) |
| 580 |
for _, scope := range scopes { |
| 581 |
if scope == oidc.ScopeOpenID { |
| 582 |
allowedScopes = append(allowedScopes, scope) |
| 583 |
} |
| 584 |
} |
| 585 |
return allowedScopes, nil |
| 586 |
} |
| 587 |
|
| 588 |
// Health implements the op.Storage interface |
| 589 |
func (s *Storage) Health(ctx context.Context) error { |
| 590 |
return nil |
| 591 |
} |
| 592 |
|
| 593 |
// createRefreshToken will store a refresh_token in-memory based on the provided information |
| 594 |
func (s *Storage) createRefreshToken(accessToken *Token, amr []string, authTime time.Time) (string, error) { |
| 595 |
s.lock.Lock() |
| 596 |
defer s.lock.Unlock() |
| 597 |
token := &RefreshToken{ |
| 598 |
ID: accessToken.RefreshTokenID, |
| 599 |
Token: accessToken.RefreshTokenID, |
| 600 |
AuthTime: authTime, |
| 601 |
AMR: amr, |
| 602 |
ApplicationID: accessToken.ApplicationID, |
| 603 |
UserID: accessToken.Subject, |
| 604 |
Audience: accessToken.Audience, |
| 605 |
Expiration: time.Now().Add(5 * time.Hour), |
| 606 |
Scopes: accessToken.Scopes, |
| 607 |
AccessToken: accessToken.ID, |
| 608 |
} |
| 609 |
s.refreshTokens[token.ID] = token |
| 610 |
return token.Token, nil |
| 611 |
} |
| 612 |
|
| 613 |
// renewRefreshToken checks the provided refresh_token and creates a new one based on the current |
| 614 |
// |
| 615 |
// [Refresh Token Rotation] is implemented. |
| 616 |
// |
| 617 |
// [Refresh Token Rotation]: https://www.rfc-editor.org/rfc/rfc6819#section-5.2.2.3 |
| 618 |
func (s *Storage) renewRefreshToken(currentRefreshToken, newRefreshToken, newAccessToken string) error { |
| 619 |
s.lock.Lock() |
| 620 |
defer s.lock.Unlock() |
| 621 |
refreshToken, ok := s.refreshTokens[currentRefreshToken] |
| 622 |
if !ok { |
| 623 |
return fmt.Errorf("invalid refresh token") |
| 624 |
} |
| 625 |
// deletes the refresh token |
| 626 |
delete(s.refreshTokens, currentRefreshToken) |
| 627 |
|
| 628 |
// delete the access token which was issued based on this refresh token |
| 629 |
delete(s.tokens, refreshToken.AccessToken) |
| 630 |
|
| 631 |
if refreshToken.Expiration.Before(time.Now()) { |
| 632 |
return fmt.Errorf("expired refresh token") |
| 633 |
} |
| 634 |
|
| 635 |
// creates a new refresh token based on the current one |
| 636 |
refreshToken.Token = newRefreshToken |
| 637 |
refreshToken.ID = newRefreshToken |
| 638 |
refreshToken.Expiration = time.Now().Add(5 * time.Hour) |
| 639 |
refreshToken.AccessToken = newAccessToken |
| 640 |
s.refreshTokens[newRefreshToken] = refreshToken |
| 641 |
return nil |
| 642 |
} |
| 643 |
|
| 644 |
// accessToken will store an access_token in-memory based on the provided information |
| 645 |
func (s *Storage) accessToken(applicationID, refreshTokenID, subject string, audience, scopes []string) (*Token, error) { |
| 646 |
s.lock.Lock() |
| 647 |
defer s.lock.Unlock() |
| 648 |
token := &Token{ |
| 649 |
ID: uuid.NewString(), |
| 650 |
ApplicationID: applicationID, |
| 651 |
RefreshTokenID: refreshTokenID, |
| 652 |
Subject: subject, |
| 653 |
Audience: audience, |
| 654 |
Expiration: time.Now().Add(5 * time.Minute), |
| 655 |
Scopes: scopes, |
| 656 |
} |
| 657 |
s.tokens[token.ID] = token |
| 658 |
return token, nil |
| 659 |
} |
| 660 |
|
| 661 |
// setUserinfo sets the info based on the user, scopes and if necessary the clientID |
| 662 |
func (s *Storage) setUserinfo(ctx context.Context, userInfo *oidc.UserInfo, userID, clientID string, scopes []string) (err error) { |
| 663 |
s.lock.Lock() |
| 664 |
defer s.lock.Unlock() |
| 665 |
user := s.userStore.GetUserByID(userID) |
| 666 |
if user == nil { |
| 667 |
return fmt.Errorf("user not found") |
| 668 |
} |
| 669 |
for _, scope := range scopes { |
| 670 |
switch scope { |
| 671 |
case oidc.ScopeOpenID: |
| 672 |
userInfo.Subject = user.ID |
| 673 |
case oidc.ScopeEmail: |
| 674 |
userInfo.Email = user.Email |
| 675 |
userInfo.EmailVerified = oidc.Bool(user.EmailVerified) |
| 676 |
case oidc.ScopeProfile: |
| 677 |
userInfo.PreferredUsername = user.Username |
| 678 |
userInfo.Name = user.FirstName + " " + user.LastName |
| 679 |
userInfo.FamilyName = user.LastName |
| 680 |
userInfo.GivenName = user.FirstName |
| 681 |
userInfo.Locale = oidc.NewLocale(user.PreferredLanguage) |
| 682 |
case oidc.ScopePhone: |
| 683 |
userInfo.PhoneNumber = user.Phone |
| 684 |
userInfo.PhoneNumberVerified = oidc.Bool(user.PhoneVerified) |
| 685 |
case CustomScope: |
| 686 |
// you can also have a custom scope and assert public or custom claims based on that |
| 687 |
userInfo.AppendClaims(CustomClaim, customClaim(clientID)) |
| 688 |
} |
| 689 |
} |
| 690 |
return nil |
| 691 |
} |
| 692 |
|
| 693 |
// ValidateTokenExchangeRequest implements the op.TokenExchangeStorage interface |
| 694 |
// it will be called to validate parsed Token Exchange Grant request |
| 695 |
func (s *Storage) ValidateTokenExchangeRequest(ctx context.Context, request op.TokenExchangeRequest) error { |
| 696 |
if request.GetRequestedTokenType() == "" { |
| 697 |
request.SetRequestedTokenType(oidc.RefreshTokenType) |
| 698 |
} |
| 699 |
|
| 700 |
// Just an example, some use cases might need this use case |
| 701 |
if request.GetExchangeSubjectTokenType() == oidc.IDTokenType && request.GetRequestedTokenType() == oidc.RefreshTokenType { |
| 702 |
return errors.New("exchanging id_token to refresh_token is not supported") |
| 703 |
} |
| 704 |
|
| 705 |
// Check impersonation permissions |
| 706 |
if request.GetExchangeActor() == "" && !s.userStore.GetUserByID(request.GetExchangeSubject()).IsAdmin { |
| 707 |
return errors.New("user doesn't have impersonation permission") |
| 708 |
} |
| 709 |
|
| 710 |
allowedScopes := make([]string, 0) |
| 711 |
for _, scope := range request.GetScopes() { |
| 712 |
if scope == oidc.ScopeAddress { |
| 713 |
continue |
| 714 |
} |
| 715 |
|
| 716 |
if strings.HasPrefix(scope, CustomScopeImpersonatePrefix) { |
| 717 |
subject := strings.TrimPrefix(scope, CustomScopeImpersonatePrefix) |
| 718 |
request.SetSubject(subject) |
| 719 |
} |
| 720 |
|
| 721 |
allowedScopes = append(allowedScopes, scope) |
| 722 |
} |
| 723 |
|
| 724 |
request.SetCurrentScopes(allowedScopes) |
| 725 |
|
| 726 |
return nil |
| 727 |
} |
| 728 |
|
| 729 |
// ValidateTokenExchangeRequest implements the op.TokenExchangeStorage interface |
| 730 |
// Common use case is to store request for audit purposes. For this example we skip the storing. |
| 731 |
func (s *Storage) CreateTokenExchangeRequest(ctx context.Context, request op.TokenExchangeRequest) error { |
| 732 |
return nil |
| 733 |
} |
| 734 |
|
| 735 |
// GetPrivateClaimsFromScopesForTokenExchange implements the op.TokenExchangeStorage interface |
| 736 |
// it will be called for the creation of an exchanged JWT access token to assert claims for custom scopes |
| 737 |
// plus adding token exchange specific claims related to delegation or impersonation |
| 738 |
func (s *Storage) GetPrivateClaimsFromTokenExchangeRequest(ctx context.Context, request op.TokenExchangeRequest) (claims map[string]any, err error) { |
| 739 |
claims, err = s.getPrivateClaimsFromScopes(ctx, "", request.GetClientID(), request.GetScopes()) |
| 740 |
if err != nil { |
| 741 |
return nil, err |
| 742 |
} |
| 743 |
|
| 744 |
for k, v := range s.getTokenExchangeClaims(ctx, request) { |
| 745 |
claims = appendClaim(claims, k, v) |
| 746 |
} |
| 747 |
|
| 748 |
return claims, nil |
| 749 |
} |
| 750 |
|
| 751 |
// SetUserinfoFromScopesForTokenExchange implements the op.TokenExchangeStorage interface |
| 752 |
// it will be called for the creation of an id_token - we are using the same private function as for other flows, |
| 753 |
// plus adding token exchange specific claims related to delegation or impersonation |
| 754 |
func (s *Storage) SetUserinfoFromTokenExchangeRequest(ctx context.Context, userinfo *oidc.UserInfo, request op.TokenExchangeRequest) error { |
| 755 |
err := s.setUserinfo(ctx, userinfo, request.GetSubject(), request.GetClientID(), request.GetScopes()) |
| 756 |
if err != nil { |
| 757 |
return err |
| 758 |
} |
| 759 |
|
| 760 |
for k, v := range s.getTokenExchangeClaims(ctx, request) { |
| 761 |
userinfo.AppendClaims(k, v) |
| 762 |
} |
| 763 |
|
| 764 |
return nil |
| 765 |
} |
| 766 |
|
| 767 |
func (s *Storage) getTokenExchangeClaims(ctx context.Context, request op.TokenExchangeRequest) (claims map[string]any) { |
| 768 |
for _, scope := range request.GetScopes() { |
| 769 |
switch { |
| 770 |
case strings.HasPrefix(scope, CustomScopeImpersonatePrefix) && request.GetExchangeActor() == "": |
| 771 |
// Set actor subject claim for impersonation flow |
| 772 |
claims = appendClaim(claims, "act", map[string]any{ |
| 773 |
"sub": request.GetExchangeSubject(), |
| 774 |
}) |
| 775 |
} |
| 776 |
} |
| 777 |
|
| 778 |
// Set actor subject claim for delegation flow |
| 779 |
// if request.GetExchangeActor() != "" { |
| 780 |
// claims = appendClaim(claims, "act", map[string]any{ |
| 781 |
// "sub": request.GetExchangeActor(), |
| 782 |
// }) |
| 783 |
// } |
| 784 |
|
| 785 |
return claims |
| 786 |
} |
| 787 |
|
| 788 |
// getInfoFromRequest returns the clientID, authTime and amr depending on the op.TokenRequest type / implementation |
| 789 |
func getInfoFromRequest(req op.TokenRequest) (clientID string, authTime time.Time, amr []string) { |
| 790 |
authReq, ok := req.(*AuthRequest) // Code Flow (with scope offline_access) |
| 791 |
if ok { |
| 792 |
return authReq.ApplicationID, authReq.authTime, authReq.GetAMR() |
| 793 |
} |
| 794 |
refreshReq, ok := req.(*RefreshTokenRequest) // Refresh Token Request |
| 795 |
if ok { |
| 796 |
return refreshReq.ApplicationID, refreshReq.AuthTime, refreshReq.AMR |
| 797 |
} |
| 798 |
return "", time.Time{}, nil |
| 799 |
} |
| 800 |
|
| 801 |
// customClaim demonstrates how to return custom claims based on provided information |
| 802 |
func customClaim(clientID string) map[string]any { |
| 803 |
return map[string]any{ |
| 804 |
"client": clientID, |
| 805 |
"other": "stuff", |
| 806 |
} |
| 807 |
} |
| 808 |
|
| 809 |
func appendClaim(claims map[string]any, claim string, value any) map[string]any { |
| 810 |
if claims == nil { |
| 811 |
claims = make(map[string]any) |
| 812 |
} |
| 813 |
claims[claim] = value |
| 814 |
return claims |
| 815 |
} |
| 816 |
|
| 817 |
type deviceAuthorizationEntry struct { |
| 818 |
deviceCode string |
| 819 |
userCode string |
| 820 |
state *op.DeviceAuthorizationState |
| 821 |
} |
| 822 |
|
| 823 |
func (s *Storage) StoreDeviceAuthorization(ctx context.Context, clientID, deviceCode, userCode string, expires time.Time, scopes []string) error { |
| 824 |
s.lock.Lock() |
| 825 |
defer s.lock.Unlock() |
| 826 |
|
| 827 |
if _, ok := s.clients[clientID]; !ok { |
| 828 |
return errors.New("client not found") |
| 829 |
} |
| 830 |
|
| 831 |
if _, ok := s.userCodes[userCode]; ok { |
| 832 |
return op.ErrDuplicateUserCode |
| 833 |
} |
| 834 |
|
| 835 |
s.deviceCodes[deviceCode] = deviceAuthorizationEntry{ |
| 836 |
deviceCode: deviceCode, |
| 837 |
userCode: userCode, |
| 838 |
state: &op.DeviceAuthorizationState{ |
| 839 |
ClientID: clientID, |
| 840 |
Scopes: scopes, |
| 841 |
Expires: expires, |
| 842 |
}, |
| 843 |
} |
| 844 |
|
| 845 |
s.userCodes[userCode] = deviceCode |
| 846 |
return nil |
| 847 |
} |
| 848 |
|
| 849 |
func (s *Storage) GetDeviceAuthorizatonState(ctx context.Context, clientID, deviceCode string) (*op.DeviceAuthorizationState, error) { |
| 850 |
if ctx.Err() != nil { |
| 851 |
return nil, ctx.Err() |
| 852 |
} |
| 853 |
|
| 854 |
s.lock.Lock() |
| 855 |
defer s.lock.Unlock() |
| 856 |
|
| 857 |
entry, ok := s.deviceCodes[deviceCode] |
| 858 |
if !ok || entry.state.ClientID != clientID { |
| 859 |
return nil, errors.New("device code not found for client") // is there a standard not found error in the framework? |
| 860 |
} |
| 861 |
|
| 862 |
return entry.state, nil |
| 863 |
} |
| 864 |
|
| 865 |
func (s *Storage) GetDeviceAuthorizationByUserCode(ctx context.Context, userCode string) (*op.DeviceAuthorizationState, error) { |
| 866 |
s.lock.Lock() |
| 867 |
defer s.lock.Unlock() |
| 868 |
|
| 869 |
entry, ok := s.deviceCodes[s.userCodes[userCode]] |
| 870 |
if !ok { |
| 871 |
return nil, errors.New("user code not found") |
| 872 |
} |
| 873 |
|
| 874 |
return entry.state, nil |
| 875 |
} |
| 876 |
|
| 877 |
func (s *Storage) CompleteDeviceAuthorization(ctx context.Context, userCode, subject string) error { |
| 878 |
s.lock.Lock() |
| 879 |
defer s.lock.Unlock() |
| 880 |
|
| 881 |
entry, ok := s.deviceCodes[s.userCodes[userCode]] |
| 882 |
if !ok { |
| 883 |
return errors.New("user code not found") |
| 884 |
} |
| 885 |
|
| 886 |
entry.state.Subject = subject |
| 887 |
entry.state.Done = true |
| 888 |
return nil |
| 889 |
} |
| 890 |
|
| 891 |
func (s *Storage) DenyDeviceAuthorization(ctx context.Context, userCode string) error { |
| 892 |
s.lock.Lock() |
| 893 |
defer s.lock.Unlock() |
| 894 |
|
| 895 |
s.deviceCodes[s.userCodes[userCode]].state.Denied = true |
| 896 |
return nil |
| 897 |
} |
| 898 |
|
| 899 |
// AuthRequestDone is used by testing and is not required to implement op.Storage |
| 900 |
func (s *Storage) AuthRequestDone(id string) error { |
| 901 |
s.lock.Lock() |
| 902 |
defer s.lock.Unlock() |
| 903 |
|
| 904 |
if req, ok := s.authRequests[id]; ok { |
| 905 |
req.done = true |
| 906 |
return nil |
| 907 |
} |
| 908 |
|
| 909 |
return errors.New("request not found") |
| 910 |
} |
| 911 |
|
| 912 |
func (s *Storage) ClientCredentials(ctx context.Context, clientID, clientSecret string) (op.Client, error) { |
| 913 |
s.lock.Lock() |
| 914 |
defer s.lock.Unlock() |
| 915 |
|
| 916 |
client, ok := s.serviceUsers[clientID] |
| 917 |
if !ok { |
| 918 |
return nil, errors.New("wrong service user or password") |
| 919 |
} |
| 920 |
if client.secret != clientSecret { |
| 921 |
return nil, errors.New("wrong service user or password") |
| 922 |
} |
| 923 |
|
| 924 |
return client, nil |
| 925 |
} |
| 926 |
|
| 927 |
func (s *Storage) ClientCredentialsTokenRequest(ctx context.Context, clientID string, scopes []string) (op.TokenRequest, error) { |
| 928 |
client, ok := s.serviceUsers[clientID] |
| 929 |
if !ok { |
| 930 |
return nil, errors.New("wrong service user or password") |
| 931 |
} |
| 932 |
|
| 933 |
return &oidc.JWTTokenRequest{ |
| 934 |
Subject: client.id, |
| 935 |
Audience: []string{clientID}, |
| 936 |
Scopes: scopes, |
| 937 |
}, nil |
| 938 |
} |