private async Task CreateAuthorizationAsync([NotNull] AuthenticationTicket ticket, [NotNull] KeystoneServerOptions options, [NotNull] OpenIdConnectRequest request) { var descriptor = new KeystoneAuthorizationDescriptor { Principal = ticket.Principal, Status = KeystoneConstants.Statuses.Valid, Subject = ticket.Principal.GetClaim(KeystoneConstants.Claims.Subject), Type = KeystoneConstants.AuthorizationTypes.AdHoc }; foreach (var property in ticket.Properties.Items) { descriptor.Properties.Add(property); } foreach (var scope in ticket.GetScopes()) { descriptor.Scopes.Add(scope); } // If the client application is known, bind it to the authorization. if (!string.IsNullOrEmpty(request.ClientId)) { var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { throw new InvalidOperationException("The application entry cannot be found in the database."); } descriptor.ApplicationId = await _applicationManager.GetIdAsync(application); } var authorization = await _authorizationManager.CreateAsync(descriptor); if (authorization != null) { var identifier = await _authorizationManager.GetIdAsync(authorization); if (string.IsNullOrEmpty(request.ClientId)) { _logger.LogInformation("An ad hoc authorization was automatically created and " + "associated with an unknown application: {Identifier}.", identifier); } else { _logger.LogInformation("An ad hoc authorization was automatically created and " + "associated with the '{ClientId}' application: {Identifier}.", request.ClientId, identifier); } // Attach the unique identifier of the ad hoc authorization to the authentication ticket // so that it is attached to all the derived tokens, allowing batched revocations support. ticket.SetInternalAuthorizationId(identifier); } }
private async Task <bool> TryExtendRefreshTokenAsync( [NotNull] object token, [NotNull] AuthenticationTicket ticket, [NotNull] KeystoneServerOptions options) { var identifier = ticket.GetInternalTokenId(); Debug.Assert(!string.IsNullOrEmpty(identifier), "The token identifier shouldn't be null or empty."); try { // Compute the new expiration date of the refresh token. var lifetime = ticket.GetRefreshTokenLifetime() ?? options.RefreshTokenLifetime; if (lifetime != null) { // Note: the request cancellation token is deliberately not used here to ensure the caller // cannot prevent this operation from being executed by resetting the TCP connection. var date = options.SystemClock.UtcNow + lifetime.Value; await _tokenManager.ExtendAsync(token, date); _logger.LogInformation("The expiration date of the refresh token '{Identifier}' " + "was automatically updated: {Date}.", identifier, date); } else if (await _tokenManager.GetExpirationDateAsync(token) != null) { // Note: the request cancellation token is deliberately not used here to ensure the caller // cannot prevent this operation from being executed by resetting the TCP connection. await _tokenManager.ExtendAsync(token, date : null); _logger.LogInformation("The expiration date of the refresh token '{Identifier}' was removed.", identifier); } return(true); } catch (KeystoneExceptions.ConcurrencyException exception) { _logger.LogDebug(exception, "A concurrency exception occurred while trying to update the " + "expiration date of the token '{Identifier}'.", identifier); return(false); } catch (Exception exception) { _logger.LogWarning(exception, "An exception occurred while trying to update the " + "expiration date of the token '{Identifier}'.", identifier); return(false); } }
/// <summary> /// Populates the default OpenID Connect server options and ensures /// that the configuration is in a consistent and valid state. /// </summary> /// <param name="name">The authentication scheme associated with the handler instance.</param> /// <param name="options">The options instance to initialize.</param> public void PostConfigure([NotNull] string name, [NotNull] KeystoneServerOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The options instance name cannot be null or empty.", nameof(name)); } if (options.RandomNumberGenerator == null) { throw new InvalidOperationException("A random number generator must be registered."); } if (options.ProviderType == null || options.ProviderType != typeof(KeystoneServerProvider)) { throw new InvalidOperationException(new StringBuilder() .AppendLine("Keystone can only be used with its built-in server provider.") .AppendLine("This error may indicate that 'KeystoneServerOptions.ProviderType' was manually set.") .Append("To execute custom request handling logic, consider registering an event handler using ") .Append("the generic 'services.AddKeystone().AddServer().AddEventHandler()' method.") .ToString()); } // When no distributed cache has been registered in the options, // try to resolve it from the dependency injection container. if (options.Cache == null) { options.Cache = _cache; } // If Keystone was configured to use reference tokens, replace the default access tokens/ // authorization codes/refresh tokens formats using a specific data protector to ensure // that encrypted tokens stored in the database cannot be treated as valid tokens if the // reference tokens option is later turned off by the developer. if (options.UseReferenceTokens) { // Note: a default data protection provider is always registered by // the OpenID Connect server handler when none is explicitly set but // this initializer is registered to be invoked before ASOS' initializer. // To ensure the provider property is never null, it's manually set here. if (options.DataProtectionProvider == null) { options.DataProtectionProvider = _dataProtectionProvider; } if (options.AccessTokenFormat == null) { var protector = options.DataProtectionProvider.CreateProtector( nameof(OpenIdConnectServerHandler), nameof(options.AccessTokenFormat), nameof(options.UseReferenceTokens), name); options.AccessTokenFormat = new TicketDataFormat(protector); } if (options.AuthorizationCodeFormat == null) { var protector = options.DataProtectionProvider.CreateProtector( nameof(OpenIdConnectServerHandler), nameof(options.AuthorizationCodeFormat), nameof(options.UseReferenceTokens), name); options.AuthorizationCodeFormat = new TicketDataFormat(protector); } if (options.RefreshTokenFormat == null) { var protector = options.DataProtectionProvider.CreateProtector( nameof(OpenIdConnectServerHandler), nameof(options.RefreshTokenFormat), nameof(options.UseReferenceTokens), name); options.RefreshTokenFormat = new TicketDataFormat(protector); } } // Ensure at least one flow has been enabled. if (options.GrantTypes.Count == 0) { throw new InvalidOperationException("At least one OAuth2/OpenID Connect flow must be enabled."); } // Ensure the authorization endpoint has been enabled when // the authorization code or implicit grants are supported. if (!options.AuthorizationEndpointPath.HasValue && (options.GrantTypes.Contains(KeystoneConstants.GrantTypes.AuthorizationCode) || options.GrantTypes.Contains(KeystoneConstants.GrantTypes.Implicit))) { throw new InvalidOperationException("The authorization endpoint must be enabled to use the authorization code and implicit flows."); } // Ensure the token endpoint has been enabled when the authorization code, // client credentials, password or refresh token grants are supported. if (!options.TokenEndpointPath.HasValue && (options.GrantTypes.Contains(KeystoneConstants.GrantTypes.AuthorizationCode) || options.GrantTypes.Contains(KeystoneConstants.GrantTypes.ClientCredentials) || options.GrantTypes.Contains(KeystoneConstants.GrantTypes.Password) || options.GrantTypes.Contains(KeystoneConstants.GrantTypes.RefreshToken))) { throw new InvalidOperationException( "The token endpoint must be enabled to use the authorization code, client credentials, password and refresh token flows."); } if (options.EnableRequestCaching && options.RequestCachingPolicy == null) { throw new InvalidOperationException("A caching policy must be specified when enabling request caching."); } if (options.RevocationEndpointPath.HasValue && options.DisableTokenStorage) { throw new InvalidOperationException("The revocation endpoint cannot be enabled when token storage is disabled."); } if (options.UseReferenceTokens && options.DisableTokenStorage) { throw new InvalidOperationException("Reference tokens cannot be used when disabling token storage."); } if (options.UseReferenceTokens && options.AccessTokenHandler != null) { throw new InvalidOperationException("Reference tokens cannot be used when configuring JWT as the access token format."); } if (options.UseSlidingExpiration && options.DisableTokenStorage && !options.UseRollingTokens) { throw new InvalidOperationException( "Sliding expiration must be disabled when turning off token storage if rolling tokens are not used."); } if (options.AccessTokenHandler != null && options.SigningCredentials.Count == 0) { throw new InvalidOperationException(new StringBuilder() .AppendLine("At least one signing key must be registered when using JWT as the access token format.") .Append("Consider registering a certificate using 'services.AddKeystone().AddServer().AddSigningCertificate()' ") .Append("or 'services.AddKeystone().AddServer().AddDevelopmentSigningCertificate()' or call ") .Append("'services.AddKeystone().AddServer().AddEphemeralSigningKey()' to use an ephemeral key.") .ToString()); } // Ensure at least one asymmetric signing certificate/key was registered if the implicit flow was enabled. if (!options.SigningCredentials.Any(credentials => credentials.Key is AsymmetricSecurityKey) && options.GrantTypes.Contains(KeystoneConstants.GrantTypes.Implicit)) { throw new InvalidOperationException(new StringBuilder() .AppendLine("At least one asymmetric signing key must be registered when enabling the implicit flow.") .Append("Consider registering a certificate using 'services.AddKeystone().AddServer().AddSigningCertificate()' ") .Append("or 'services.AddKeystone().AddServer().AddDevelopmentSigningCertificate()' or call ") .Append("'services.AddKeystone().AddServer().AddEphemeralSigningKey()' to use an ephemeral key.") .ToString()); } // Automatically add the offline_access scope if the refresh token grant has been enabled. if (options.GrantTypes.Contains(KeystoneConstants.GrantTypes.RefreshToken)) { options.Scopes.Add(KeystoneConstants.Scopes.OfflineAccess); } }
private async Task <string> CreateTokenAsync( [NotNull] string type, [NotNull] AuthenticationTicket ticket, [NotNull] KeystoneServerOptions options, [NotNull] OpenIdConnectRequest request, [NotNull] ISecureDataFormat <AuthenticationTicket> format) { Debug.Assert(!(options.DisableTokenStorage && options.UseReferenceTokens), "Token storage cannot be disabled when using reference tokens."); Debug.Assert(type == OpenIdConnectConstants.TokenUsages.AccessToken || type == OpenIdConnectConstants.TokenUsages.AuthorizationCode || type == OpenIdConnectConstants.TokenUsages.RefreshToken, "Only authorization codes, access and refresh tokens should be created using this method."); // When sliding expiration is disabled, the expiration date of generated refresh tokens is fixed // and must exactly match the expiration date of the refresh token used in the token request. if (request.IsTokenRequest() && request.IsRefreshTokenGrantType() && !options.UseSlidingExpiration && type == OpenIdConnectConstants.TokenUsages.RefreshToken) { var properties = request.GetProperty <AuthenticationTicket>( KeystoneConstants.Properties.AuthenticationTicket)?.Properties; Debug.Assert(properties != null, "The authentication properties shouldn't be null."); ticket.Properties.ExpiresUtc = properties.ExpiresUtc; } if (options.DisableTokenStorage) { return(null); } var descriptor = new KeystoneTokenDescriptor { AuthorizationId = ticket.GetInternalAuthorizationId(), CreationDate = ticket.Properties.IssuedUtc, ExpirationDate = ticket.Properties.ExpiresUtc, Principal = ticket.Principal, Status = KeystoneConstants.Statuses.Valid, Subject = ticket.Principal.GetClaim(KeystoneConstants.Claims.Subject), Type = type }; foreach (var property in ticket.Properties.Items) { descriptor.Properties.Add(property); } // When reference tokens are enabled or when the token is an authorization code or a // refresh token, remove the unnecessary properties from the authentication ticket. if (options.UseReferenceTokens || (type == OpenIdConnectConstants.TokenUsages.AuthorizationCode || type == OpenIdConnectConstants.TokenUsages.RefreshToken)) { ticket.Properties.IssuedUtc = ticket.Properties.ExpiresUtc = null; ticket.RemoveProperty(KeystoneConstants.Properties.InternalAuthorizationId) .RemoveProperty(KeystoneConstants.Properties.InternalTokenId); } // If reference tokens are enabled, create a new entry for // authorization codes, refresh tokens and access tokens. if (options.UseReferenceTokens) { // Note: the data format is automatically replaced at startup time to ensure // that encrypted tokens stored in the database cannot be considered as // valid tokens if the developer decides to disable reference tokens support. descriptor.Payload = format.Protect(ticket); // Generate a new crypto-secure random identifier that will be // substituted to the ciphertext returned by the data format. var bytes = new byte[256 / 8]; options.RandomNumberGenerator.GetBytes(bytes); // Note: the default token manager automatically obfuscates the // reference identifier so it can be safely stored in the databse. descriptor.ReferenceId = Base64UrlEncoder.Encode(bytes); } // Otherwise, only create a token metadata entry for authorization codes and refresh tokens. else if (type != OpenIdConnectConstants.TokenUsages.AuthorizationCode && type != OpenIdConnectConstants.TokenUsages.RefreshToken) { return(null); } // If the client application is known, associate it with the token. if (!string.IsNullOrEmpty(request.ClientId)) { var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { throw new InvalidOperationException("The application entry cannot be found in the database."); } descriptor.ApplicationId = await _applicationManager.GetIdAsync(application); } // If a null value was returned by CreateAsync(), return immediately. // Note: the request cancellation token is deliberately not used here to ensure the caller // cannot prevent this operation from being executed by resetting the TCP connection. var token = await _tokenManager.CreateAsync(descriptor); if (token == null) { return(null); } // Throw an exception if the token identifier can't be resolved. var identifier = await _tokenManager.GetIdAsync(token); if (string.IsNullOrEmpty(identifier)) { throw new InvalidOperationException("The unique key associated with a refresh token cannot be null or empty."); } // Dynamically set the creation and expiration dates. ticket.Properties.IssuedUtc = descriptor.CreationDate; ticket.Properties.ExpiresUtc = descriptor.ExpirationDate; // Restore the token/authorization identifiers using the identifiers attached with the database entry. ticket.SetInternalAuthorizationId(descriptor.AuthorizationId) .SetInternalTokenId(identifier); if (options.UseReferenceTokens) { _logger.LogTrace("A new reference token was successfully generated and persisted " + "in the database: {Token} ; {Claims} ; {Properties}.", descriptor.ReferenceId, ticket.Principal.Claims, ticket.Properties.Items); return(descriptor.ReferenceId); } return(null); }
private async Task <AuthenticationTicket> ReceiveTokenAsync( [NotNull] string type, [NotNull] string value, [NotNull] KeystoneServerOptions options, [NotNull] OpenIdConnectRequest request, [NotNull] ISecureDataFormat <AuthenticationTicket> format) { Debug.Assert(!(options.DisableTokenStorage && options.UseReferenceTokens), "Token revocation cannot be disabled when using reference tokens."); Debug.Assert(type == OpenIdConnectConstants.TokenUsages.AccessToken || type == OpenIdConnectConstants.TokenUsages.AuthorizationCode || type == OpenIdConnectConstants.TokenUsages.RefreshToken, "Only authorization codes, access and refresh tokens should be validated using this method."); string identifier; AuthenticationTicket ticket; object token; if (options.UseReferenceTokens) { token = await _tokenManager.FindByReferenceIdAsync(value); if (token == null) { _logger.LogInformation("The reference token corresponding to the '{Identifier}' " + "reference identifier cannot be found in the database.", value); return(null); } // Optimization: avoid extracting/decrypting the token payload // (that relies on a format specific to the token type requested) // if the token type associated with the token entry isn't valid. var usage = await _tokenManager.GetTypeAsync(token); if (string.IsNullOrEmpty(usage)) { _logger.LogWarning("The token type associated with the received token cannot be retrieved. " + "This may indicate that the token entry is corrupted."); return(null); } if (!string.Equals(usage, type, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("The token type '{ActualType}' associated with the database entry doesn't match " + "the expected type: {ExpectedType}.", await _tokenManager.GetTypeAsync(token), type); return(null); } identifier = await _tokenManager.GetIdAsync(token); if (string.IsNullOrEmpty(identifier)) { _logger.LogWarning("The identifier associated with the received token cannot be retrieved. " + "This may indicate that the token entry is corrupted."); return(null); } // Extract the encrypted payload from the token. If it's null or empty, // assume the token is not a reference token and consider it as invalid. var payload = await _tokenManager.GetPayloadAsync(token); if (string.IsNullOrEmpty(payload)) { _logger.LogWarning("The ciphertext associated with the token '{Identifier}' cannot be retrieved. " + "This may indicate that the token is not a reference token.", identifier); return(null); } ticket = format.Unprotect(payload); if (ticket == null) { _logger.LogWarning("The ciphertext associated with the token '{Identifier}' cannot be decrypted. " + "This may indicate that the token entry is corrupted or tampered.", await _tokenManager.GetIdAsync(token)); return(null); } } else if (type == OpenIdConnectConstants.TokenUsages.AuthorizationCode || type == OpenIdConnectConstants.TokenUsages.RefreshToken) { ticket = format.Unprotect(value); if (ticket == null) { _logger.LogTrace("The received token was invalid or malformed: {Token}.", value); return(null); } identifier = ticket.GetInternalTokenId(); if (string.IsNullOrEmpty(identifier)) { _logger.LogWarning("The identifier associated with the received token cannot be retrieved. " + "This may indicate that the token entry is corrupted."); return(null); } token = await _tokenManager.FindByIdAsync(identifier); if (token == null) { _logger.LogInformation("The token '{Identifier}' cannot be found in the database.", identifier); return(null); } } else { return(null); } // Dynamically set the creation and expiration dates. ticket.Properties.IssuedUtc = await _tokenManager.GetCreationDateAsync(token); ticket.Properties.ExpiresUtc = await _tokenManager.GetExpirationDateAsync(token); // Restore the token/authorization identifiers using the identifiers attached with the database entry. ticket.SetInternalAuthorizationId(await _tokenManager.GetAuthorizationIdAsync(token)) .SetInternalTokenId(identifier); _logger.LogTrace("The token '{Identifier}' was successfully decrypted and " + "retrieved from the database: {Claims} ; {Properties}.", identifier, ticket.Principal.Claims, ticket.Properties.Items); return(ticket); }