Use automatic properties, replace scope by a list and replace the validators list by a single validator

This commit is contained in:
Kévin Chalet 2015-05-24 19:25:57 +02:00
parent 56315c441c
commit fa39144937
10 changed files with 61 additions and 206 deletions

View File

@ -63,6 +63,11 @@ namespace Microsoft.AspNet.Authentication.OAuth
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.TokenEndpoint))); throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.TokenEndpoint)));
} }
if (Options.Notifications == null)
{
Options.Notifications = new OAuthAuthenticationNotifications();
}
if (Options.StateDataFormat == null) if (Options.StateDataFormat == null)
{ {
var dataProtector = dataProtectionProvider.CreateProtector( var dataProtector = dataProtectionProvider.CreateProtector(

View File

@ -7,7 +7,6 @@ using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication.OAuth namespace Microsoft.AspNet.Authentication.OAuth
{ {
@ -83,7 +82,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <summary> /// <summary>
/// Gets or sets the <see cref="IOAuthAuthenticationNotifications"/> used to handle authentication events. /// Gets or sets the <see cref="IOAuthAuthenticationNotifications"/> used to handle authentication events.
/// </summary> /// </summary>
public IOAuthAuthenticationNotifications Notifications { get; [param: NotNull] set; } = new OAuthAuthenticationNotifications(); public IOAuthAuthenticationNotifications Notifications { get; set; } = new OAuthAuthenticationNotifications();
/// <summary> /// <summary>
/// A list of permissions to request. /// A list of permissions to request.

View File

@ -2,12 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http; using System.Net.Http;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.Framework.Internal; using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
@ -43,11 +39,6 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
Options.Notifications = new OAuthBearerAuthenticationNotifications(); Options.Notifications = new OAuthBearerAuthenticationNotifications();
} }
if (Options.SecurityTokenValidators == null)
{
Options.SecurityTokenValidators = new List<ISecurityTokenValidator> { new JwtSecurityTokenHandler() };
}
if (string.IsNullOrEmpty(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(Options.Audience)) if (string.IsNullOrEmpty(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(Options.Audience))
{ {
Options.TokenValidationParameters.ValidAudience = Options.Audience; Options.TokenValidationParameters.ValidAudience = Options.Audience;

View File

@ -4,8 +4,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IdentityModel.Tokens; using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http; using System.Net.Http;
using Microsoft.Framework.Internal;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
@ -16,21 +16,12 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
/// </summary> /// </summary>
public class OAuthBearerAuthenticationOptions : AuthenticationOptions public class OAuthBearerAuthenticationOptions : AuthenticationOptions
{ {
private ICollection<ISecurityTokenValidator> _securityTokenValidators;
private TokenValidationParameters _tokenValidationParameters;
/// <summary> /// <summary>
/// Creates an instance of bearer authentication options with default values. /// Creates an instance of bearer authentication options with default values.
/// </summary> /// </summary>
public OAuthBearerAuthenticationOptions() : base() public OAuthBearerAuthenticationOptions() : base()
{ {
AuthenticationScheme = OAuthBearerAuthenticationDefaults.AuthenticationScheme; AuthenticationScheme = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
BackchannelTimeout = TimeSpan.FromMinutes(1);
Challenge = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
Notifications = new OAuthBearerAuthenticationNotifications();
RefreshOnIssuerKeyNotFound = true;
SystemClock = new SystemClock();
TokenValidationParameters = new TokenValidationParameters();
} }
/// <summary> /// <summary>
@ -54,15 +45,14 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
/// <summary> /// <summary>
/// Gets or sets the challenge to put in the "WWW-Authenticate" header. /// Gets or sets the challenge to put in the "WWW-Authenticate" header.
/// </summary> /// </summary>
/// TODO - brentschmaltz, should not be null. public string Challenge { get; set; } = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
public string Challenge { get; set; }
/// <summary> /// <summary>
/// The object provided by the application to process events raised by the bearer authentication middleware. /// The object provided by the application to process events raised by the bearer authentication middleware.
/// The application may implement the interface fully, or it may create an instance of OAuthBearerAuthenticationProvider /// The application may implement the interface fully, or it may create an instance of OAuthBearerAuthenticationProvider
/// and assign delegates only to the events it wants to process. /// and assign delegates only to the events it wants to process.
/// </summary> /// </summary>
public OAuthBearerAuthenticationNotifications Notifications { get; set; } public OAuthBearerAuthenticationNotifications Notifications { get; set; } = new OAuthBearerAuthenticationNotifications();
/// <summary> /// <summary>
/// The HttpMessageHandler used to retrieve metadata. /// The HttpMessageHandler used to retrieve metadata.
@ -74,7 +64,7 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
/// <summary> /// <summary>
/// Gets or sets the timeout when using the backchannel to make an http call. /// Gets or sets the timeout when using the backchannel to make an http call.
/// </summary> /// </summary>
public TimeSpan BackchannelTimeout { get; set; } public TimeSpan BackchannelTimeout { get; set; } = TimeSpan.FromMinutes(1);
#if DNX451 #if DNX451
/// <summary> /// <summary>
@ -104,48 +94,24 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
/// Gets or sets if a metadata refresh should be attempted after a SecurityTokenSignatureKeyNotFoundException. This allows for automatic /// Gets or sets if a metadata refresh should be attempted after a SecurityTokenSignatureKeyNotFoundException. This allows for automatic
/// recovery in the event of a signature key rollover. This is enabled by default. /// recovery in the event of a signature key rollover. This is enabled by default.
/// </summary> /// </summary>
public bool RefreshOnIssuerKeyNotFound { get; set; } public bool RefreshOnIssuerKeyNotFound { get; set; } = true;
/// <summary> /// <summary>
/// Used to know what the current clock time is when calculating or validating token expiration. When not assigned default is based on /// Used to know what the current clock time is when calculating or validating token expiration. When not assigned default is based on
/// DateTimeOffset.UtcNow. This is typically needed only for unit testing. /// DateTimeOffset.UtcNow. This is typically needed only for unit testing.
/// </summary> /// </summary>
public ISystemClock SystemClock { get; set; } public ISystemClock SystemClock { get; set; } = new SystemClock();
/// <summary> /// <summary>
/// Gets or sets the <see cref="SecurityTokenValidators"/> for validating tokens. /// Gets the ordered list of <see cref="ISecurityTokenValidator"/> used to validate access tokens.
/// </summary> /// </summary>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception> public IList<ISecurityTokenValidator> SecurityTokenValidators { get; } = new List<ISecurityTokenValidator> { new JwtSecurityTokenHandler() };
public ICollection<ISecurityTokenValidator> SecurityTokenValidators
{
get
{
return _securityTokenValidators;
}
[param: NotNull]
set
{
_securityTokenValidators = value;
}
}
/// <summary> /// <summary>
/// Gets or sets the TokenValidationParameters /// Gets or sets the parameters used to validate identity tokens.
/// </summary> /// </summary>
/// <remarks>Contains the types and definitions required for validating a token.</remarks> /// <remarks>Contains the types and definitions required for validating a token.</remarks>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception> /// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public TokenValidationParameters TokenValidationParameters public TokenValidationParameters TokenValidationParameters { get; set; } = new TokenValidationParameters();
{
get
{
return _tokenValidationParameters;
}
[param: NotNull]
set
{
_tokenValidationParameters = value;
}
}
} }
} }

View File

@ -141,7 +141,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
RequestType = OpenIdConnectRequestType.AuthenticationRequest, RequestType = OpenIdConnectRequestType.AuthenticationRequest,
Resource = Options.Resource, Resource = Options.Resource,
ResponseType = Options.ResponseType, ResponseType = Options.ResponseType,
Scope = Options.Scope Scope = string.Join(" ", Options.Scope)
}; };
// Omitting the response_mode parameter when it already corresponds to the default // Omitting the response_mode parameter when it already corresponds to the default
@ -827,17 +827,14 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
SecurityToken validatedToken = null; SecurityToken validatedToken = null;
ClaimsPrincipal principal = null; ClaimsPrincipal principal = null;
foreach (var validator in Options.SecurityTokenValidators) if (Options.SecurityTokenValidator.CanReadToken(idToken))
{ {
if (validator.CanReadToken(idToken)) principal = Options.SecurityTokenValidator.ValidateToken(idToken, validationParameters, out validatedToken);
jwt = validatedToken as JwtSecurityToken;
if (jwt == null)
{ {
principal = validator.ValidateToken(idToken, validationParameters, out validatedToken); Logger.LogError(Resources.OIDCH_0010_ValidatedSecurityTokenNotJwt, validatedToken?.GetType());
jwt = validatedToken as JwtSecurityToken; throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, Resources.OIDCH_0010_ValidatedSecurityTokenNotJwt, validatedToken?.GetType()));
if (jwt == null)
{
Logger.LogError(Resources.OIDCH_0010_ValidatedSecurityTokenNotJwt, validatedToken?.GetType());
throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, Resources.OIDCH_0010_ValidatedSecurityTokenNotJwt, validatedToken?.GetType()));
}
} }
} }

