diff --git a/build/dependencies.props b/build/dependencies.props index 850642f8..f06f338a 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -2,8 +2,8 @@ 1.0.0 - 1.0.0 - 1.0.2 + 1.1.0-preview-0310 + 1.1.0-preview-1374 4.0.1 2.0.4 4.1.0 diff --git a/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Authentication.cs b/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Authentication.cs index 19b5e47f..0206fb82 100644 --- a/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Authentication.cs +++ b/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Authentication.cs @@ -5,6 +5,8 @@ */ using System; +using System.Collections.Generic; +using System.Collections.Immutable; using System.IO; using System.Threading.Tasks; using AspNet.Security.OpenIdConnect.Extensions; @@ -185,16 +187,27 @@ namespace OpenIddict.Server } // Validates scopes, unless scope validation was explicitly disabled. - foreach (var scope in context.Request.GetScopes()) + if (options.EnableScopeValidation) { - if (options.EnableScopeValidation && !options.Scopes.Contains(scope) && - await scopeManager.FindByNameAsync(scope) == null) + var scopes = new HashSet(context.Request.GetScopes(), StringComparer.Ordinal); + scopes.ExceptWith(options.Scopes); + + // If all the specified scopes are registered in the options, avoid making a database lookup. + if (scopes.Count != 0) + { + foreach (var scope in await scopeManager.FindByNamesAsync(scopes.ToImmutableArray())) + { + scopes.Remove(await scopeManager.GetNameAsync(scope)); + } + } + + // If at least one scope was not recognized, return an error. + if (scopes.Count != 0) { - logger.LogError("The authorization request was rejected because an " + - "unregistered scope was specified: {Scope}.", scope); + logger.LogError("The authentication request was rejected because invalid scopes were specified: {Scopes}.", scopes); context.Reject( - error: OpenIdConnectConstants.Errors.InvalidRequest, + error: OpenIdConnectConstants.Errors.InvalidScope, description: "The specified 'scope' parameter is not valid."); return; diff --git a/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Exchange.cs b/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Exchange.cs index 897b2b53..5eacb2a3 100644 --- a/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Exchange.cs +++ b/src/OpenIddict.Server/Internal/OpenIddictServerProvider.Exchange.cs @@ -5,6 +5,8 @@ */ using System; +using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; using System.Threading.Tasks; using AspNet.Security.OpenIdConnect.Extensions; @@ -81,16 +83,27 @@ namespace OpenIddict.Server } // Validates scopes, unless scope validation was explicitly disabled. - foreach (var scope in context.Request.GetScopes()) + if (options.EnableScopeValidation) { - if (options.EnableScopeValidation && !options.Scopes.Contains(scope) && - await scopeManager.FindByNameAsync(scope) == null) + var scopes = new HashSet(context.Request.GetScopes(), StringComparer.Ordinal); + scopes.ExceptWith(options.Scopes); + + // If all the specified scopes are registered in the options, avoid making a database lookup. + if (scopes.Count != 0) + { + foreach (var scope in await scopeManager.FindByNamesAsync(scopes.ToImmutableArray())) + { + scopes.Remove(await scopeManager.GetNameAsync(scope)); + } + } + + // If at least one scope was not recognized, return an error. + if (scopes.Count != 0) { - logger.LogError("The token request was rejected because an " + - "unregistered scope was specified: {Scope}.", scope); + logger.LogError("The token request was rejected because invalid scopes were specified: {Scopes}.", scopes); context.Reject( - error: OpenIdConnectConstants.Errors.InvalidRequest, + error: OpenIdConnectConstants.Errors.InvalidScope, description: "The specified 'scope' parameter is not valid."); return; diff --git a/src/OpenIddict.Server/OpenIddictServerBuilder.cs b/src/OpenIddict.Server/OpenIddictServerBuilder.cs index 13d59f5c..0cc5e431 100644 --- a/src/OpenIddict.Server/OpenIddictServerBuilder.cs +++ b/src/OpenIddict.Server/OpenIddictServerBuilder.cs @@ -450,6 +450,66 @@ namespace Microsoft.Extensions.DependencyInjection return Configure(options => options.UserinfoEndpointPath = path); } + /// + /// Registers the specified claims as supported claims so + /// they can be returned as part of the discovery document. + /// + /// The supported claims. + /// The . + public OpenIddictServerBuilder RegisterClaims([NotNull] params string[] claims) + { + if (claims == null) + { + throw new ArgumentNullException(nameof(claims)); + } + + if (claims.Any(claim => string.IsNullOrEmpty(claim))) + { + throw new ArgumentException("Claims cannot be null or empty.", nameof(claims)); + } + + return Configure(options => options.Claims.UnionWith(claims)); + } + + /// + /// Registers an application-specific OpenID Connect server provider whose events + /// are automatically invoked for each request handled by the OpenIddict server handler. + /// Using this method is NOT recommended if you're not familiar with the OIDC events model. + /// + /// The custom service. + /// The . + [EditorBrowsable(EditorBrowsableState.Advanced)] + public OpenIddictServerBuilder RegisterProvider([NotNull] OpenIdConnectServerProvider provider) + { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + + return Configure(options => options.ApplicationProvider = provider); + } + + /// + /// Registers the specified scopes as supported scopes so + /// they can be returned as part of the discovery document. + /// + /// The supported scopes. + /// The . + public OpenIddictServerBuilder RegisterScopes([NotNull] params string[] scopes) + { + if (scopes == null) + { + throw new ArgumentNullException(nameof(scopes)); + } + + if (scopes.Any(scope => string.IsNullOrEmpty(scope))) + { + throw new ArgumentException("Scopes cannot be null or empty.", nameof(scopes)); + } + + return Configure(options => options.Scopes.UnionWith(scopes)); + } + /// /// Makes client identification mandatory so that token and revocation /// requests that don't specify a client_id are automatically rejected. @@ -517,66 +577,6 @@ namespace Microsoft.Extensions.DependencyInjection return Configure(options => options.Issuer = address); } - /// - /// Registers the specified claims as supported claims so - /// they can be returned as part of the discovery document. - /// - /// The supported claims. - /// The . - public OpenIddictServerBuilder RegisterClaims([NotNull] params string[] claims) - { - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } - - if (claims.Any(claim => string.IsNullOrEmpty(claim))) - { - throw new ArgumentException("Claims cannot be null or empty.", nameof(claims)); - } - - return Configure(options => options.Claims.UnionWith(claims)); - } - - /// - /// Registers an application-specific OpenID Connect server provider whose events - /// are automatically invoked for each request handled by the OpenIddict server handler. - /// Using this method is NOT recommended if you're not familiar with the OIDC events model. - /// - /// The custom service. - /// The . - [EditorBrowsable(EditorBrowsableState.Advanced)] - public OpenIddictServerBuilder RegisterProvider([NotNull] OpenIdConnectServerProvider provider) - { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - return Configure(options => options.ApplicationProvider = provider); - } - - /// - /// Registers the specified scopes as supported scopes so - /// they can be returned as part of the discovery document. - /// - /// The supported scopes. - /// The . - public OpenIddictServerBuilder RegisterScopes([NotNull] params string[] scopes) - { - if (scopes == null) - { - throw new ArgumentNullException(nameof(scopes)); - } - - if (scopes.Any(scope => string.IsNullOrEmpty(scope))) - { - throw new ArgumentException("Scopes cannot be null or empty.", nameof(scopes)); - } - - return Configure(options => options.Scopes.UnionWith(scopes)); - } - /// /// Configures OpenIddict to use a specific data protection provider /// instead of relying on the default instance provided by the DI container. diff --git a/src/OpenIddict.Validation/Internal/OpenIddictValidationEvents.cs b/src/OpenIddict.Validation/Internal/OpenIddictValidationEvents.cs new file mode 100644 index 00000000..af18805d --- /dev/null +++ b/src/OpenIddict.Validation/Internal/OpenIddictValidationEvents.cs @@ -0,0 +1,101 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using System; +using System.ComponentModel; +using System.Text; +using System.Threading.Tasks; +using AspNet.Security.OAuth.Validation; +using JetBrains.Annotations; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenIddict.Abstractions; + +namespace OpenIddict.Validation +{ + /// + /// Provides the logic necessary to extract, validate and handle OAuth2 requests. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public class OpenIddictValidationEvents : OAuthValidationEvents + { + public override async Task DecryptToken([NotNull] DecryptTokenContext context) + { + var options = (OpenIddictValidationOptions) context.Options; + + var logger = context.HttpContext.RequestServices.GetRequiredService>(); + + if (options.UseReferenceTokens) + { + // Note: the token manager is deliberately not injected using constructor injection + // to allow using the validation handler without having to register the core services. + var manager = context.HttpContext.RequestServices.GetService(); + if (manager == null) + { + throw new InvalidOperationException(new StringBuilder() + .AppendLine("The core services must be registered when enabling reference tokens support.") + .Append("To register the OpenIddict core services, use 'services.AddOpenIddict().AddCore()'.") + .ToString()); + } + + // Retrieve the token entry from the database. If it + // cannot be found, assume the token is not valid. + var token = await manager.FindByReferenceIdAsync(context.Token); + if (token == null) + { + logger.LogError("Authentication failed because the access token cannot be found in the database."); + + context.HandleResponse(); + return; + } + + // 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 manager.GetPayloadAsync(token); + if (string.IsNullOrEmpty(payload)) + { + logger.LogError("Authentication failed because the access token is not a reference token."); + + context.HandleResponse(); + return; + } + + var ticket = context.DataFormat.Unprotect(payload); + if (ticket == null) + { + logger.LogError("Authentication failed because the reference token cannot be decrypted. " + + "This may indicate that the token entry is corrupted or tampered."); + + context.HandleResponse(); + return; + } + + // Dynamically set the creation and expiration dates. + ticket.Properties.IssuedUtc = await manager.GetCreationDateAsync(token); + ticket.Properties.ExpiresUtc = await manager.GetExpirationDateAsync(token); + + // Restore the token and authorization identifiers attached with the database entry. + ticket.Properties.SetProperty(OpenIddictConstants.Properties.TokenId, await manager.GetIdAsync(token)); + ticket.Properties.SetProperty(OpenIddictConstants.Properties.AuthorizationId, + await manager.GetAuthorizationIdAsync(token)); + + context.Ticket = ticket; + context.HandleResponse(); + } + + await base.DecryptToken(context); + } + + public void Import([NotNull] OAuthValidationEvents events) + { + OnApplyChallenge = events.ApplyChallenge; + OnCreateTicket = events.CreateTicket; + OnDecryptToken = events.DecryptToken; + OnRetrieveToken = events.RetrieveToken; + OnValidateToken = events.ValidateToken; + } + } +} diff --git a/src/OpenIddict.Validation/Internal/OpenIddictValidationHandler.cs b/src/OpenIddict.Validation/Internal/OpenIddictValidationHandler.cs deleted file mode 100644 index 37cb1d82..00000000 --- a/src/OpenIddict.Validation/Internal/OpenIddictValidationHandler.cs +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - * See https://github.com/openiddict/openiddict-core for more information concerning - * the license and the contributors participating to this project. - */ - -using System; -using System.ComponentModel; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; -using AspNet.Security.OAuth.Validation; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Net.Http.Headers; -using Newtonsoft.Json.Linq; -using OpenIddict.Abstractions; - -namespace OpenIddict.Validation -{ - [EditorBrowsable(EditorBrowsableState.Never)] - public class OpenIddictValidationHandler : OAuthValidationHandler - { - protected override async Task HandleAuthenticateAsync() - { - if (!Options.UseReferenceTokens) - { - return await base.HandleAuthenticateAsync(); - } - - var context = new RetrieveTokenContext(Context, Options); - await Options.Events.RetrieveToken(context); - - if (context.HandledResponse) - { - // If no ticket has been provided, return a failed result to - // indicate that authentication was rejected by application code. - if (context.Ticket == null) - { - return AuthenticateResult.Fail("Authentication was stopped by application code."); - } - - return AuthenticateResult.Success(context.Ticket); - } - - else if (context.Skipped) - { - Logger.LogInformation("Authentication was skipped by application code."); - - return AuthenticateResult.Skip(); - } - - var token = context.Token; - - if (string.IsNullOrEmpty(token)) - { - // Try to retrieve the access token from the authorization header. - string header = Request.Headers[HeaderNames.Authorization]; - if (string.IsNullOrEmpty(header)) - { - Logger.LogDebug("Authentication was skipped because no bearer token was received."); - - return AuthenticateResult.Skip(); - } - - // Ensure that the authorization header contains the mandatory "Bearer" scheme. - // See https://tools.ietf.org/html/rfc6750#section-2.1 - if (!header.StartsWith(OAuthValidationConstants.Schemes.Bearer + ' ', StringComparison.OrdinalIgnoreCase)) - { - Logger.LogDebug("Authentication was skipped because an incompatible " + - "scheme was used in the 'Authorization' header."); - - return AuthenticateResult.Skip(); - } - - // Extract the token from the authorization header. - token = header.Substring(OAuthValidationConstants.Schemes.Bearer.Length + 1).Trim(); - - if (string.IsNullOrEmpty(token)) - { - Logger.LogDebug("Authentication was skipped because the bearer token " + - "was missing from the 'Authorization' header."); - - return AuthenticateResult.Skip(); - } - } - - // Try to unprotect the token and return an error - // if the ticket can't be decrypted or validated. - var result = await CreateTicketAsync(token); - if (!result.Succeeded) - { - Context.Features.Set(new OAuthValidationFeature - { - Error = new OAuthValidationError - { - Error = OAuthValidationConstants.Errors.InvalidToken, - ErrorDescription = "The access token is not valid." - } - }); - - return AuthenticateResult.Fail("Authentication failed because the access token was invalid."); - } - - // Ensure that the authentication ticket is still valid. - var ticket = result.Ticket; - if (ticket.Properties.ExpiresUtc.HasValue && - ticket.Properties.ExpiresUtc.Value < Options.SystemClock.UtcNow) - { - Context.Features.Set(new OAuthValidationFeature - { - Error = new OAuthValidationError - { - Error = OAuthValidationConstants.Errors.InvalidToken, - ErrorDescription = "The access token is no longer valid." - } - }); - - return AuthenticateResult.Fail("Authentication failed because the access token was expired."); - } - - // Ensure that the access token was issued - // to be used with this resource server. - if (!ValidateAudience(ticket)) - { - Context.Features.Set(new OAuthValidationFeature - { - Error = new OAuthValidationError - { - Error = OAuthValidationConstants.Errors.InvalidToken, - ErrorDescription = "The access token is not valid for this resource server." - } - }); - - return AuthenticateResult.Fail("Authentication failed because the access token " + - "was not valid for this resource server."); - } - - var notification = new ValidateTokenContext(Context, Options, ticket); - await Options.Events.ValidateToken(notification); - - if (notification.HandledResponse) - { - // If no ticket has been provided, return a failed result to - // indicate that authentication was rejected by application code. - if (notification.Ticket == null) - { - return AuthenticateResult.Fail("Authentication was stopped by application code."); - } - - return AuthenticateResult.Success(notification.Ticket); - } - - else if (notification.Skipped) - { - Logger.LogInformation("Authentication was skipped by application code."); - - return AuthenticateResult.Skip(); - } - - // Allow the application code to replace the ticket - // reference from the ValidateToken event. - ticket = notification.Ticket; - - if (ticket == null) - { - return AuthenticateResult.Fail("Authentication was stopped by application code."); - } - - return AuthenticateResult.Success(ticket); - } - - private bool ValidateAudience(AuthenticationTicket ticket) - { - // If no explicit audience has been configured, - // skip the default audience validation. - if (Options.Audiences.Count == 0) - { - return true; - } - - // Extract the audiences from the authentication ticket. - var audiences = ticket.Properties.GetProperty(OAuthValidationConstants.Properties.Audiences); - if (string.IsNullOrEmpty(audiences)) - { - return false; - } - - // Ensure that the authentication ticket contains one of the registered audiences. - foreach (var audience in JArray.Parse(audiences).Values()) - { - if (Options.Audiences.Contains(audience)) - { - return true; - } - } - - return false; - } - - private async Task CreateTicketAsync(string payload) - { - // Note: the token manager is deliberately not injected using constructor injection - // to allow using the validation handler without having to register the core services. - var manager = Context.RequestServices.GetService(); - if (manager == null) - { - throw new InvalidOperationException(new StringBuilder() - .AppendLine("The core services must be registered when enabling reference tokens support.") - .Append("To register the OpenIddict core services, use 'services.AddOpenIddict().AddCore()'.") - .ToString()); - } - - // Retrieve the token entry from the database. If it - // cannot be found, assume the token is not valid. - var token = await manager.FindByReferenceIdAsync(payload); - if (token == null) - { - return AuthenticateResult.Fail("Authentication failed because the access token cannot be found in the database."); - } - - // 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 ciphertext = await manager.GetPayloadAsync(token); - if (string.IsNullOrEmpty(ciphertext)) - { - return AuthenticateResult.Fail("Authentication failed because the access token is not a reference token."); - } - - var ticket = Options.AccessTokenFormat.Unprotect(ciphertext); - if (ticket == null) - { - return AuthenticateResult.Fail( - "Authentication failed because the reference token cannot be decrypted. " + - "This may indicate that the token entry is corrupted or tampered."); - } - - // Dynamically set the creation and expiration dates. - ticket.Properties.IssuedUtc = await manager.GetCreationDateAsync(token); - ticket.Properties.ExpiresUtc = await manager.GetExpirationDateAsync(token); - - // Restore the token and authorization identifiers attached with the database entry. - ticket.Properties.SetProperty(OpenIddictConstants.Properties.TokenId, await manager.GetIdAsync(token)); - ticket.Properties.SetProperty(OpenIddictConstants.Properties.AuthorizationId, - await manager.GetAuthorizationIdAsync(token)); - - if (Options.SaveToken) - { - // Store the access token in the authentication ticket. - ticket.Properties.StoreTokens(new[] - { - new AuthenticationToken { Name = OAuthValidationConstants.Properties.Token, Value = payload } - }); - } - - // Resolve the primary identity associated with the principal. - var identity = (ClaimsIdentity) ticket.Principal.Identity; - - // Copy the scopes extracted from the authentication ticket to the - // ClaimsIdentity to make them easier to retrieve from application code. - var scopes = ticket.Properties.GetProperty(OAuthValidationConstants.Properties.Scopes); - if (!string.IsNullOrEmpty(scopes)) - { - foreach (var scope in JArray.Parse(scopes).Values()) - { - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Scope, scope)); - } - } - - var notification = new CreateTicketContext(Context, Options, ticket); - await Options.Events.CreateTicket(notification); - - if (notification.HandledResponse) - { - // If no ticket has been provided, return a failed result to - // indicate that authentication was rejected by application code. - if (notification.Ticket == null) - { - return AuthenticateResult.Skip(); - } - - return AuthenticateResult.Success(notification.Ticket); - } - - else if (notification.Skipped) - { - return AuthenticateResult.Skip(); - } - - return AuthenticateResult.Success(notification.Ticket); - } - - private new OpenIddictValidationOptions Options => (OpenIddictValidationOptions) base.Options; - } -} diff --git a/src/OpenIddict.Validation/Internal/OpenIddictValidationMiddleware.cs b/src/OpenIddict.Validation/Internal/OpenIddictValidationMiddleware.cs deleted file mode 100644 index b8cf5822..00000000 --- a/src/OpenIddict.Validation/Internal/OpenIddictValidationMiddleware.cs +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - * See https://github.com/openiddict/openiddict-core for more information concerning - * the license and the contributors participating to this project. - */ - -using System.ComponentModel; -using System.Text.Encodings.Web; -using AspNet.Security.OAuth.Validation; -using JetBrains.Annotations; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.DataProtection; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -namespace OpenIddict.Validation -{ - [EditorBrowsable(EditorBrowsableState.Never)] - public class OpenIddictValidationMiddleware : OAuthValidationMiddleware - { - public OpenIddictValidationMiddleware( - [NotNull] RequestDelegate next, - [NotNull] IOptions options, - [NotNull] ILoggerFactory loggerFactory, - [NotNull] UrlEncoder encoder, - [NotNull] IDataProtectionProvider dataProtectionProvider) - : base(next, options, loggerFactory, encoder, dataProtectionProvider) - { - } - - protected override AuthenticationHandler CreateHandler() - => new OpenIddictValidationHandler(); - } -} diff --git a/src/OpenIddict.Validation/OpenIddictValidationBuilder.cs b/src/OpenIddict.Validation/OpenIddictValidationBuilder.cs index f626f9be..be66ab92 100644 --- a/src/OpenIddict.Validation/OpenIddictValidationBuilder.cs +++ b/src/OpenIddict.Validation/OpenIddictValidationBuilder.cs @@ -7,8 +7,11 @@ using System; using System.ComponentModel; using System.Linq; +using System.Reflection; +using AspNet.Security.OAuth.Validation; using JetBrains.Annotations; using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection.Extensions; using OpenIddict.Validation; namespace Microsoft.Extensions.DependencyInjection @@ -77,6 +80,23 @@ namespace Microsoft.Extensions.DependencyInjection return Configure(options => options.Audiences.UnionWith(audiences)); } + /// + /// Registers application-specific OAuth2 validation events that are automatically + /// invoked for each request handled by the OpenIddict validation handler. + /// + /// The custom service. + /// The . + [EditorBrowsable(EditorBrowsableState.Advanced)] + public OpenIddictValidationBuilder RegisterEvents([NotNull] OAuthValidationEvents events) + { + if (events == null) + { + throw new ArgumentNullException(nameof(events)); + } + + return Configure(options => options.ApplicationEvents = events); + } + /// /// Configures OpenIddict not to return the authentication error /// details as part of the standard WWW-Authenticate response header. @@ -100,13 +120,6 @@ namespace Microsoft.Extensions.DependencyInjection return Configure(options => options.Realm = realm); } - /// - /// Configures the OpenIddict validation handler to use reference tokens. - /// - /// The . - public OpenIddictValidationBuilder UseReferenceTokens() - => Configure(options => options.UseReferenceTokens = true); - /// /// Configures OpenIddict to use a specific data protection provider /// instead of relying on the default instance provided by the DI container. @@ -122,5 +135,12 @@ namespace Microsoft.Extensions.DependencyInjection return Configure(options => options.DataProtectionProvider = provider); } + + /// + /// Configures the OpenIddict validation handler to use reference tokens. + /// + /// The . + public OpenIddictValidationBuilder UseReferenceTokens() + => Configure(options => options.UseReferenceTokens = true); } } \ No newline at end of file diff --git a/src/OpenIddict.Validation/OpenIddictValidationExtensions.cs b/src/OpenIddict.Validation/OpenIddictValidationExtensions.cs index fe64f6d5..cf4e2e3f 100644 --- a/src/OpenIddict.Validation/OpenIddictValidationExtensions.cs +++ b/src/OpenIddict.Validation/OpenIddictValidationExtensions.cs @@ -88,7 +88,19 @@ namespace Microsoft.Extensions.DependencyInjection options.AccessTokenFormat = new TicketDataFormat(protector); } - return app.UseMiddleware(new OptionsWrapper(options)); + // If application events have been registered, import the events into the main provider. + if (options.ApplicationEvents != null) + { + var events = options.Events as OpenIddictValidationEvents; + if (events == null) + { + throw new InvalidOperationException("The specified OAuth2 validation events are not compatible."); + } + + events.Import(options.ApplicationEvents); + } + + return app.UseOAuthValidation(options); } } } \ No newline at end of file diff --git a/src/OpenIddict.Validation/OpenIddictValidationOptions.cs b/src/OpenIddict.Validation/OpenIddictValidationOptions.cs index 3409cd77..cc275271 100644 --- a/src/OpenIddict.Validation/OpenIddictValidationOptions.cs +++ b/src/OpenIddict.Validation/OpenIddictValidationOptions.cs @@ -4,12 +4,30 @@ * the license and the contributors participating to this project. */ +using System; using AspNet.Security.OAuth.Validation; namespace OpenIddict.Validation { + /// + /// Provides various settings needed to configure the OpenIddict validation handler. + /// public class OpenIddictValidationOptions : OAuthValidationOptions { + /// + /// Creates a new instance of the class. + /// + public OpenIddictValidationOptions() + { + Events = new OpenIddictValidationEvents(); + } + + /// + /// Gets or sets the user-provided that the OpenIddict + /// validation handler invokes to enable developer control over the entire authentication process. + /// + public OAuthValidationEvents ApplicationEvents { get; set; } + /// /// Gets or sets a boolean indicating whether reference tokens are used. /// diff --git a/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Authentication.cs b/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Authentication.cs index 78f0b2f5..25725861 100644 --- a/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Authentication.cs +++ b/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Authentication.cs @@ -4,6 +4,7 @@ * the license and the contributors participating to this project. */ +using System.Collections.Immutable; using System.IO; using System.Security.Cryptography; using System.Threading; @@ -198,6 +199,14 @@ namespace OpenIddict.Server.Tests // Arrange var server = CreateAuthorizationServer(builder => { + builder.Services.AddSingleton(CreateScopeManager(instance => + { + instance.Setup(mock => mock.FindByNamesAsync( + It.Is>(scopes => scopes.Length == 1 && scopes[0] == "unregistered_scope"), + It.IsAny())) + .ReturnsAsync(ImmutableArray.Create()); + })); + builder.EnableScopeValidation(); }); @@ -213,7 +222,7 @@ namespace OpenIddict.Server.Tests }); // Assert - Assert.Equal(OpenIdConnectConstants.Errors.InvalidRequest, response.Error); + Assert.Equal(OpenIdConnectConstants.Errors.InvalidScope, response.Error); Assert.Equal("The specified 'scope' parameter is not valid.", response.ErrorDescription); } @@ -276,10 +285,17 @@ namespace OpenIddict.Server.Tests public async Task ValidateAuthorizationRequest_RequestIsValidatedWhenRegisteredScopeIsSpecified() { // Arrange + var scope = new OpenIddictScope(); + var manager = CreateScopeManager(instance => { - instance.Setup(mock => mock.FindByNameAsync("registered_scope", It.IsAny())) - .ReturnsAsync(new OpenIddictScope()); + instance.Setup(mock => mock.FindByNamesAsync( + It.Is>(scopes => scopes.Length == 1 && scopes[0] == "scope_registered_in_database"), + It.IsAny())) + .ReturnsAsync(ImmutableArray.Create(scope)); + + instance.Setup(mock => mock.GetNameAsync(scope, It.IsAny())) + .Returns(new ValueTask("scope_registered_in_database")); }); var server = CreateAuthorizationServer(builder => @@ -306,10 +322,16 @@ namespace OpenIddict.Server.Tests .ReturnsAsync(true); instance.Setup(mock => mock.HasPermissionAsync(application, - OpenIddictConstants.Permissions.Prefixes.Scope + "registered_scope", It.IsAny())) + OpenIddictConstants.Permissions.Prefixes.Scope + "scope_registered_in_database", It.IsAny())) + .ReturnsAsync(true); + + instance.Setup(mock => mock.HasPermissionAsync(application, + OpenIddictConstants.Permissions.Prefixes.Scope + "scope_registered_in_options", It.IsAny())) .ReturnsAsync(true); })); + builder.RegisterScopes("scope_registered_in_options"); + builder.EnableScopeValidation(); builder.Services.AddSingleton(manager); }); @@ -323,7 +345,7 @@ namespace OpenIddict.Server.Tests Nonce = "n-0S6_WzA2Mj", RedirectUri = "http://www.fabrikam.com/path", ResponseType = OpenIdConnectConstants.ResponseTypes.Token, - Scope = "registered_scope" + Scope = "scope_registered_in_database scope_registered_in_options" }); // Assert diff --git a/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Exchange.cs b/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Exchange.cs index 502cc339..d6d1ac01 100644 --- a/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Exchange.cs +++ b/test/OpenIddict.Server.Tests/Internal/OpenIddictServerProviderTests.Exchange.cs @@ -110,6 +110,14 @@ namespace OpenIddict.Server.Tests // Arrange var server = CreateAuthorizationServer(builder => { + builder.Services.AddSingleton(CreateScopeManager(instance => + { + instance.Setup(mock => mock.FindByNamesAsync( + It.Is>(scopes => scopes.Length == 1 && scopes[0] == "unregistered_scope"), + It.IsAny())) + .ReturnsAsync(ImmutableArray.Create()); + })); + builder.EnableScopeValidation(); }); @@ -125,7 +133,7 @@ namespace OpenIddict.Server.Tests }); // Assert - Assert.Equal(OpenIdConnectConstants.Errors.InvalidRequest, response.Error); + Assert.Equal(OpenIdConnectConstants.Errors.InvalidScope, response.Error); Assert.Equal("The specified 'scope' parameter is not valid.", response.ErrorDescription); } @@ -161,14 +169,24 @@ namespace OpenIddict.Server.Tests public async Task ValidateTokenRequest_RequestIsValidatedWhenRegisteredScopeIsSpecified() { // Arrange + var scope = new OpenIddictScope(); + var manager = CreateScopeManager(instance => { - instance.Setup(mock => mock.FindByNameAsync("registered_scope", It.IsAny())) - .ReturnsAsync(new OpenIddictScope()); + instance.Setup(mock => mock.FindByNamesAsync( + It.Is>(scopes => scopes.Length == 1 && scopes[0] == "scope_registered_in_database"), + It.IsAny())) + .ReturnsAsync(ImmutableArray.Create(scope)); + + instance.Setup(mock => mock.GetNameAsync(scope, It.IsAny())) + .Returns(new ValueTask("scope_registered_in_database")); }); var server = CreateAuthorizationServer(builder => { + builder.EnableScopeValidation(); + builder.RegisterScopes("scope_registered_in_options"); + builder.Services.AddSingleton(manager); }); @@ -180,7 +198,7 @@ namespace OpenIddict.Server.Tests GrantType = OpenIdConnectConstants.GrantTypes.Password, Username = "johndoe", Password = "A3ddj3w", - Scope = "registered_scope" + Scope = "scope_registered_in_database scope_registered_in_options" }); // Assert diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs index abd27bae..28d64c5d 100644 --- a/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs +++ b/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs @@ -8,6 +8,7 @@ using System; using System.IdentityModel.Tokens.Jwt; using System.Reflection; using AspNet.Security.OpenIdConnect.Primitives; +using AspNet.Security.OpenIdConnect.Server; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -595,6 +596,22 @@ namespace OpenIddict.Server.Tests Assert.Equal(new Uri("http://www.fabrikam.com/"), options.Value.Issuer); } + [Fact] + public void RegisterProvider_ProviderIsAttached() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.RegisterProvider(new OpenIdConnectServerProvider()); + + var options = GetOptions(services); + + // Assert + Assert.NotNull(options.ApplicationProvider); + } + [Fact] public void RegisterClaims_ClaimsAreAdded() { @@ -704,10 +721,5 @@ namespace OpenIddict.Server.Tests var options = provider.GetRequiredService>(); return options.Value; } - - public class OpenIddictApplication { } - public class OpenIddictAuthorization { } - public class OpenIddictScope { } - public class OpenIddictToken { } } } diff --git a/test/OpenIddict.Validation.Tests/Internal/OpenIddictValidationEventsTests.cs b/test/OpenIddict.Validation.Tests/Internal/OpenIddictValidationEventsTests.cs new file mode 100644 index 00000000..dd464132 --- /dev/null +++ b/test/OpenIddict.Validation.Tests/Internal/OpenIddictValidationEventsTests.cs @@ -0,0 +1,352 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using System; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using AspNet.Security.OAuth.Validation; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Authentication; +using Microsoft.AspNetCore.Http.Features.Authentication; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OpenIddict.Abstractions; +using OpenIddict.Core; +using Xunit; + +namespace OpenIddict.Validation.Tests +{ + public class OpenIddictValidationEventsTests + { + [Fact] + public async Task DecryptToken_ThrowsAnExceptionWhenTokenManagerIsNotRegistered() + { + // Arrange + var server = CreateResourceServer(builder => + { + foreach (var service in builder.Services.ToArray()) + { + if (service.ServiceType == typeof(IOpenIddictTokenManager)) + { + builder.Services.Remove(service); + } + } + }); + + var client = server.CreateClient(); + + var request = new HttpRequestMessage(HttpMethod.Get, "/"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-reference-token-id"); + + // Act and assert + var exception = await Assert.ThrowsAsync(delegate + { + return client.SendAsync(request); + }); + + Assert.Equal(new StringBuilder() + .AppendLine("The core services must be registered when enabling reference tokens support.") + .Append("To register the OpenIddict core services, use 'services.AddOpenIddict().AddCore()'.") + .ToString(), exception.Message); + } + + [Fact] + public async Task DecryptToken_ReturnsFailedResultForUnknownReferenceToken() + { + // Arrange + var manager = CreateTokenManager(instance => + { + instance.Setup(mock => mock.FindByReferenceIdAsync("invalid-reference-token-id", It.IsAny())) + .ReturnsAsync(value: null); + }); + + var server = CreateResourceServer(builder => + { + builder.Services.AddSingleton(manager); + }); + + var client = server.CreateClient(); + + var request = new HttpRequestMessage(HttpMethod.Get, "/"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "invalid-reference-token-id"); + + // Act + var response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + Mock.Get(manager).Verify(mock => mock.FindByReferenceIdAsync("invalid-reference-token-id", It.IsAny()), Times.Once()); + } + + [Fact] + public async Task DecryptToken_ReturnsFailedResultForNonReferenceToken() + { + // Arrange + var token = new OpenIddictToken(); + + var manager = CreateTokenManager(instance => + { + instance.Setup(mock => mock.FindByReferenceIdAsync("valid-reference-token-id", It.IsAny())) + .ReturnsAsync(token); + + instance.Setup(mock => mock.GetPayloadAsync(token, It.IsAny())) + .Returns(new ValueTask(result: null)); + }); + + var server = CreateResourceServer(builder => + { + builder.Services.AddSingleton(manager); + }); + + var client = server.CreateClient(); + + var request = new HttpRequestMessage(HttpMethod.Get, "/"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-reference-token-id"); + + // Act + var response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + Mock.Get(manager).Verify(mock => mock.FindByReferenceIdAsync("valid-reference-token-id", It.IsAny()), Times.Once()); + Mock.Get(manager).Verify(mock => mock.GetPayloadAsync(token, It.IsAny()), Times.Once()); + } + + [Fact] + public async Task DecryptToken_ReturnsFailedResultForInvalidReferenceTokenPayload() + { + // Arrange + var token = new OpenIddictToken(); + + var format = new Mock>(); + format.Setup(mock => mock.Unprotect("invalid-reference-token-payload")) + .Returns(value: null); + + var manager = CreateTokenManager(instance => + { + instance.Setup(mock => mock.FindByReferenceIdAsync("valid-reference-token-id", It.IsAny())) + .ReturnsAsync(token); + + instance.Setup(mock => mock.GetPayloadAsync(token, It.IsAny())) + .Returns(new ValueTask("invalid-reference-token-payload")); + }); + + var server = CreateResourceServer(builder => + { + builder.Services.AddSingleton(manager); + builder.Configure(options => options.AccessTokenFormat = format.Object); + }); + + var client = server.CreateClient(); + + var request = new HttpRequestMessage(HttpMethod.Get, "/"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-reference-token-id"); + + // Act + var response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + Mock.Get(manager).Verify(mock => mock.FindByReferenceIdAsync("valid-reference-token-id", It.IsAny()), Times.Once()); + Mock.Get(manager).Verify(mock => mock.GetPayloadAsync(token, It.IsAny()), Times.Once()); + format.Verify(mock => mock.Unprotect("invalid-reference-token-payload"), Times.Once()); + } + + [Fact] + public async Task DecryptToken_ReturnsValidResultForValidReferenceToken() + { + // Arrange + var token = new OpenIddictToken(); + + var format = new Mock>(); + format.Setup(mock => mock.Unprotect("valid-reference-token-payload")) + .Returns(delegate + { + var identity = new ClaimsIdentity(OpenIddictValidationDefaults.AuthenticationScheme); + identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); + + return new AuthenticationTicket( + new ClaimsPrincipal(identity), + new AuthenticationProperties(), + OpenIddictValidationDefaults.AuthenticationScheme); + }); + + var manager = CreateTokenManager(instance => + { + instance.Setup(mock => mock.FindByReferenceIdAsync("valid-reference-token-id", It.IsAny())) + .ReturnsAsync(token); + + instance.Setup(mock => mock.GetPayloadAsync(token, It.IsAny())) + .Returns(new ValueTask("valid-reference-token-payload")); + + instance.Setup(mock => mock.GetCreationDateAsync(token, It.IsAny())) + .Returns(new ValueTask(new DateTimeOffset(2018, 01, 01, 00, 00, 00, TimeSpan.Zero))); + + instance.Setup(mock => mock.GetExpirationDateAsync(token, It.IsAny())) + .Returns(new ValueTask(new DateTimeOffset(2918, 01, 01, 00, 00, 00, TimeSpan.Zero))); + }); + + var server = CreateResourceServer(builder => + { + builder.Services.AddSingleton(manager); + builder.Configure(options => options.AccessTokenFormat = format.Object); + }); + + var client = server.CreateClient(); + + var request = new HttpRequestMessage(HttpMethod.Get, "/ticket"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-reference-token-id"); + + // Act + var response = await client.SendAsync(request); + + var ticket = JObject.Parse(await response.Content.ReadAsStringAsync()); + var properties = (from property in ticket.Value("Properties") + select new + { + Name = property.Value("Name"), + Value = property.Value("Value") + }).ToDictionary(property => property.Name, property => property.Value); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + Assert.Equal( + new DateTimeOffset(2018, 01, 01, 00, 00, 00, TimeSpan.Zero), + DateTimeOffset.Parse(properties[".issued"], CultureInfo.InvariantCulture)); + Assert.Equal( + new DateTimeOffset(2918, 01, 01, 00, 00, 00, TimeSpan.Zero), + DateTimeOffset.Parse(properties[".expires"], CultureInfo.InvariantCulture)); + + Mock.Get(manager).Verify(mock => mock.FindByReferenceIdAsync("valid-reference-token-id", It.IsAny()), Times.Once()); + Mock.Get(manager).Verify(mock => mock.GetPayloadAsync(token, It.IsAny()), Times.Once()); + Mock.Get(manager).Verify(mock => mock.GetCreationDateAsync(token, It.IsAny()), Times.Once()); + Mock.Get(manager).Verify(mock => mock.GetExpirationDateAsync(token, It.IsAny()), Times.Once()); + format.Verify(mock => mock.Unprotect("valid-reference-token-payload"), Times.Once()); + } + + private static TestServer CreateResourceServer(Action configuration = null) + { + var builder = new WebHostBuilder(); + builder.UseEnvironment("Testing"); + + builder.ConfigureLogging(options => options.AddDebug()); + + builder.ConfigureServices(services => + { + services.AddOpenIddict() + .AddCore(options => + { + options.SetDefaultTokenEntity(); + options.Services.AddSingleton(CreateTokenManager()); + }) + + .AddValidation(options => + { + options.UseReferenceTokens(); + + // Note: overriding the default data protection provider is not necessary for the tests to pass, + // but is useful to ensure unnecessary keys are not persisted in testing environments, which also + // helps make the unit tests run faster, as no registry or disk access is required in this case. + options.UseDataProtectionProvider(new EphemeralDataProtectionProvider()); + + // Run the configuration delegate + // registered by the unit tests. + configuration?.Invoke(options); + }); + }); + + builder.Configure(app => + { + app.UseOpenIddictValidation(); + + app.Map("/ticket", map => map.Run(async context => + { + var result = new AuthenticateContext(OpenIddictValidationDefaults.AuthenticationScheme); + await context.Authentication.AuthenticateAsync(result); + + if (result.Principal == null) + { + await context.Authentication.ChallengeAsync(OpenIddictValidationDefaults.AuthenticationScheme); + + return; + } + + context.Response.ContentType = "application/json"; + + // Return the authentication ticket as a JSON object. + await context.Response.WriteAsync(JsonConvert.SerializeObject(new + { + Claims = from claim in result.Principal.Claims + select new { claim.Type, claim.Value }, + + Properties = from property in result.Properties + select new { Name = property.Key, property.Value } + })); + })); + + app.Run(async context => + { + var result = new AuthenticateContext(OpenIddictValidationDefaults.AuthenticationScheme); + await context.Authentication.AuthenticateAsync(result); + + if (result.Principal == null) + { + await context.Authentication.ChallengeAsync(OpenIddictValidationDefaults.AuthenticationScheme); + + return; + } + + var subject = result.Principal.FindFirst(OAuthValidationConstants.Claims.Subject)?.Value; + if (string.IsNullOrEmpty(subject)) + { + await context.Authentication.ChallengeAsync(OpenIddictValidationDefaults.AuthenticationScheme); + + return; + } + + await context.Response.WriteAsync(subject); + }); + }); + + return new TestServer(builder); + } + + private static OpenIddictTokenManager CreateTokenManager( + Action>> configuration = null) + { + var manager = new Mock>( + Mock.Of(), + Mock.Of>>(), + Mock.Of>()); + + configuration?.Invoke(manager); + + return manager.Object; + } + + public class OpenIddictToken { } + } +} diff --git a/test/OpenIddict.Validation.Tests/OpenIddict.Validation.Tests.csproj b/test/OpenIddict.Validation.Tests/OpenIddict.Validation.Tests.csproj index 2290da3e..febc3998 100644 --- a/test/OpenIddict.Validation.Tests/OpenIddict.Validation.Tests.csproj +++ b/test/OpenIddict.Validation.Tests/OpenIddict.Validation.Tests.csproj @@ -12,6 +12,7 @@ + diff --git a/test/OpenIddict.Validation.Tests/OpenIddictValidationBuilderTests.cs b/test/OpenIddict.Validation.Tests/OpenIddictValidationBuilderTests.cs new file mode 100644 index 00000000..76fba718 --- /dev/null +++ b/test/OpenIddict.Validation.Tests/OpenIddictValidationBuilderTests.cs @@ -0,0 +1,141 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using AspNet.Security.OAuth.Validation; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Xunit; + +namespace OpenIddict.Validation.Tests +{ + public class OpenIddictValidationBuilderTests + { + [Fact] + public void Configure_OptionsAreCorrectlyAmended() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.Configure(configuration => configuration.ClaimsIssuer = "custom_issuer"); + + var options = GetOptions(services); + + // Assert + Assert.Equal("custom_issuer", options.ClaimsIssuer); + } + + [Fact] + public void AddAudiences_AudiencesAreAdded() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.AddAudiences("Fabrikam", "Contoso"); + + var options = GetOptions(services); + + // Assert + Assert.Equal(new[] { "Fabrikam", "Contoso" }, options.Audiences); + } + + [Fact] + public void RegisterEvents_EventsAreAttached() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.RegisterEvents(new OAuthValidationEvents()); + + var options = GetOptions(services); + + // Assert + Assert.NotNull(options.ApplicationEvents); + } + + [Fact] + public void RemoveErrorDetails_IncludeErrorDetailsIsSetToFalse() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.RemoveErrorDetails(); + + var options = GetOptions(services); + + // Assert + Assert.False(options.IncludeErrorDetails); + } + + [Fact] + public void SetRealm_RealmIsReplaced() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.SetRealm("custom_realm"); + + var options = GetOptions(services); + + // Assert + Assert.Equal("custom_realm", options.Realm); + } + + [Fact] + public void UseDataProtectionProvider_DefaultProviderIsReplaced() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.UseDataProtectionProvider(new EphemeralDataProtectionProvider()); + + var options = GetOptions(services); + + // Assert + Assert.IsType(options.DataProtectionProvider); + } + + [Fact] + public void UseReferenceTokens_ReferenceTokensAreEnabled() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.UseReferenceTokens(); + + var options = GetOptions(services); + + // Assert + Assert.True(options.UseReferenceTokens); + } + + private static IServiceCollection CreateServices() + => new ServiceCollection().AddOptions(); + + private static OpenIddictValidationBuilder CreateBuilder(IServiceCollection services) + => new OpenIddictValidationBuilder(services); + + private static OpenIddictValidationOptions GetOptions(IServiceCollection services) + { + var provider = services.BuildServiceProvider(); + return provider.GetRequiredService>().Value; + } + } +} diff --git a/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlerTests.cs b/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlerTests.cs deleted file mode 100644 index 093c1f1c..00000000 --- a/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlerTests.cs +++ /dev/null @@ -1,904 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - * See https://github.com/openiddict/openiddict-core for more information concerning - * the license and the contributors participating to this project. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Claims; -using System.Threading.Tasks; -using AspNet.Security.OAuth.Validation; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.DataProtection; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Authentication; -using Microsoft.AspNetCore.Http.Features.Authentication; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Moq; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenIddict.Abstractions; -using OpenIddict.Core; -using Xunit; - -namespace OpenIddict.Validation.Tests -{ - public class OpenIddictValidationHandlerTests - { - [Fact] - public async Task HandleAuthenticateAsync_InvalidTokenCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "invalid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_ValidTokenAllowsSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_MissingAudienceCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.AddAudiences("http://www.fabrikam.com/"); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_InvalidAudienceCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.AddAudiences("http://www.fabrikam.com/"); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token-with-single-audience"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_ValidAudienceAllowsSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.AddAudiences("http://www.fabrikam.com/"); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token-with-multiple-audiences"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_AnyMatchingAudienceCausesSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.AddAudiences("http://www.contoso.com/"); - builder.AddAudiences("http://www.fabrikam.com/"); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token-with-single-audience"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_MultipleMatchingAudienceCausesSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.AddAudiences("http://www.contoso.com/"); - builder.AddAudiences("http://www.fabrikam.com/"); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token-with-multiple-audiences"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_ExpiredTicketCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "expired-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_AuthenticationTicketContainsRequiredClaims() - { - // Arrange - var server = CreateResourceServer(); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/ticket"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token-with-scopes"); - - // Act - var response = await client.SendAsync(request); - - var ticket = JObject.Parse(await response.Content.ReadAsStringAsync()); - var claims = from claim in ticket.Value("Claims") - select new - { - Type = claim.Value(nameof(Claim.Type)), - Value = claim.Value(nameof(Claim.Value)) - }; - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - Assert.Contains(claims, claim => claim.Type == OAuthValidationConstants.Claims.Subject && - claim.Value == "Fabrikam"); - - Assert.Contains(claims, claim => claim.Type == OAuthValidationConstants.Claims.Scope && - claim.Value == "C54A8F5E-0387-43F4-BA43-FD4B50DC190D"); - - Assert.Contains(claims, claim => claim.Type == OAuthValidationConstants.Claims.Scope && - claim.Value == "5C57E3BD-9EFB-4224-9AB8-C8C5E009FFD7"); - } - - [Fact] - public async Task HandleAuthenticateAsync_AuthenticationTicketContainsRequiredProperties() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.SaveToken = true); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/ticket"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - var ticket = JObject.Parse(await response.Content.ReadAsStringAsync()); - var properties = from claim in ticket.Value("Properties") - select new - { - Name = claim.Value("Name"), - Value = claim.Value("Value") - }; - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - Assert.Contains(properties, property => property.Name == ".Token.access_token" && - property.Value == "valid-token"); - } - - [Fact] - public async Task HandleAuthenticateAsync_InvalidReplacedTokenCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnRetrieveToken = context => - { - context.Token = "invalid-token"; - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_ValidReplacedTokenCausesSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnRetrieveToken = context => - { - context.Token = "valid-token"; - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "invalid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_SkipToNextMiddlewareFromReceiveTokenCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnRetrieveToken = context => - { - context.SkipToNextMiddleware(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_NullTicketAndHandleResponseFromReceiveTokenCauseInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnRetrieveToken = context => - { - context.Ticket = null; - context.HandleResponse(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_ReplacedTicketAndHandleResponseFromReceiveTokenCauseSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnRetrieveToken = context => - { - var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); - - context.Ticket = new AuthenticationTicket( - new ClaimsPrincipal(identity), - new AuthenticationProperties(), - context.Options.AuthenticationScheme); - - context.HandleResponse(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "invalid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_SkipToNextMiddlewareFromValidateTokenCausesInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnValidateToken = context => - { - context.SkipToNextMiddleware(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_NullTicketAndHandleResponseFromValidateTokenCauseInvalidAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnValidateToken = context => - { - context.Ticket = null; - context.HandleResponse(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task HandleAuthenticateAsync_ReplacedTicketAndHandleResponseFromValidateTokenCauseSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnValidateToken = context => - { - var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Contoso")); - - context.Ticket = new AuthenticationTicket( - new ClaimsPrincipal(identity), - new AuthenticationProperties(), - context.Options.AuthenticationScheme); - - context.HandleResponse(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Contoso", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleAuthenticateAsync_UpdatedTicketFromValidateTokenCausesSuccessfulAuthentication() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnValidateToken = context => - { - var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Contoso")); - - context.Ticket = new AuthenticationTicket( - new ClaimsPrincipal(identity), - new AuthenticationProperties(), - context.Options.AuthenticationScheme); - - context.HandleResponse(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token"); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Contoso", await response.Content.ReadAsStringAsync()); - } - - [Fact] - public async Task HandleUnauthorizedAsync_ErrorDetailsAreResolvedFromChallengeContext() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.RemoveErrorDetails(); - builder.SetRealm("global_realm"); - - builder.Configure(options => options.Events.OnApplyChallenge = context => - { - // Assert - Assert.Equal(context.Error, "custom_error"); - Assert.Equal(context.ErrorDescription, "custom_error_description"); - Assert.Equal(context.ErrorUri, "custom_error_uri"); - Assert.Equal(context.Realm, "custom_realm"); - Assert.Equal(context.Scope, "custom_scope"); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("/challenge"); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Equal(@"Bearer realm=""custom_realm"", error=""custom_error"", error_description=""custom_error_description"", " + - @"error_uri=""custom_error_uri"", scope=""custom_scope""", response.Headers.WwwAuthenticate.ToString()); - } - - [Theory] - [InlineData("invalid-token", OAuthValidationConstants.Errors.InvalidToken, "The access token is not valid.")] - [InlineData("expired-token", OAuthValidationConstants.Errors.InvalidToken, "The access token is no longer valid.")] - public async Task HandleUnauthorizedAsync_ErrorDetailsAreInferredFromAuthenticationFailure( - string token, string error, string description) - { - // Arrange - var server = CreateResourceServer(); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Get, "/"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - - // Act - var response = await client.SendAsync(request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Equal($@"Bearer error=""{error}"", error_description=""{description}""", - response.Headers.WwwAuthenticate.ToString()); - } - - [Fact] - public async Task HandleUnauthorizedAsync_ApplyChallenge_AllowsHandlingResponse() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnApplyChallenge = context => - { - context.HandleResponse(); - context.HttpContext.Response.Headers["X-Custom-Authentication-Header"] = "Bearer"; - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("/challenge"); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Empty(response.Headers.WwwAuthenticate); - Assert.Equal(new[] { "Bearer" }, response.Headers.GetValues("X-Custom-Authentication-Header")); - } - - [Fact] - public async Task HandleUnauthorizedAsync_ApplyChallenge_AllowsSkippingToNextMiddleware() - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnApplyChallenge = context => - { - context.SkipToNextMiddleware(); - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("/challenge"); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Empty(response.Headers.WwwAuthenticate); - Assert.Empty(await response.Content.ReadAsStringAsync()); - } - - [Theory] - [InlineData(null, null, null, null, null, "Bearer")] - [InlineData("custom_error", null, null, null, null, @"Bearer error=""custom_error""")] - [InlineData(null, "custom_error_description", null, null, null, @"Bearer error_description=""custom_error_description""")] - [InlineData(null, null, "custom_error_uri", null, null, @"Bearer error_uri=""custom_error_uri""")] - [InlineData(null, null, null, "custom_realm", null, @"Bearer realm=""custom_realm""")] - [InlineData(null, null, null, null, "custom_scope", @"Bearer scope=""custom_scope""")] - [InlineData("custom_error", "custom_error_description", "custom_error_uri", "custom_realm", "custom_scope", - @"Bearer realm=""custom_realm"", error=""custom_error"", " + - @"error_description=""custom_error_description"", " + - @"error_uri=""custom_error_uri"", scope=""custom_scope""")] - public async Task HandleUnauthorizedAsync_ReturnsExpectedWwwAuthenticateHeader( - string error, string description, string uri, string realm, string scope, string header) - { - // Arrange - var server = CreateResourceServer(builder => - { - builder.Configure(options => options.Events.OnApplyChallenge = context => - { - context.Error = error; - context.ErrorDescription = description; - context.ErrorUri = uri; - context.Realm = realm; - context.Scope = scope; - - return Task.FromResult(0); - }); - }); - - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("/challenge"); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Equal(header, response.Headers.WwwAuthenticate.ToString()); - } - - private static TestServer CreateResourceServer(Action configuration = null) - { - var format = new Mock>(MockBehavior.Strict); - - format.Setup(mock => mock.Unprotect(It.Is(token => token == "invalid-token"))) - .Returns(value: null); - - format.Setup(mock => mock.Unprotect(It.Is(token => token == "valid-token"))) - .Returns(delegate - { - var identity = new ClaimsIdentity(OpenIddictValidationDefaults.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); - - var properties = new AuthenticationProperties(); - - return new AuthenticationTicket(new ClaimsPrincipal(identity), - properties, OpenIddictValidationDefaults.AuthenticationScheme); - }); - - format.Setup(mock => mock.Unprotect(It.Is(token => token == "valid-token-with-scopes"))) - .Returns(delegate - { - var identity = new ClaimsIdentity(OpenIddictValidationDefaults.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); - - var properties = new AuthenticationProperties(); - properties.Items[OAuthValidationConstants.Properties.Scopes] = - @"[""C54A8F5E-0387-43F4-BA43-FD4B50DC190D"",""5C57E3BD-9EFB-4224-9AB8-C8C5E009FFD7""]"; - - return new AuthenticationTicket(new ClaimsPrincipal(identity), - properties, OpenIddictValidationDefaults.AuthenticationScheme); - }); - - format.Setup(mock => mock.Unprotect(It.Is(token => token == "valid-token-with-single-audience"))) - .Returns(delegate - { - var identity = new ClaimsIdentity(OpenIddictValidationDefaults.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); - - var properties = new AuthenticationProperties(new Dictionary - { - [OAuthValidationConstants.Properties.Audiences] = @"[""http://www.contoso.com/""]" - }); - - return new AuthenticationTicket(new ClaimsPrincipal(identity), - properties, OpenIddictValidationDefaults.AuthenticationScheme); - }); - - format.Setup(mock => mock.Unprotect(It.Is(token => token == "valid-token-with-multiple-audiences"))) - .Returns(delegate - { - var identity = new ClaimsIdentity(OpenIddictValidationDefaults.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); - - var properties = new AuthenticationProperties(new Dictionary - { - [OAuthValidationConstants.Properties.Audiences] = @"[""http://www.contoso.com/"",""http://www.fabrikam.com/""]" - }); - - return new AuthenticationTicket(new ClaimsPrincipal(identity), - properties, OpenIddictValidationDefaults.AuthenticationScheme); - }); - - format.Setup(mock => mock.Unprotect(It.Is(token => token == "expired-token"))) - .Returns(delegate - { - var identity = new ClaimsIdentity(OpenIddictValidationDefaults.AuthenticationScheme); - identity.AddClaim(new Claim(OAuthValidationConstants.Claims.Subject, "Fabrikam")); - - var properties = new AuthenticationProperties(); - properties.ExpiresUtc = DateTimeOffset.UtcNow - TimeSpan.FromDays(1); - - return new AuthenticationTicket(new ClaimsPrincipal(identity), - properties, OpenIddictValidationDefaults.AuthenticationScheme); - }); - - var builder = new WebHostBuilder(); - builder.UseEnvironment("Testing"); - - builder.ConfigureLogging(options => options.AddDebug()); - - builder.ConfigureServices(services => - { - services.AddOpenIddict() - .AddCore(options => - { - options.SetDefaultApplicationEntity() - .SetDefaultAuthorizationEntity() - .SetDefaultScopeEntity() - .SetDefaultTokenEntity(); - - // Replace the default OpenIddict managers. - options.Services.AddSingleton(CreateApplicationManager()); - options.Services.AddSingleton(CreateAuthorizationManager()); - options.Services.AddSingleton(CreateScopeManager()); - options.Services.AddSingleton(CreateTokenManager()); - }) - - .AddValidation(options => - { - options.Configure(settings => settings.AccessTokenFormat = format.Object); - - // Note: overriding the default data protection provider is not necessary for the tests to pass, - // but is useful to ensure unnecessary keys are not persisted in testing environments, which also - // helps make the unit tests run faster, as no registry or disk access is required in this case. - options.UseDataProtectionProvider(new EphemeralDataProtectionProvider()); - - // Run the configuration delegate - // registered by the unit tests. - configuration?.Invoke(options); - }); - }); - - builder.Configure(app => - { - app.UseOpenIddictValidation(); - - app.Map("/ticket", map => map.Run(async context => - { - var ticket = new AuthenticateContext(OpenIddictValidationDefaults.AuthenticationScheme); - await context.Authentication.AuthenticateAsync(ticket); - - if (!ticket.Accepted || ticket.Principal == null || ticket.Properties == null) - { - await context.Authentication.ChallengeAsync(); - - return; - } - - context.Response.ContentType = "application/json"; - - // Return the authentication ticket as a JSON object. - await context.Response.WriteAsync(JsonConvert.SerializeObject(new - { - Claims = from claim in ticket.Principal.Claims - select new { claim.Type, claim.Value }, - - Properties = from property in ticket.Properties - select new { Name = property.Key, property.Value } - })); - })); - - app.Map("/challenge", map => map.Run(context => - { - var properties = new AuthenticationProperties(new Dictionary - { - [OAuthValidationConstants.Properties.Error] = "custom_error", - [OAuthValidationConstants.Properties.ErrorDescription] = "custom_error_description", - [OAuthValidationConstants.Properties.ErrorUri] = "custom_error_uri", - [OAuthValidationConstants.Properties.Realm] = "custom_realm", - [OAuthValidationConstants.Properties.Scope] = "custom_scope", - }); - - return context.Authentication.ChallengeAsync(OpenIddictValidationDefaults.AuthenticationScheme, properties); - })); - - app.Run(context => - { - if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) - { - return context.Authentication.ChallengeAsync(); - } - - var identifier = context.User.FindFirst(OAuthValidationConstants.Claims.Subject).Value; - return context.Response.WriteAsync(identifier); - }); - }); - - return new TestServer(builder); - - } - - private static OpenIddictApplicationManager CreateApplicationManager( - Action>> configuration = null) - { - var manager = new Mock>( - Mock.Of(), - Mock.Of>>(), - Mock.Of>()); - - configuration?.Invoke(manager); - - return manager.Object; - } - - private static OpenIddictAuthorizationManager CreateAuthorizationManager( - Action>> configuration = null) - { - var manager = new Mock>( - Mock.Of(), - Mock.Of>>(), - Mock.Of>()); - - configuration?.Invoke(manager); - - return manager.Object; - } - - private static OpenIddictScopeManager CreateScopeManager( - Action>> configuration = null) - { - var manager = new Mock>( - Mock.Of(), - Mock.Of>>(), - Mock.Of>()); - - configuration?.Invoke(manager); - - return manager.Object; - } - - private static OpenIddictTokenManager CreateTokenManager( - Action>> configuration = null) - { - var manager = new Mock>( - Mock.Of(), - Mock.Of>>(), - Mock.Of>()); - - configuration?.Invoke(manager); - - return manager.Object; - } - - public class OpenIddictApplication { } - public class OpenIddictAuthorization { } - public class OpenIddictScope { } - public class OpenIddictToken { } - } -}