View File

@ -2,10 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
@ -60,10 +57,10 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
if (Options.StateDataFormat == null) if (Options.StateDataFormat == null)
{ {
var dataProtector = dataProtectionProvider.CreateProtector( var dataProtector = dataProtectionProvider.CreateProtector(
typeof(OpenIdConnectAuthenticationMiddleware).FullName, typeof(OpenIdConnectAuthenticationMiddleware).FullName,
typeof(string).FullName, typeof(string).FullName,
Options.AuthenticationScheme, Options.AuthenticationScheme,
"v1"); "v1");
Options.StateDataFormat = new PropertiesDataFormat(dataProtector); Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
} }
@ -78,11 +75,6 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
Options.StringDataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector, TextEncodings.Base64Url); Options.StringDataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector, TextEncodings.Base64Url);
} }
if (Options.SecurityTokenValidators == null)
{
Options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { new JwtSecurityTokenHandler() };
}
// if the user has not set the AuthorizeCallback, set it from the redirect_uri // if the user has not set the AuthorizeCallback, set it from the redirect_uri
if (!Options.CallbackPath.HasValue) if (!Options.CallbackPath.HasValue)

View File

@ -5,11 +5,12 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens; using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Framework.Caching.Distributed; using Microsoft.Framework.Caching.Distributed;
using Microsoft.Framework.Internal;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
@ -20,13 +21,6 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// </summary> /// </summary>
public class OpenIdConnectAuthenticationOptions : AuthenticationOptions public class OpenIdConnectAuthenticationOptions : AuthenticationOptions
{ {
private TimeSpan _backchannelTimeout;
private OpenIdConnectProtocolValidator _protocolValidator;
private ICollection<ISecurityTokenValidator> _securityTokenValidators;
private ISecureDataFormat<AuthenticationProperties> _stateDataFormat;
private ISecureDataFormat<string> _stringDataFormat;
private TokenValidationParameters _tokenValidationParameters;
/// <summary> /// <summary>
/// Initializes a new <see cref="OpenIdConnectAuthenticationOptions"/> /// Initializes a new <see cref="OpenIdConnectAuthenticationOptions"/>
/// </summary> /// </summary>
@ -55,16 +49,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
public OpenIdConnectAuthenticationOptions(string authenticationScheme) public OpenIdConnectAuthenticationOptions(string authenticationScheme)
{ {
AuthenticationScheme = authenticationScheme; AuthenticationScheme = authenticationScheme;
BackchannelTimeout = TimeSpan.FromMinutes(1);
Caption = OpenIdConnectAuthenticationDefaults.Caption; Caption = OpenIdConnectAuthenticationDefaults.Caption;
GetClaimsFromUserInfoEndpoint = false;
ProtocolValidator = new OpenIdConnectProtocolValidator() { RequireState = false };
RefreshOnIssuerKeyNotFound = true;
ResponseMode = OpenIdConnectResponseModes.FormPost;
ResponseType = OpenIdConnectResponseTypes.CodeIdToken;
Scope = OpenIdConnectScopes.OpenIdProfile;
TokenValidationParameters = new TokenValidationParameters();
UseTokenLifetime = true;
} }
/// <summary> /// <summary>
@ -103,23 +88,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// Gets or sets the timeout when using the backchannel to make an http call. /// Gets or sets the timeout when using the backchannel to make an http call.
/// </summary> /// </summary>
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "By design we use the property name in the exception")] [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "By design we use the property name in the exception")]
public TimeSpan BackchannelTimeout public TimeSpan BackchannelTimeout { get; set; } = TimeSpan.FromSeconds(60);
{
get
{
return _backchannelTimeout;
}
set
{
if (value <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(BackchannelTimeout), value, Resources.OIDCH_0101_BackChallnelLessThanZero);
}
_backchannelTimeout = value;
}
}
/// <summary> /// <summary>
/// Get or sets the text that the user can display on a sign in user interface. /// Get or sets the text that the user can display on a sign in user interface.
@ -192,25 +161,14 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// <summary> /// <summary>
/// Gets or sets the <see cref="OpenIdConnectAuthenticationNotifications"/> to notify when processing OpenIdConnect messages. /// Gets or sets the <see cref="OpenIdConnectAuthenticationNotifications"/> to notify when processing OpenIdConnect messages.
/// </summary> /// </summary>
public OpenIdConnectAuthenticationNotifications Notifications { get; set; } public OpenIdConnectAuthenticationNotifications Notifications { get; set; } = new OpenIdConnectAuthenticationNotifications();
/// <summary> /// <summary>
/// Gets or sets the <see cref="OpenIdConnectProtocolValidator"/> that is used to ensure that the 'id_token' received /// Gets or sets the <see cref="OpenIdConnectProtocolValidator"/> that is used to ensure that the 'id_token' received
/// is valid per: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation /// is valid per: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
/// </summary> /// </summary>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception> /// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public OpenIdConnectProtocolValidator ProtocolValidator public OpenIdConnectProtocolValidator ProtocolValidator { get; set; } = new OpenIdConnectProtocolValidator { RequireState = false };
{
get
{
return _protocolValidator;
}
[param: NotNull]
set
{
_protocolValidator = value;
}
}
/// <summary> /// <summary>
/// Gets or sets the 'post_logout_redirect_uri' /// Gets or sets the 'post_logout_redirect_uri'
@ -230,7 +188,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// Gets or sets if a metadata refresh should be attempted after a SecurityTokenSignatureKeyNotFoundException. This allows for automatic /// Gets or sets if a metadata refresh should be attempted after a SecurityTokenSignatureKeyNotFoundException. This allows for automatic
/// recovery in the event of a signature key rollover. This is enabled by default. /// recovery in the event of a signature key rollover. This is enabled by default.
/// </summary> /// </summary>
public bool RefreshOnIssuerKeyNotFound { get; set; } public bool RefreshOnIssuerKeyNotFound { get; set; } = true;
/// <summary> /// <summary>
/// Gets or sets the 'resource'. /// Gets or sets the 'resource'.
@ -240,103 +198,49 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// <summary> /// <summary>
/// Gets or sets the 'response_mode'. /// Gets or sets the 'response_mode'.
/// </summary> /// </summary>
public string ResponseMode { get; set; } public string ResponseMode { get; set; } = OpenIdConnectResponseModes.FormPost;
/// <summary> /// <summary>
/// Gets or sets the 'response_type'. /// Gets or sets the 'response_type'.
/// </summary> /// </summary>
public string ResponseType { get; set; } public string ResponseType { get; set; } = OpenIdConnectResponseTypes.CodeIdToken;
/// <summary> /// <summary>
/// Gets or sets the 'scope'. /// Gets the list of permissions to request.
/// </summary> /// </summary>
public string Scope { get; set; } public IList<string> Scope { get; } = new List<string> { "openid", "profile" };
/// <summary> /// <summary>
/// Gets or sets the SignInScheme which will be used to set the <see cref="System.Security.Claims.ClaimsIdentity.AuthenticationType"/>. /// Gets or sets the SignInScheme which will be used to set the <see cref="ClaimsIdentity.AuthenticationType"/>.
/// </summary> /// </summary>
public string SignInScheme { get; set; } public string SignInScheme { get; set; }
/// <summary> /// <summary>
/// Gets or sets the type used to secure data handled by the middleware. /// Gets or sets the type used to secure data handled by the middleware.
/// </summary> /// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
{
get
{
return _stateDataFormat;
}
[param: NotNull]
set
{
_stateDataFormat = value;
}
}
/// <summary> /// <summary>
/// Gets or sets the type used to secure strings used by the middleware. /// Gets or sets the type used to secure strings used by the middleware.
/// </summary> /// </summary>
public ISecureDataFormat<string> StringDataFormat public ISecureDataFormat<string> StringDataFormat { get; set; }
{
get
{
return _stringDataFormat;
}
[param: NotNull]
set
{
_stringDataFormat = value;
}
}
/// <summary> /// <summary>
/// Gets or sets the <see cref="SecurityTokenValidators"/> for validating tokens. /// Gets or sets the <see cref="ISecurityTokenValidator"/> used to validate identity tokens.
/// </summary> /// </summary>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception> public ISecurityTokenValidator SecurityTokenValidator { get; set; } = new JwtSecurityTokenHandler();
public ICollection<ISecurityTokenValidator> SecurityTokenValidators
{
get
{
return _securityTokenValidators;
}
set
{
if (value == null)
{
throw new ArgumentNullException("SecurityTokenValidators");
}
_securityTokenValidators = value;
}
}
/// <summary> /// <summary>
/// Gets or sets the TokenValidationParameters /// Gets or sets the parameters used to validate identity tokens.
/// </summary> /// </summary>
/// <remarks>Contains the types and definitions required for validating a token.</remarks> /// <remarks>Contains the types and definitions required for validating a token.</remarks>
public TokenValidationParameters TokenValidationParameters public TokenValidationParameters TokenValidationParameters { get; set; } = new TokenValidationParameters();
{
get
{
return _tokenValidationParameters;
}
[param: NotNull]
set
{
_tokenValidationParameters = value;
}
}
/// <summary> /// <summary>
/// Indicates that the authentication session lifetime (e.g. cookies) should match that of the authentication token. /// Indicates that the authentication session lifetime (e.g. cookies) should match that of the authentication token.
/// If the token does not provide lifetime information then normal session lifetimes will be used. /// If the token does not provide lifetime information then normal session lifetimes will be used.
/// This is enabled by default. /// This is enabled by default.
/// </summary> /// </summary>
public bool UseTokenLifetime public bool UseTokenLifetime { get; set; } = true;
{
get;
set;
}
} }
} }

View File

@ -29,10 +29,7 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
options.Authority = "https://login.windows.net/tushartest.onmicrosoft.com"; options.Authority = "https://login.windows.net/tushartest.onmicrosoft.com";
options.Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"; options.Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt";
options.TokenValidationParameters = new TokenValidationParameters options.TokenValidationParameters.ValidateLifetime = false;
{
Validate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l9pbXBlcnNvbmF0aW9uIiwiYWNyIjoiMSJ9.N_Kw1EhoVGrHbE6hOcm7ERdZ7paBQiNdObvp2c6T6n5CE8p0fZqmUd-ya_EqwElcD6SiKSiP7gj0gpNUnOJcBl_H2X8GseaeeMxBrZdsnDL8qecc6_ygHruwlPltnLTdka67s1Ow4fDSHaqhVTEk6lzGmNEcbNAyb0CxQxU6o7Fh0yHRiWoLsT8yqYk8nKzsHXfZBNby4aRo3_hXaa4i0SZLYfDGGYPdttG4vT_u54QGGd4Wzbonv2gjDlllOVGOwoJS6kfl1h8mk0qxdiIaT_ChbDWgkWvTB7bTvBE-EgHgV0XmAo0WtJeSxgjsG3KhhEPsONmqrSjhIUV4IVnF2w";
@ -167,7 +164,7 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
}; };
options.SecurityTokenValidators = new[] { new BlobTokenValidator(options.AuthenticationScheme) }; options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme));
}); });
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");

View File

@ -3,7 +3,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics; using System.Diagnostics;
using System.IdentityModel.Tokens; using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
@ -273,7 +272,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private static void AuthorizationCodeReceivedHandledOptions(OpenIdConnectAuthenticationOptions options) private static void AuthorizationCodeReceivedHandledOptions(OpenIdConnectAuthenticationOptions options)
{ {
DefaultOptions(options); DefaultOptions(options);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { MockSecurityTokenValidator() }; options.SecurityTokenValidator = MockSecurityTokenValidator();
options.ProtocolValidator = MockProtocolValidator(); options.ProtocolValidator = MockProtocolValidator();
options.Notifications = options.Notifications =
new OpenIdConnectAuthenticationNotifications new OpenIdConnectAuthenticationNotifications
@ -289,7 +288,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private static void AuthorizationCodeReceivedSkippedOptions(OpenIdConnectAuthenticationOptions options) private static void AuthorizationCodeReceivedSkippedOptions(OpenIdConnectAuthenticationOptions options)
{ {
DefaultOptions(options); DefaultOptions(options);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { MockSecurityTokenValidator() }; options.SecurityTokenValidator = MockSecurityTokenValidator();
options.ProtocolValidator = MockProtocolValidator(); options.ProtocolValidator = MockProtocolValidator();
options.Notifications = options.Notifications =
new OpenIdConnectAuthenticationNotifications new OpenIdConnectAuthenticationNotifications
@ -305,7 +304,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private static void AuthenticationErrorHandledOptions(OpenIdConnectAuthenticationOptions options) private static void AuthenticationErrorHandledOptions(OpenIdConnectAuthenticationOptions options)
{ {
DefaultOptions(options); DefaultOptions(options);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { MockSecurityTokenValidator() }; options.SecurityTokenValidator = MockSecurityTokenValidator();
options.ProtocolValidator = MockProtocolValidator(); options.ProtocolValidator = MockProtocolValidator();
options.Notifications = options.Notifications =
new OpenIdConnectAuthenticationNotifications new OpenIdConnectAuthenticationNotifications
@ -321,7 +320,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private static void AuthenticationErrorSkippedOptions(OpenIdConnectAuthenticationOptions options) private static void AuthenticationErrorSkippedOptions(OpenIdConnectAuthenticationOptions options)
{ {
DefaultOptions(options); DefaultOptions(options);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { MockSecurityTokenValidator() }; options.SecurityTokenValidator = MockSecurityTokenValidator();
options.ProtocolValidator = MockProtocolValidator(); options.ProtocolValidator = MockProtocolValidator();
options.Notifications = options.Notifications =
new OpenIdConnectAuthenticationNotifications new OpenIdConnectAuthenticationNotifications
@ -387,7 +386,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
options.ProtocolValidator.RequireNonce = false; options.ProtocolValidator.RequireNonce = false;
options.StateDataFormat = new AuthenticationPropertiesFormaterKeyValue(); options.StateDataFormat = new AuthenticationPropertiesFormaterKeyValue();
options.GetClaimsFromUserInfoEndpoint = true; options.GetClaimsFromUserInfoEndpoint = true;
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { MockSecurityTokenValidator() }; options.SecurityTokenValidator = MockSecurityTokenValidator();
options.Notifications = options.Notifications =
new OpenIdConnectAuthenticationNotifications new OpenIdConnectAuthenticationNotifications
{ {
@ -469,7 +468,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
SecurityToken jwt = null; SecurityToken jwt = null;
mockValidator.Setup(v => v.ValidateToken(It.IsAny<string>(), It.IsAny<TokenValidationParameters>(), out jwt)).Returns(new ClaimsPrincipal()); mockValidator.Setup(v => v.ValidateToken(It.IsAny<string>(), It.IsAny<TokenValidationParameters>(), out jwt)).Returns(new ClaimsPrincipal());
mockValidator.Setup(v => v.CanReadToken(It.IsAny<string>())).Returns(false); mockValidator.Setup(v => v.CanReadToken(It.IsAny<string>())).Returns(false);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { mockValidator.Object }; options.SecurityTokenValidator = mockValidator.Object;
} }
private static void SecurityTokenValidatorThrows(OpenIdConnectAuthenticationOptions options) private static void SecurityTokenValidatorThrows(OpenIdConnectAuthenticationOptions options)
@ -479,13 +478,13 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
SecurityToken jwt = null; SecurityToken jwt = null;
mockValidator.Setup(v => v.ValidateToken(It.IsAny<string>(), It.IsAny<TokenValidationParameters>(), out jwt)).Throws<SecurityTokenSignatureKeyNotFoundException>(); mockValidator.Setup(v => v.ValidateToken(It.IsAny<string>(), It.IsAny<TokenValidationParameters>(), out jwt)).Throws<SecurityTokenSignatureKeyNotFoundException>();
mockValidator.Setup(v => v.CanReadToken(It.IsAny<string>())).Returns(true); mockValidator.Setup(v => v.CanReadToken(It.IsAny<string>())).Returns(true);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { mockValidator.Object }; options.SecurityTokenValidator = mockValidator.Object;
} }
private static void SecurityTokenValidatorValidatesAllTokens(OpenIdConnectAuthenticationOptions options) private static void SecurityTokenValidatorValidatesAllTokens(OpenIdConnectAuthenticationOptions options)
{ {
DefaultOptions(options); DefaultOptions(options);
options.SecurityTokenValidators = new Collection<ISecurityTokenValidator> { MockSecurityTokenValidator() }; options.SecurityTokenValidator = MockSecurityTokenValidator();
options.ProtocolValidator.RequireTimeStampInNonce = false; options.ProtocolValidator.RequireTimeStampInNonce = false;
options.ProtocolValidator.RequireNonce = false; options.ProtocolValidator.RequireNonce = false;
} }

View File

@ -226,8 +226,13 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
options.RedirectUri = queryValues.RedirectUri; options.RedirectUri = queryValues.RedirectUri;
else if (param.Equals(OpenIdConnectParameterNames.Resource)) else if (param.Equals(OpenIdConnectParameterNames.Resource))
options.Resource = queryValues.Resource; options.Resource = queryValues.Resource;
else if (param.Equals(OpenIdConnectParameterNames.Scope)) else if (param.Equals(OpenIdConnectParameterNames.Scope)) {
options.Scope = queryValues.Scope; options.Scope.Clear();
foreach (var scope in queryValues.Scope.Split(' ')) {
options.Scope.Add(scope);
}
}
} }
options.Authority = queryValues.Authority; options.Authority = queryValues.Authority;