Move generics off of Validator/TokenProvider interfaces

This commit is contained in:
Hao Kung 2015-08-13 18:49:04 -07:00
parent f26b20b7ee
commit 62a1d49710
25 changed files with 164 additions and 175 deletions

View File

@ -15,7 +15,7 @@ namespace Microsoft.AspNet.Identity
/// Provides protection and validation of identity tokens. /// Provides protection and validation of identity tokens.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type used to represent a user.</typeparam> /// <typeparam name="TUser">The type used to represent a user.</typeparam>
public class DataProtectorTokenProvider<TUser> : IUserTokenProvider<TUser> where TUser : class public class DataProtectorTokenProvider : IUserTokenProvider
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="DataProtectorTokenProvider{TUser}"/> class. /// Initializes a new instance of the <see cref="DataProtectorTokenProvider{TUser}"/> class.
@ -64,7 +64,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve user properties from.</param> /// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve user properties from.</param>
/// <param name="user">The <see cref="TUser"/> the token will be generated from.</param> /// <param name="user">The <see cref="TUser"/> the token will be generated from.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the generated token.</returns> /// <returns>A <see cref="Task{TResult}"/> representing the generated token.</returns>
public virtual async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user) public virtual async Task<string> GenerateAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class
{ {
if (user == null) if (user == null)
{ {
@ -99,7 +99,7 @@ namespace Microsoft.AspNet.Identity
/// A <see cref="Task{TResult}"/> that represents the result of the asynchronous validation, /// A <see cref="Task{TResult}"/> that represents the result of the asynchronous validation,
/// containing true if the token is valid, otherwise false. /// containing true if the token is valid, otherwise false.
/// </returns> /// </returns>
public virtual async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user) public virtual async Task<bool> ValidateAsync<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class
{ {
try try
{ {
@ -157,7 +157,7 @@ namespace Microsoft.AspNet.Identity
/// containing true if a token generated by this instance can be used as a Two Factor Authentication token, otherwise false. /// containing true if a token generated by this instance can be used as a Two Factor Authentication token, otherwise false.
/// </returns> /// </returns>
/// <remarks>This method will always return false for instances of <see cref="DataProtectorTokenProvider{TUser}"/>.</remarks> /// <remarks>This method will always return false for instances of <see cref="DataProtectorTokenProvider{TUser}"/>.</remarks>
public virtual Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user) public virtual Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class
{ {
return Task.FromResult(false); return Task.FromResult(false);
} }
@ -169,7 +169,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve user properties from.</param> /// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve user properties from.</param>
/// <param name="user">The <see cref="TUser"/> the token was generated for.</param> /// <param name="user">The <see cref="TUser"/> the token was generated for.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous notification.</returns> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous notification.</returns>
public virtual Task NotifyAsync(string token, UserManager<TUser> manager, TUser user) public virtual Task NotifyAsync<TUser>(string token, UserManager<TUser> manager, TUser user) where TUser : class
{ {
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -22,8 +22,7 @@ namespace Microsoft.AspNet.Identity
/// TokenProvider that generates tokens from the user's security stamp and notifies a user via email. /// TokenProvider that generates tokens from the user's security stamp and notifies a user via email.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type used to represent a user.</typeparam> /// <typeparam name="TUser">The type used to represent a user.</typeparam>
public class EmailTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser> public class EmailTokenProvider : TotpSecurityStampBasedTokenProvider
where TUser : class
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="EmailTokenProvider{TUser}"/> class. /// Initializes a new instance of the <see cref="EmailTokenProvider{TUser}"/> class.
@ -61,7 +60,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param> /// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param>
/// <param name="user">The <see cref="TUser"/> to check for the possibility of generating a two factor authentication token.</param> /// <param name="user">The <see cref="TUser"/> to check for the possibility of generating a two factor authentication token.</param>
/// <returns>True if the user has an email address set, otherwise false.</returns> /// <returns>True if the user has an email address set, otherwise false.</returns>
public override async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user) public override async Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user)
{ {
var email = await manager.GetEmailAsync(user); var email = await manager.GetEmailAsync(user);
return !string.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user); return !string.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user);
@ -74,8 +73,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param> /// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param>
/// <param name="user">The <see cref="TUser"/> to check for the possibility of generating a two factor authentication token.</param> /// <param name="user">The <see cref="TUser"/> to check for the possibility of generating a two factor authentication token.</param>
/// <returns>A string suitable for use as entropy in token generation.</returns> /// <returns>A string suitable for use as entropy in token generation.</returns>
public override async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager, public override async Task<string> GetUserModifierAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user)
TUser user)
{ {
var email = await manager.GetEmailAsync(user); var email = await manager.GetEmailAsync(user);
return "Email:" + purpose + ":" + email; return "Email:" + purpose + ":" + email;

View File

@ -7,7 +7,7 @@ namespace Microsoft.AspNet.Identity
/// Provides an abstraction for hashing passwords. /// Provides an abstraction for hashing passwords.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type used to represent a user.</typeparam> /// <typeparam name="TUser">The type used to represent a user.</typeparam>
public interface IPasswordHasher<TUser> where TUser : class public interface IPasswordHasher
{ {
/// <summary> /// <summary>
/// Returns a hashed representation of the supplied <paramref name="password"/> for the specified <paramref name="user"/>. /// Returns a hashed representation of the supplied <paramref name="password"/> for the specified <paramref name="user"/>.
@ -15,7 +15,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user">The user whose password is to be hashed.</param> /// <param name="user">The user whose password is to be hashed.</param>
/// <param name="password">The password to hash.</param> /// <param name="password">The password to hash.</param>
/// <returns>A hashed representation of the supplied <paramref name="password"/> for the specified <paramref name="user"/>.</returns> /// <returns>A hashed representation of the supplied <paramref name="password"/> for the specified <paramref name="user"/>.</returns>
string HashPassword(TUser user, string password); string HashPassword<TUser>(TUser user, string password) where TUser : class;
/// <summary> /// <summary>
/// Returns a <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison. /// Returns a <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison.
@ -25,6 +25,6 @@ namespace Microsoft.AspNet.Identity
/// <param name="providedPassword">The password supplied for comparison.</param> /// <param name="providedPassword">The password supplied for comparison.</param>
/// <returns>A <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison.</returns> /// <returns>A <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison.</returns>
/// <remarks>Implementations of this method should be time consistent.</remarks> /// <remarks>Implementations of this method should be time consistent.</remarks>
PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword); PasswordVerificationResult VerifyHashedPassword<TUser>(TUser user, string hashedPassword, string providedPassword) where TUser : class;
} }
} }

View File

@ -1,7 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity
@ -10,7 +9,7 @@ namespace Microsoft.AspNet.Identity
/// Provides an abstraction for validating passwords. /// Provides an abstraction for validating passwords.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type that represents a user.</typeparam> /// <typeparam name="TUser">The type that represents a user.</typeparam>
public interface IPasswordValidator<TUser> where TUser : class public interface IPasswordValidator
{ {
/// <summary> /// <summary>
/// Validates a password as an asynchronous operation. /// Validates a password as an asynchronous operation.
@ -19,6 +18,6 @@ namespace Microsoft.AspNet.Identity
/// <param name="user">The user whose password should be validated.</param> /// <param name="user">The user whose password should be validated.</param>
/// <param name="password">The password supplied for validation</param> /// <param name="password">The password supplied for validation</param>
/// <returns>The task object representing the asynchronous operation.</returns> /// <returns>The task object representing the asynchronous operation.</returns>
Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password); Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user, string password) where TUser : class;
} }
} }

View File

@ -9,7 +9,7 @@ namespace Microsoft.AspNet.Identity
/// Provides an abstraction for a validating a role. /// Provides an abstraction for a validating a role.
/// </summary> /// </summary>
/// <typeparam name="TRole">The type encapsulating a role.</typeparam> /// <typeparam name="TRole">The type encapsulating a role.</typeparam>
public interface IRoleValidator<TRole> where TRole : class public interface IRoleValidator
{ {
/// <summary> /// <summary>
/// Validates a role as an asynchronous operation. /// Validates a role as an asynchronous operation.
@ -17,6 +17,6 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="RoleManager{TRole}"/> managing the role store.</param> /// <param name="manager">The <see cref="RoleManager{TRole}"/> managing the role store.</param>
/// <param name="role">The role to validate.</param> /// <param name="role">The role to validate.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous validation.</returns> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous validation.</returns>
Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role); Task<IdentityResult> ValidateAsync<TRole>(RoleManager<TRole> manager, TRole role) where TRole : class;
} }
} }

View File

@ -9,7 +9,7 @@ namespace Microsoft.AspNet.Identity
/// Provides an abstraction for token generators. /// Provides an abstraction for token generators.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type encapsulating a user.</typeparam> /// <typeparam name="TUser">The type encapsulating a user.</typeparam>
public interface IUserTokenProvider<TUser> where TUser : class public interface IUserTokenProvider
{ {
/// <summary> /// <summary>
/// Gets the name of the token provider. /// Gets the name of the token provider.
@ -36,7 +36,7 @@ namespace Microsoft.AspNet.Identity
/// Implementations of <see cref="IUserTokenProvider{TUser}"/> should validate that purpose is not null or empty to /// Implementations of <see cref="IUserTokenProvider{TUser}"/> should validate that purpose is not null or empty to
/// help with token separation. /// help with token separation.
/// </remarks> /// </remarks>
Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user); Task<string> GenerateAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class;
/// <summary> /// <summary>
/// Returns a flag indicating whether the specified <paramref name="token"/> is valid for the given /// Returns a flag indicating whether the specified <paramref name="token"/> is valid for the given
@ -51,7 +51,7 @@ namespace Microsoft.AspNet.Identity
/// of validating the <paramref name="token"> for the specified </paramref><paramref name="user"/> and <paramref name="purpose"/>. /// of validating the <paramref name="token"> for the specified </paramref><paramref name="user"/> and <paramref name="purpose"/>.
/// The task will return true if the token is valid, otherwise false. /// The task will return true if the token is valid, otherwise false.
/// </returns> /// </returns>
Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user); Task<bool> ValidateAsync<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class;
/// <summary> /// <summary>
/// Returns a flag indicating whether the token provider can generate a token suitable for two factor authentication token for /// Returns a flag indicating whether the token provider can generate a token suitable for two factor authentication token for
@ -64,6 +64,6 @@ namespace Microsoft.AspNet.Identity
/// factor token could be generated by this provider for the specified <paramref name="user"/> and <paramref name="purpose"/>. /// factor token could be generated by this provider for the specified <paramref name="user"/> and <paramref name="purpose"/>.
/// The task will return true if a two factor authentication token could be generated, otherwise false. /// The task will return true if a two factor authentication token could be generated, otherwise false.
/// </returns> /// </returns>
Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user); Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class;
} }
} }

View File

@ -10,7 +10,7 @@ namespace Microsoft.AspNet.Identity
/// Provides an abstraction for user validation. /// Provides an abstraction for user validation.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type encapsulating a user.</typeparam> /// <typeparam name="TUser">The type encapsulating a user.</typeparam>
public interface IUserValidator<TUser> where TUser : class public interface IUserValidator
{ {
/// <summary> /// <summary>
/// Validates the specified <paramref name="user"/> as an asynchronous operation. /// Validates the specified <paramref name="user"/> as an asynchronous operation.
@ -18,6 +18,6 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="UserManager{TUser}"/> that can be used to retrieve user properties.</param> /// <param name="manager">The <see cref="UserManager{TUser}"/> that can be used to retrieve user properties.</param>
/// <param name="user">The user to validate.</param> /// <param name="user">The user to validate.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the validation operation.</returns> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the validation operation.</returns>
Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user); Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class;
} }
} }

View File

@ -60,9 +60,10 @@ namespace Microsoft.AspNet.Identity
/// </summary> /// </summary>
/// <typeparam name="T">The user type to validate.</typeparam> /// <typeparam name="T">The user type to validate.</typeparam>
/// <returns>The <see cref="IdentityBuilder"/>.</returns> /// <returns>The <see cref="IdentityBuilder"/>.</returns>
public virtual IdentityBuilder AddUserValidator<T>() where T : class public virtual IdentityBuilder AddUserValidator<TValidator>() where TValidator : class, IUserValidator
{ {
return AddScoped(typeof(IUserValidator<>).MakeGenericType(UserType), typeof(T)); Services.AddScoped<IUserValidator, TValidator>();
return this;
} }
/// <summary> /// <summary>
@ -70,9 +71,10 @@ namespace Microsoft.AspNet.Identity
/// </summary> /// </summary>
/// <typeparam name="T">The role type to validate.</typeparam> /// <typeparam name="T">The role type to validate.</typeparam>
/// <returns>The <see cref="IdentityBuilder"/>.</returns> /// <returns>The <see cref="IdentityBuilder"/>.</returns>
public virtual IdentityBuilder AddRoleValidator<T>() where T : class public virtual IdentityBuilder AddRoleValidator<TValidator>() where TValidator : class, IRoleValidator
{ {
return AddScoped(typeof(IRoleValidator<>).MakeGenericType(RoleType), typeof(T)); Services.AddScoped<IRoleValidator, TValidator>();
return this;
} }
/// <summary> /// <summary>
@ -91,9 +93,10 @@ namespace Microsoft.AspNet.Identity
/// </summary> /// </summary>
/// <typeparam name="T">The user type whose password will be validated.</typeparam> /// <typeparam name="T">The user type whose password will be validated.</typeparam>
/// <returns>The <see cref="IdentityBuilder"/>.</returns> /// <returns>The <see cref="IdentityBuilder"/>.</returns>
public virtual IdentityBuilder AddPasswordValidator<T>() where T : class public virtual IdentityBuilder AddPasswordValidator<TValidator>() where TValidator : class,IPasswordValidator
{ {
return AddScoped(typeof(IPasswordValidator<>).MakeGenericType(UserType), typeof(T)); Services.AddScoped<IPasswordValidator, TValidator>();
return this;
} }
/// <summary> /// <summary>
@ -121,19 +124,10 @@ namespace Microsoft.AspNet.Identity
/// </summary> /// </summary>
/// <typeparam name="TProvider">The type of the token provider to add.</typeparam> /// <typeparam name="TProvider">The type of the token provider to add.</typeparam>
/// <returns>The <see cref="IdentityBuilder"/>.</returns> /// <returns>The <see cref="IdentityBuilder"/>.</returns>
public virtual IdentityBuilder AddTokenProvider<TProvider>() where TProvider : class public virtual IdentityBuilder AddTokenProvider<TProvider>() where TProvider : class, IUserTokenProvider
{ {
return AddTokenProvider(typeof(TProvider)); Services.AddScoped<IUserTokenProvider, TProvider>();
} return this;
/// <summary>
/// Adds a token provider for the <seealso cref="UserType"/>.
/// </summary>
/// <param name="provider">The type of the <see cref="IUserTokenProvider{TUser}"/> to add.</param>
/// <returns>The <see cref="IdentityBuilder"/>.</returns>
public virtual IdentityBuilder AddTokenProvider(Type provider)
{
return AddScoped(typeof(IUserTokenProvider<>).MakeGenericType(UserType), provider);
} }
/// <summary> /// <summary>
@ -147,9 +141,9 @@ namespace Microsoft.AspNet.Identity
options.Name = Resources.DefaultTokenProvider; options.Name = Resources.DefaultTokenProvider;
}); });
return AddTokenProvider(typeof(DataProtectorTokenProvider<>).MakeGenericType(UserType)) return AddTokenProvider<DataProtectorTokenProvider>()
.AddTokenProvider(typeof(PhoneNumberTokenProvider<>).MakeGenericType(UserType)) .AddTokenProvider<PhoneNumberTokenProvider>()
.AddTokenProvider(typeof(EmailTokenProvider<>).MakeGenericType(UserType)); .AddTokenProvider<EmailTokenProvider>();
} }
/// <summary> /// <summary>

View File

@ -83,11 +83,11 @@ namespace Microsoft.Framework.DependencyInjection
services.AddAuthentication(); services.AddAuthentication();
// Identity services // Identity services
services.TryAdd(ServiceDescriptor.Scoped<IUserValidator<TUser>, UserValidator<TUser>>()); services.TryAdd(ServiceDescriptor.Scoped<IUserValidator, UserValidator>());
services.TryAdd(ServiceDescriptor.Scoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>()); services.TryAdd(ServiceDescriptor.Scoped<IPasswordValidator, PasswordValidator>());
services.TryAdd(ServiceDescriptor.Scoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>()); services.TryAdd(ServiceDescriptor.Scoped<IPasswordHasher, PasswordHasher>());
services.TryAdd(ServiceDescriptor.Scoped<ILookupNormalizer, UpperInvariantLookupNormalizer>()); services.TryAdd(ServiceDescriptor.Scoped<ILookupNormalizer, UpperInvariantLookupNormalizer>());
services.TryAdd(ServiceDescriptor.Scoped<IRoleValidator<TRole>, RoleValidator<TRole>>()); services.TryAdd(ServiceDescriptor.Scoped<IRoleValidator, RoleValidator>());
// No interface for the error describer so we can add errors without rev'ing the interface // No interface for the error describer so we can add errors without rev'ing the interface
services.TryAdd(ServiceDescriptor.Scoped<IdentityErrorDescriber, IdentityErrorDescriber>()); services.TryAdd(ServiceDescriptor.Scoped<IdentityErrorDescriber, IdentityErrorDescriber>());
services.TryAdd(ServiceDescriptor.Scoped<ISecurityStampValidator, SecurityStampValidator<TUser>>()); services.TryAdd(ServiceDescriptor.Scoped<ISecurityStampValidator, SecurityStampValidator<TUser>>());

View File

@ -13,7 +13,7 @@ namespace Microsoft.AspNet.Identity
/// Implements the standard Identity password hashing. /// Implements the standard Identity password hashing.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type used to represent a user.</typeparam> /// <typeparam name="TUser">The type used to represent a user.</typeparam>
public class PasswordHasher<TUser> : IPasswordHasher<TUser> where TUser : class public class PasswordHasher: IPasswordHasher
{ {
/* ======================= /* =======================
* HASHED PASSWORD FORMATS * HASHED PASSWORD FORMATS
@ -90,7 +90,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user">The user whose password is to be hashed.</param> /// <param name="user">The user whose password is to be hashed.</param>
/// <param name="password">The password to hash.</param> /// <param name="password">The password to hash.</param>
/// <returns>A hashed representation of the supplied <paramref name="password"/> for the specified <paramref name="user"/>.</returns> /// <returns>A hashed representation of the supplied <paramref name="password"/> for the specified <paramref name="user"/>.</returns>
public virtual string HashPassword(TUser user, string password) public virtual string HashPassword<TUser>(TUser user, string password) where TUser : class
{ {
if (password == null) if (password == null)
{ {
@ -168,7 +168,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="providedPassword">The password supplied for comparison.</param> /// <param name="providedPassword">The password supplied for comparison.</param>
/// <returns>A <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison.</returns> /// <returns>A <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison.</returns>
/// <remarks>Implementations of this method should be time consistent.</remarks> /// <remarks>Implementations of this method should be time consistent.</remarks>
public virtual PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword) public virtual PasswordVerificationResult VerifyHashedPassword<TUser>(TUser user, string hashedPassword, string providedPassword) where TUser : class
{ {
if (hashedPassword == null) if (hashedPassword == null)
{ {

View File

@ -12,10 +12,10 @@ namespace Microsoft.AspNet.Identity
/// Provides the default password policy for Identity. /// Provides the default password policy for Identity.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type that represents a user.</typeparam> /// <typeparam name="TUser">The type that represents a user.</typeparam>
public class PasswordValidator<TUser> : IPasswordValidator<TUser> where TUser : class public class PasswordValidator : IPasswordValidator
{ {
/// <summary> /// <summary>
/// Constructions a new instance of <see cref="PasswordValidator{TUser}"/>. /// Constructions a new instance of <see cref="PasswordValidator"/>.
/// </summary> /// </summary>
/// <param name="errors">The <see cref="IdentityErrorDescriber"/> to retrieve error text from.</param> /// <param name="errors">The <see cref="IdentityErrorDescriber"/> to retrieve error text from.</param>
public PasswordValidator(IdentityErrorDescriber errors = null) public PasswordValidator(IdentityErrorDescriber errors = null)
@ -36,7 +36,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user">The user whose password should be validated.</param> /// <param name="user">The user whose password should be validated.</param>
/// <param name="password">The password supplied for validation</param> /// <param name="password">The password supplied for validation</param>
/// <returns>The task object representing the asynchronous operation.</returns> /// <returns>The task object representing the asynchronous operation.</returns>
public virtual Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password) public virtual Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user, string password) where TUser : class
{ {
if (password == null) if (password == null)
{ {

View File

@ -23,8 +23,7 @@ namespace Microsoft.AspNet.Identity
/// sends them to the user via their phone number. /// sends them to the user via their phone number.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type encapsulating a user.</typeparam> /// <typeparam name="TUser">The type encapsulating a user.</typeparam>
public class PhoneNumberTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser> public class PhoneNumberTokenProvider : TotpSecurityStampBasedTokenProvider
where TUser : class
{ {
/// <summary> /// <summary>
/// Creates a new instance of <see cref="PhoneNumberTokenProvider{TUser}"/> with the specified <paramref name="options"/>. /// Creates a new instance of <see cref="PhoneNumberTokenProvider{TUser}"/> with the specified <paramref name="options"/>.
@ -63,7 +62,7 @@ namespace Microsoft.AspNet.Identity
/// The task will return true if a two factor authentication token could be generated as the user has /// The task will return true if a two factor authentication token could be generated as the user has
/// a telephone number, otherwise false. /// a telephone number, otherwise false.
/// </returns> /// </returns>
public override async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user) public override async Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {
@ -83,7 +82,7 @@ namespace Microsoft.AspNet.Identity
/// The <see cref="Task"/> that represents the asynchronous operation, containing a constant modifier for the specified /// The <see cref="Task"/> that represents the asynchronous operation, containing a constant modifier for the specified
/// <paramref name="user"/> and <paramref name="purpose"/>. /// <paramref name="user"/> and <paramref name="purpose"/>.
/// </returns> /// </returns>
public override async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager, TUser user) public override async Task<string> GetUserModifierAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {

View File

@ -4,11 +4,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Claims; using System.Security.Claims;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
@ -34,7 +32,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="logger">The logger used to log messages, warnings and errors.</param> /// <param name="logger">The logger used to log messages, warnings and errors.</param>
/// <param name="contextAccessor">The accessor used to access the <see cref="HttpContext"/>.</param> /// <param name="contextAccessor">The accessor used to access the <see cref="HttpContext"/>.</param>
public RoleManager(IRoleStore<TRole> store, public RoleManager(IRoleStore<TRole> store,
IEnumerable<IRoleValidator<TRole>> roleValidators, IEnumerable<IRoleValidator> roleValidators,
ILookupNormalizer keyNormalizer, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IdentityErrorDescriber errors,
ILogger<RoleManager<TRole>> logger, ILogger<RoleManager<TRole>> logger,
@ -77,7 +75,7 @@ namespace Microsoft.AspNet.Identity
/// Gets a list of validators for roles to call before persistence. /// Gets a list of validators for roles to call before persistence.
/// </summary> /// </summary>
/// <value>A list of validators for roles to call before persistence.</value> /// <value>A list of validators for roles to call before persistence.</value>
internal IList<IRoleValidator<TRole>> RoleValidators { get; } = new List<IRoleValidator<TRole>>(); internal IList<IRoleValidator> RoleValidators { get; } = new List<IRoleValidator>();
/// <summary> /// <summary>
/// Gets the <see cref="IdentityErrorDescriber"/> used to provider error messages. /// Gets the <see cref="IdentityErrorDescriber"/> used to provider error messages.

View File

@ -11,7 +11,7 @@ namespace Microsoft.AspNet.Identity
/// Provides the default validation of roles. /// Provides the default validation of roles.
/// </summary> /// </summary>
/// <typeparam name="TRole">The type encapsulating a role.</typeparam> /// <typeparam name="TRole">The type encapsulating a role.</typeparam>
public class RoleValidator<TRole> : IRoleValidator<TRole> where TRole : class public class RoleValidator : IRoleValidator
{ {
/// <summary> /// <summary>
/// Creates a new instance of <see cref="RoleValidator{TRole}"/>/ /// Creates a new instance of <see cref="RoleValidator{TRole}"/>/
@ -30,7 +30,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="RoleManager{TRole}"/> managing the role store.</param> /// <param name="manager">The <see cref="RoleManager{TRole}"/> managing the role store.</param>
/// <param name="role">The role to validate.</param> /// <param name="role">The role to validate.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous validation.</returns> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous validation.</returns>
public virtual async Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role) public virtual async Task<IdentityResult> ValidateAsync<TRole>(RoleManager<TRole> manager, TRole role) where TRole : class
{ {
if (manager == null) if (manager == null)
{ {
@ -49,8 +49,8 @@ namespace Microsoft.AspNet.Identity
return IdentityResult.Success; return IdentityResult.Success;
} }
private async Task ValidateRoleName(RoleManager<TRole> manager, TRole role, private async Task ValidateRoleName<TRole>(RoleManager<TRole> manager, TRole role,
ICollection<IdentityError> errors) ICollection<IdentityError> errors) where TRole : class
{ {
var roleName = await manager.GetRoleNameAsync(role); var roleName = await manager.GetRoleNameAsync(role);
if (string.IsNullOrWhiteSpace(roleName)) if (string.IsNullOrWhiteSpace(roleName))

View File

@ -9,8 +9,7 @@ namespace Microsoft.AspNet.Identity
/// Represents a token provider that generates time based codes using the user's security stamp. /// Represents a token provider that generates time based codes using the user's security stamp.
/// </summary> /// </summary>
/// <typeparam name="TUser">The type encapsulating a user.</typeparam> /// <typeparam name="TUser">The type encapsulating a user.</typeparam>
public abstract class TotpSecurityStampBasedTokenProvider<TUser> : IUserTokenProvider<TUser> public abstract class TotpSecurityStampBasedTokenProvider : IUserTokenProvider
where TUser : class
{ {
/// <summary> /// <summary>
/// Gets the name of the token provider. /// Gets the name of the token provider.
@ -37,7 +36,7 @@ namespace Microsoft.AspNet.Identity
/// Implementations of <see cref="IUserTokenProvider{TUser}"/> should validate that purpose is not null or empty to /// Implementations of <see cref="IUserTokenProvider{TUser}"/> should validate that purpose is not null or empty to
/// help with token separation. /// help with token separation.
/// </remarks> /// </remarks>
public virtual async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user) public virtual async Task<string> GenerateAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class
{ {
if (manager == null) if (manager == null)
{ {
@ -61,7 +60,7 @@ namespace Microsoft.AspNet.Identity
/// of validating the <paramref name="token"> for the specified </paramref><paramref name="user"/> and <paramref name="purpose"/>. /// of validating the <paramref name="token"> for the specified </paramref><paramref name="user"/> and <paramref name="purpose"/>.
/// The task will return true if the token is valid, otherwise false. /// The task will return true if the token is valid, otherwise false.
/// </returns> /// </returns>
public virtual async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user) public virtual async Task<bool> ValidateAsync<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class
{ {
if (manager == null) if (manager == null)
{ {
@ -87,7 +86,7 @@ namespace Microsoft.AspNet.Identity
/// The <see cref="Task"/> that represents the asynchronous operation, containing a constant modifier for the specified /// The <see cref="Task"/> that represents the asynchronous operation, containing a constant modifier for the specified
/// <paramref name="user"/> and <paramref name="purpose"/>. /// <paramref name="user"/> and <paramref name="purpose"/>.
/// </returns> /// </returns>
public virtual async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager, TUser user) public virtual async Task<string> GetUserModifierAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class
{ {
if (manager == null) if (manager == null)
{ {
@ -108,6 +107,6 @@ namespace Microsoft.AspNet.Identity
/// factor token could be generated by this provider for the specified <paramref name="user"/> and <paramref name="purpose"/>. /// factor token could be generated by this provider for the specified <paramref name="user"/> and <paramref name="purpose"/>.
/// The task will return true if a two factor authentication token could be generated, otherwise false. /// The task will return true if a two factor authentication token could be generated, otherwise false.
/// </returns> /// </returns>
public abstract Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user); public abstract Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class;
} }
} }

View File

@ -23,8 +23,8 @@ namespace Microsoft.AspNet.Identity
/// <typeparam name="TUser">The type encapsulating a user.</typeparam> /// <typeparam name="TUser">The type encapsulating a user.</typeparam>
public class UserManager<TUser> : IDisposable where TUser : class public class UserManager<TUser> : IDisposable where TUser : class
{ {
private readonly Dictionary<string, IUserTokenProvider<TUser>> _tokenProviders = private readonly Dictionary<string, IUserTokenProvider> _tokenProviders =
new Dictionary<string, IUserTokenProvider<TUser>>(); new Dictionary<string, IUserTokenProvider>();
private TimeSpan _defaultLockout = TimeSpan.Zero; private TimeSpan _defaultLockout = TimeSpan.Zero;
private bool _disposed; private bool _disposed;
@ -46,12 +46,12 @@ namespace Microsoft.AspNet.Identity
/// <param name="contextAccessor">The accessor used to access the <see cref="HttpContext"/>.</param> /// <param name="contextAccessor">The accessor used to access the <see cref="HttpContext"/>.</param>
public UserManager(IUserStore<TUser> store, public UserManager(IUserStore<TUser> store,
IOptions<IdentityOptions> optionsAccessor, IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<TUser> passwordHasher, IPasswordHasher passwordHasher,
IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IUserValidator> userValidators,
IEnumerable<IPasswordValidator<TUser>> passwordValidators, IEnumerable<IPasswordValidator> passwordValidators,
ILookupNormalizer keyNormalizer, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IdentityErrorDescriber errors,
IEnumerable<IUserTokenProvider<TUser>> tokenProviders, IEnumerable<IUserTokenProvider> tokenProviders,
ILogger<UserManager<TUser>> logger, ILogger<UserManager<TUser>> logger,
IHttpContextAccessor contextAccessor) IHttpContextAccessor contextAccessor)
{ {
@ -105,11 +105,11 @@ namespace Microsoft.AspNet.Identity
/// </value> /// </value>
protected internal virtual ILogger Logger { get; set; } protected internal virtual ILogger Logger { get; set; }
internal IPasswordHasher<TUser> PasswordHasher { get; set; } internal IPasswordHasher PasswordHasher { get; set; }
internal IList<IUserValidator<TUser>> UserValidators { get; } = new List<IUserValidator<TUser>>(); internal IList<IUserValidator> UserValidators { get; } = new List<IUserValidator>();
internal IList<IPasswordValidator<TUser>> PasswordValidators { get; } = new List<IPasswordValidator<TUser>>(); internal IList<IPasswordValidator> PasswordValidators { get; } = new List<IPasswordValidator>();
internal ILookupNormalizer KeyNormalizer { get; set; } internal ILookupNormalizer KeyNormalizer { get; set; }
@ -1557,7 +1557,7 @@ namespace Microsoft.AspNet.Identity
/// Registers a token provider. /// Registers a token provider.
/// </summary> /// </summary>
/// <param name="provider">The provider to register.</param> /// <param name="provider">The provider to register.</param>
public virtual void RegisterTokenProvider(IUserTokenProvider<TUser> provider) public virtual void RegisterTokenProvider(IUserTokenProvider provider)
{ {
ThrowIfDisposed(); ThrowIfDisposed();
if (provider == null) if (provider == null)

View File

@ -7,8 +7,6 @@ using System.Linq;
#if DNX451 #if DNX451
using System.Net.Mail; using System.Net.Mail;
#endif #endif
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity
@ -17,7 +15,7 @@ namespace Microsoft.AspNet.Identity
/// Provides validation services for user classes. /// Provides validation services for user classes.
/// </summary> /// </summary>
/// <typeparam name="TRole">The type encapsulating a user.</typeparam> /// <typeparam name="TRole">The type encapsulating a user.</typeparam>
public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class public class UserValidator : IUserValidator
{ {
/// <summary> /// <summary>
/// Creates a new instance of <see cref="UserValidator{TUser}"/>/ /// Creates a new instance of <see cref="UserValidator{TUser}"/>/
@ -40,7 +38,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager">The <see cref="UserManager{TUser}"/> that can be used to retrieve user properties.</param> /// <param name="manager">The <see cref="UserManager{TUser}"/> that can be used to retrieve user properties.</param>
/// <param name="user">The user to validate.</param> /// <param name="user">The user to validate.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the validation operation.</returns> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the validation operation.</returns>
public virtual async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user) public virtual async Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class
{ {
if (manager == null) if (manager == null)
{ {
@ -59,7 +57,7 @@ namespace Microsoft.AspNet.Identity
return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success; return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success;
} }
private async Task ValidateUserName(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors) private async Task ValidateUserName<TUser>(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors) where TUser : class
{ {
var userName = await manager.GetUserNameAsync(user); var userName = await manager.GetUserNameAsync(user);
if (string.IsNullOrWhiteSpace(userName)) if (string.IsNullOrWhiteSpace(userName))
@ -83,7 +81,7 @@ namespace Microsoft.AspNet.Identity
} }
// make sure email is not empty, valid, and unique // make sure email is not empty, valid, and unique
private async Task ValidateEmail(UserManager<TUser> manager, TUser user, List<IdentityError> errors) private async Task ValidateEmail<TUser>(UserManager<TUser> manager, TUser user, List<IdentityError> errors) where TUser : class
{ {
var email = await manager.GetEmailAsync(user); var email = await manager.GetEmailAsync(user);
if (string.IsNullOrWhiteSpace(email)) if (string.IsNullOrWhiteSpace(email))

View File

@ -37,7 +37,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity<TestUser,TestRole>().AddRoleValidator<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddRoleValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<TestRole>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -46,7 +46,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity<TestUser,TestRole>().AddUserValidator<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddUserValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<TestUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -55,7 +55,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity<TestUser,TestRole>().AddPasswordValidator<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddPasswordValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<TestUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -88,13 +88,13 @@ namespace Microsoft.AspNet.Identity.Test
services.AddIdentity<TestUser,TestRole>(); services.AddIdentity<TestUser,TestRole>();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var userValidator = provider.GetRequiredService<IUserValidator<TestUser>>() as UserValidator<TestUser>; var userValidator = provider.GetRequiredService<IUserValidator>() as UserValidator;
Assert.NotNull(userValidator); Assert.NotNull(userValidator);
var pwdValidator = provider.GetRequiredService<IPasswordValidator<TestUser>>() as PasswordValidator<TestUser>; var pwdValidator = provider.GetRequiredService<IPasswordValidator>() as PasswordValidator;
Assert.NotNull(pwdValidator); Assert.NotNull(pwdValidator);
var hasher = provider.GetRequiredService<IPasswordHasher<TestUser>>() as PasswordHasher<TestUser>; var hasher = provider.GetRequiredService<IPasswordHasher>() as PasswordHasher;
Assert.NotNull(hasher); Assert.NotNull(hasher);
} }
@ -105,11 +105,11 @@ namespace Microsoft.AspNet.Identity.Test
services.AddIdentity<TestUser,TestRole>().AddDefaultTokenProviders(); services.AddIdentity<TestUser,TestRole>().AddDefaultTokenProviders();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var tokenProviders = provider.GetRequiredService<IEnumerable<IUserTokenProvider<TestUser>>>(); var tokenProviders = provider.GetRequiredService<IEnumerable<IUserTokenProvider>>();
Assert.Equal(3, tokenProviders.Count()); Assert.Equal(3, tokenProviders.Count());
} }
private class MyUberThingy : IUserValidator<TestUser>, IPasswordValidator<TestUser>, IRoleValidator<TestRole>, IUserStore<TestUser>, IRoleStore<TestRole> private class MyUberThingy : IUserValidator, IPasswordValidator, IRoleValidator, IUserStore<TestUser>, IRoleStore<TestRole>
{ {
public Task<IdentityResult> CreateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
@ -221,6 +221,21 @@ namespace Microsoft.AspNet.Identity.Test
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync<TRole>(RoleManager<TRole> manager, TRole role) where TRole : class
{
throw new NotImplementedException();
}
public Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class
{
throw new NotImplementedException();
}
public Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user, string password) where TUser : class
{
throw new NotImplementedException();
}
Task<TestRole> IRoleStore<TestRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken) Task<TestRole> IRoleStore<TestRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
@ -240,7 +255,7 @@ namespace Microsoft.AspNet.Identity.Test
private class MyRoleManager : RoleManager<TestRole> private class MyRoleManager : RoleManager<TestRole>
{ {
public MyRoleManager(IRoleStore<TestRole> store, public MyRoleManager(IRoleStore<TestRole> store,
IEnumerable<IRoleValidator<TestRole>> roleValidators) : base(store, null, null, null, null, null) IEnumerable<IRoleValidator> roleValidators) : base(store, null, null, null, null, null)
{ {
} }

View File

@ -16,7 +16,7 @@ namespace Microsoft.AspNet.Identity.Test
// Act & assert // Act & assert
var ex = Assert.Throws<InvalidOperationException>(() => var ex = Assert.Throws<InvalidOperationException>(() =>
{ {
new PasswordHasher(compatMode: (PasswordHasherCompatibilityMode)(-1)); new TestPasswordHasher(compatMode: (PasswordHasherCompatibilityMode)(-1));
}); });
Assert.Equal("The provided PasswordHasherCompatibilityMode is invalid.", ex.Message); Assert.Equal("The provided PasswordHasherCompatibilityMode is invalid.", ex.Message);
} }
@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Identity.Test
// Act & assert // Act & assert
var ex = Assert.Throws<InvalidOperationException>(() => var ex = Assert.Throws<InvalidOperationException>(() =>
{ {
new PasswordHasher(iterCount: iterCount); new TestPasswordHasher(iterCount: iterCount);
}); });
Assert.Equal("The iteration count must be a positive integer.", ex.Message); Assert.Equal("The iteration count must be a positive integer.", ex.Message);
} }
@ -40,15 +40,15 @@ namespace Microsoft.AspNet.Identity.Test
public void FullRoundTrip(PasswordHasherCompatibilityMode compatMode) public void FullRoundTrip(PasswordHasherCompatibilityMode compatMode)
{ {
// Arrange // Arrange
var hasher = new PasswordHasher(compatMode: compatMode); var hasher = new TestPasswordHasher(compatMode: compatMode);
// Act & assert - success case // Act & assert - success case
var hashedPassword = hasher.HashPassword(null, "password 1"); var hashedPassword = hasher.HashPassword<object>(null, "password 1");
var successResult = hasher.VerifyHashedPassword(null, hashedPassword, "password 1"); var successResult = hasher.VerifyHashedPassword<object>(null, hashedPassword, "password 1");
Assert.Equal(PasswordVerificationResult.Success, successResult); Assert.Equal(PasswordVerificationResult.Success, successResult);
// Act & assert - failure case // Act & assert - failure case
var failedResult = hasher.VerifyHashedPassword(null, hashedPassword, "password 2"); var failedResult = hasher.VerifyHashedPassword<object>(null, hashedPassword, "password 2");
Assert.Equal(PasswordVerificationResult.Failed, failedResult); Assert.Equal(PasswordVerificationResult.Failed, failedResult);
} }
@ -56,10 +56,10 @@ namespace Microsoft.AspNet.Identity.Test
public void HashPassword_DefaultsToVersion3() public void HashPassword_DefaultsToVersion3()
{ {
// Arrange // Arrange
var hasher = new PasswordHasher(compatMode: null); var hasher = new TestPasswordHasher(compatMode: null);
// Act // Act
string retVal = hasher.HashPassword(null, "my password"); string retVal = hasher.HashPassword<object>(null, "my password");
// Assert // Assert
Assert.Equal("AQAAAAEAACcQAAAAEAABAgMEBQYHCAkKCwwNDg+yWU7rLgUwPZb1Itsmra7cbxw2EFpwpVFIEtP+JIuUEw==", retVal); Assert.Equal("AQAAAAEAACcQAAAAEAABAgMEBQYHCAkKCwwNDg+yWU7rLgUwPZb1Itsmra7cbxw2EFpwpVFIEtP+JIuUEw==", retVal);
@ -69,10 +69,10 @@ namespace Microsoft.AspNet.Identity.Test
public void HashPassword_Version2() public void HashPassword_Version2()
{ {
// Arrange // Arrange
var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2); var hasher = new TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2);
// Act // Act
string retVal = hasher.HashPassword(null, "my password"); string retVal = hasher.HashPassword<object>(null, "my password");
// Assert // Assert
Assert.Equal("AAABAgMEBQYHCAkKCwwNDg+ukCEMDf0yyQ29NYubggHIVY0sdEUfdyeM+E1LtH1uJg==", retVal); Assert.Equal("AAABAgMEBQYHCAkKCwwNDg+ukCEMDf0yyQ29NYubggHIVY0sdEUfdyeM+E1LtH1uJg==", retVal);
@ -82,10 +82,10 @@ namespace Microsoft.AspNet.Identity.Test
public void HashPassword_Version3() public void HashPassword_Version3()
{ {
// Arrange // Arrange
var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3); var hasher = new TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3);
// Act // Act
string retVal = hasher.HashPassword(null, "my password"); string retVal = hasher.HashPassword<object>(null, "my password");
// Assert // Assert
Assert.Equal("AQAAAAEAACcQAAAAEAABAgMEBQYHCAkKCwwNDg+yWU7rLgUwPZb1Itsmra7cbxw2EFpwpVFIEtP+JIuUEw==", retVal); Assert.Equal("AQAAAAEAACcQAAAAEAABAgMEBQYHCAkKCwwNDg+yWU7rLgUwPZb1Itsmra7cbxw2EFpwpVFIEtP+JIuUEw==", retVal);
@ -106,7 +106,7 @@ namespace Microsoft.AspNet.Identity.Test
var hasher = new PasswordHasher(); var hasher = new PasswordHasher();
// Act // Act
var result = hasher.VerifyHashedPassword(null, hashedPassword, "my password"); var result = hasher.VerifyHashedPassword<object>(null, hashedPassword, "my password");
// Assert // Assert
Assert.Equal(PasswordVerificationResult.Failed, result); Assert.Equal(PasswordVerificationResult.Failed, result);
@ -123,10 +123,10 @@ namespace Microsoft.AspNet.Identity.Test
public void VerifyHashedPassword_Version2CompatMode_SuccessCases(string hashedPassword) public void VerifyHashedPassword_Version2CompatMode_SuccessCases(string hashedPassword)
{ {
// Arrange // Arrange
var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2); var hasher = new TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2);
// Act // Act
var result = hasher.VerifyHashedPassword(null, hashedPassword, "my password"); var result = hasher.VerifyHashedPassword<object>(null, hashedPassword, "my password");
// Assert // Assert
Assert.Equal(PasswordVerificationResult.Success, result); Assert.Equal(PasswordVerificationResult.Success, result);
@ -143,18 +143,18 @@ namespace Microsoft.AspNet.Identity.Test
public void VerifyHashedPassword_Version3CompatMode_SuccessCases(string hashedPassword, PasswordVerificationResult expectedResult) public void VerifyHashedPassword_Version3CompatMode_SuccessCases(string hashedPassword, PasswordVerificationResult expectedResult)
{ {
// Arrange // Arrange
var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3); var hasher = new TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3);
// Act // Act
var actualResult = hasher.VerifyHashedPassword(null, hashedPassword, "my password"); var actualResult = hasher.VerifyHashedPassword<object>(null, hashedPassword, "my password");
// Assert // Assert
Assert.Equal(expectedResult, actualResult); Assert.Equal(expectedResult, actualResult);
} }
private sealed class PasswordHasher : PasswordHasher<object> private sealed class TestPasswordHasher : PasswordHasher
{ {
public PasswordHasher(PasswordHasherCompatibilityMode? compatMode = null, int? iterCount = null) public TestPasswordHasher(PasswordHasherCompatibilityMode? compatMode = null, int? iterCount = null)
: base(BuildOptions(compatMode, iterCount)) : base(BuildOptions(compatMode, iterCount))
{ {
} }

View File

@ -26,12 +26,12 @@ namespace Microsoft.AspNet.Identity.Test
public async Task ValidateThrowsWithNullTest() public async Task ValidateThrowsWithNullTest()
{ {
// Setup // Setup
var validator = new PasswordValidator<TestUser>(); var validator = new PasswordValidator();
// Act // Act
// Assert // Assert
await Assert.ThrowsAsync<ArgumentNullException>("password", () => validator.ValidateAsync(null, null, null)); await Assert.ThrowsAsync<ArgumentNullException>("password", () => validator.ValidateAsync<object>(null, null, null));
await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync(null, null, "foo")); await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync<object>(null, null, "foo"));
} }
@ -43,7 +43,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
const string error = "Passwords must be at least 6 characters."; const string error = "Passwords must be at least 6 characters.";
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = false; manager.Options.Password.RequireNonLetterOrDigit = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -57,7 +57,7 @@ namespace Microsoft.AspNet.Identity.Test
public async Task SuccessIfLongEnoughTests(string input) public async Task SuccessIfLongEnoughTests(string input)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = false; manager.Options.Password.RequireNonLetterOrDigit = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -71,7 +71,7 @@ namespace Microsoft.AspNet.Identity.Test
public async Task FailsWithoutRequiredNonAlphanumericTests(string input) public async Task FailsWithoutRequiredNonAlphanumericTests(string input)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = true; manager.Options.Password.RequireNonLetterOrDigit = true;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -88,7 +88,7 @@ namespace Microsoft.AspNet.Identity.Test
public async Task SucceedsWithRequiredNonAlphanumericTests(string input) public async Task SucceedsWithRequiredNonAlphanumericTests(string input)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = true; manager.Options.Password.RequireNonLetterOrDigit = true;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -112,7 +112,7 @@ namespace Microsoft.AspNet.Identity.Test
const string digitError = "Passwords must have at least one digit ('0'-'9')."; const string digitError = "Passwords must have at least one digit ('0'-'9').";
const string lengthError = "Passwords must be at least 6 characters."; const string lengthError = "Passwords must be at least 6 characters.";
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator();
var errors = new List<string>(); var errors = new List<string>();
if ((errorMask & Errors.Length) != Errors.None) if ((errorMask & Errors.Length) != Errors.None)
{ {

View File

@ -13,12 +13,12 @@ namespace Microsoft.AspNet.Identity.Test
public async Task ValidateThrowsWithNull() public async Task ValidateThrowsWithNull()
{ {
// Setup // Setup
var validator = new RoleValidator<TestRole>(); var validator = new RoleValidator();
var manager = MockHelpers.TestRoleManager<TestRole>(); var manager = MockHelpers.TestRoleManager<TestRole>();
// Act // Act
// Assert // Assert
await Assert.ThrowsAsync<ArgumentNullException>("manager", async () => await validator.ValidateAsync(null, null)); await Assert.ThrowsAsync<ArgumentNullException>("manager", async () => await validator.ValidateAsync<object>(null, null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await validator.ValidateAsync(manager, null)); await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await validator.ValidateAsync(manager, null));
} }
@ -28,7 +28,7 @@ namespace Microsoft.AspNet.Identity.Test
public async Task ValidateFailsWithTooShortRoleName(string input) public async Task ValidateFailsWithTooShortRoleName(string input)
{ {
// Setup // Setup
var validator = new RoleValidator<TestRole>(); var validator = new RoleValidator();
var manager = MockHelpers.TestRoleManager<TestRole>(); var manager = MockHelpers.TestRoleManager<TestRole>();
var user = new TestRole {Name = input}; var user = new TestRole {Name = input};

View File

@ -415,7 +415,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
// Setup // Setup
var store = new Mock<IUserPasswordStore<TestUser>>(); var store = new Mock<IUserPasswordStore<TestUser>>();
var hasher = new Mock<IPasswordHasher<TestUser>>(); var hasher = new Mock<IPasswordHasher>();
var user = new TestUser { UserName = "Foo" }; var user = new TestUser { UserName = "Foo" };
var pwd = "password"; var pwd = "password";
var hashed = "hashed"; var hashed = "hashed";
@ -630,9 +630,9 @@ namespace Microsoft.AspNet.Identity.Test
// TODO: Can switch to Mock eventually // TODO: Can switch to Mock eventually
var manager = MockHelpers.TestUserManager(new EmptyStore()); var manager = MockHelpers.TestUserManager(new EmptyStore());
manager.PasswordValidators.Clear(); manager.PasswordValidators.Clear();
manager.PasswordValidators.Add(new BadPasswordValidator<TestUser>()); manager.PasswordValidators.Add(new BadPasswordValidator());
IdentityResultAssert.IsFailure(await manager.CreateAsync(new TestUser(), "password"), IdentityResultAssert.IsFailure(await manager.CreateAsync(new TestUser(), "password"),
BadPasswordValidator<TestUser>.ErrorMessage); BadPasswordValidator.ErrorMessage);
} }
[Fact] [Fact]
@ -819,11 +819,11 @@ namespace Microsoft.AspNet.Identity.Test
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.ConfirmEmailAsync(null, null)); await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.ConfirmEmailAsync(null, null));
} }
private class BadPasswordValidator<TUser> : IPasswordValidator<TUser> where TUser : class private class BadPasswordValidator : IPasswordValidator
{ {
public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad." }; public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad." };
public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password) Task<IdentityResult> IPasswordValidator.ValidateAsync<TUser>(UserManager<TUser> manager, TUser user, string password)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }
@ -1090,26 +1090,21 @@ namespace Microsoft.AspNet.Identity.Test
} }
} }
private class NoOpTokenProvider : IUserTokenProvider<TestUser> private class NoOpTokenProvider : IUserTokenProvider
{ {
public string Name { get; } = "Noop"; public string Name { get; } = "Noop";
public Task<string> GenerateAsync(string purpose, UserManager<TestUser> manager, TestUser user) public Task<string> GenerateAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class
{ {
return Task.FromResult("Test"); return Task.FromResult("Test");
} }
public Task<bool> ValidateAsync(string purpose, string token, UserManager<TestUser> manager, TestUser user) public Task<bool> ValidateAsync<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class
{ {
return Task.FromResult(true); return Task.FromResult(true);
} }
public Task NotifyAsync(string token, UserManager<TestUser> manager, TestUser user) public Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class
{
return Task.FromResult(0);
}
public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TestUser> manager, TestUser user)
{ {
return Task.FromResult(true); return Task.FromResult(true);
} }

View File

@ -14,11 +14,11 @@ namespace Microsoft.AspNet.Identity.Test
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
var validator = new UserValidator<TestUser>(); var validator = new UserValidator();
// Act // Act
// Assert // Assert
await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync(null, null)); await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync<object>(null, null));
await Assert.ThrowsAsync<ArgumentNullException>("user", () => validator.ValidateAsync(manager, null)); await Assert.ThrowsAsync<ArgumentNullException>("user", () => validator.ValidateAsync(manager, null));
} }
@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
var validator = new UserValidator<TestUser>(); var validator = new UserValidator();
var user = new TestUser {UserName = input}; var user = new TestUser {UserName = input};
// Act // Act
@ -50,7 +50,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
var validator = new UserValidator<TestUser>(); var validator = new UserValidator();
var user = new TestUser {UserName = userName}; var user = new TestUser {UserName = userName};
// Act // Act
@ -78,7 +78,7 @@ namespace Microsoft.AspNet.Identity.Test
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
manager.Options.User.AllowedUserNameCharacters = null; manager.Options.User.AllowedUserNameCharacters = null;
var validator = new UserValidator<TestUser>(); var validator = new UserValidator();
var user = new TestUser {UserName = userName}; var user = new TestUser {UserName = userName};
// Act // Act

View File

@ -22,16 +22,16 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var store = new Mock<IUserStore<TUser>>(); var store = new Mock<IUserStore<TUser>>();
var mgr = new Mock<UserManager<TUser>>(store.Object, null, null, null, null, null, null, null, null, null); var mgr = new Mock<UserManager<TUser>>(store.Object, null, null, null, null, null, null, null, null, null);
mgr.Object.UserValidators.Add(new UserValidator<TUser>()); mgr.Object.UserValidators.Add(new UserValidator());
mgr.Object.PasswordValidators.Add(new PasswordValidator<TUser>()); mgr.Object.PasswordValidators.Add(new PasswordValidator());
return mgr; return mgr;
} }
public static Mock<RoleManager<TRole>> MockRoleManager<TRole>(IRoleStore<TRole> store = null) where TRole : class public static Mock<RoleManager<TRole>> MockRoleManager<TRole>(IRoleStore<TRole> store = null) where TRole : class
{ {
store = store ?? new Mock<IRoleStore<TRole>>().Object; store = store ?? new Mock<IRoleStore<TRole>>().Object;
var roles = new List<IRoleValidator<TRole>>(); var roles = new List<IRoleValidator>();
roles.Add(new RoleValidator<TRole>()); roles.Add(new RoleValidator());
return new Mock<RoleManager<TRole>>(store, roles, null, null, null, null); return new Mock<RoleManager<TRole>>(store, roles, null, null, null, null);
} }
@ -71,14 +71,14 @@ namespace Microsoft.AspNet.Identity.Test
var idOptions = new IdentityOptions(); var idOptions = new IdentityOptions();
idOptions.Lockout.AllowedForNewUsers = false; idOptions.Lockout.AllowedForNewUsers = false;
options.Setup(o => o.Options).Returns(idOptions); options.Setup(o => o.Options).Returns(idOptions);
var userValidators = new List<IUserValidator<TUser>>(); var userValidators = new List<IUserValidator>();
var validator = new Mock<IUserValidator<TUser>>(); var validator = new Mock<IUserValidator>();
userValidators.Add(validator.Object); userValidators.Add(validator.Object);
var pwdValidators = new List<PasswordValidator<TUser>>(); var pwdValidators = new List<PasswordValidator>();
pwdValidators.Add(new PasswordValidator<TUser>()); pwdValidators.Add(new PasswordValidator());
var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher<TUser>(), var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher(),
userValidators, pwdValidators, new UpperInvariantLookupNormalizer(), userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), Enumerable.Empty<IUserTokenProvider<TUser>>(), new IdentityErrorDescriber(), Enumerable.Empty<IUserTokenProvider>(),
new Mock<ILogger<UserManager<TUser>>>().Object, new Mock<ILogger<UserManager<TUser>>>().Object,
null); null);
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>())) validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>()))
@ -89,8 +89,8 @@ namespace Microsoft.AspNet.Identity.Test
public static RoleManager<TRole> TestRoleManager<TRole>(IRoleStore<TRole> store = null) where TRole : class public static RoleManager<TRole> TestRoleManager<TRole>(IRoleStore<TRole> store = null) where TRole : class
{ {
store = store ?? new Mock<IRoleStore<TRole>>().Object; store = store ?? new Mock<IRoleStore<TRole>>().Object;
var roles = new List<IRoleValidator<TRole>>(); var roles = new List<IRoleValidator>();
roles.Add(new RoleValidator<TRole>()); roles.Add(new RoleValidator());
return new RoleManager<TRole>(store, roles, return new RoleManager<TRole>(store, roles,
new UpperInvariantLookupNormalizer(), new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), new IdentityErrorDescriber(),

View File

@ -163,7 +163,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var manager = CreateManager(); var manager = CreateManager();
manager.Options.User.RequireUniqueEmail = true; manager.Options.User.RequireUniqueEmail = true;
manager.UserValidators.Add(new UserValidator<TUser>()); manager.UserValidators.Add(new UserValidator());
var random = new Random(); var random = new Random();
var email = "foo" + random.Next() + "@example.com"; var email = "foo" + random.Next() + "@example.com";
var newEmail = "bar" + random.Next() + "@example.com"; var newEmail = "bar" + random.Next() + "@example.com";
@ -646,26 +646,21 @@ namespace Microsoft.AspNet.Identity.Test
Assert.False(await manager.IsEmailConfirmedAsync(user)); Assert.False(await manager.IsEmailConfirmedAsync(user));
} }
private class StaticTokenProvider : IUserTokenProvider<TUser> private class StaticTokenProvider : IUserTokenProvider
{ {
public string Name { get; } = "Static"; public string Name { get; } = "Static";
public async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user) async Task<string> IUserTokenProvider.GenerateAsync<TUser1>(string purpose, UserManager<TUser1> manager, TUser1 user)
{ {
return MakeToken(purpose, await manager.GetUserIdAsync(user)); return MakeToken(purpose, await manager.GetUserIdAsync(user));
} }
public async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user) async Task<bool> IUserTokenProvider.ValidateAsync<TUser1>(string purpose, string token, UserManager<TUser1> manager, TUser1 user)
{ {
return token == MakeToken(purpose, await manager.GetUserIdAsync(user)); return token == MakeToken(purpose, await manager.GetUserIdAsync(user));
} }
public Task NotifyAsync(string token, UserManager<TUser> manager, TUser user) Task<bool> IUserTokenProvider.CanGenerateTwoFactorTokenAsync<TUser1>(UserManager<TUser1> manager, TUser1 user)
{
return Task.FromResult(0);
}
public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{ {
return Task.FromResult(true); return Task.FromResult(true);
} }
@ -981,22 +976,21 @@ namespace Microsoft.AspNet.Identity.Test
Assert.True(await manager.RoleExistsAsync(roleName)); Assert.True(await manager.RoleExistsAsync(roleName));
} }
private class AlwaysBadValidator : IUserValidator<TUser>, IRoleValidator<TRole>, private class AlwaysBadValidator : IUserValidator, IRoleValidator, IPasswordValidator
IPasswordValidator<TUser>
{ {
public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad.", Code = "BadValidator" }; public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad.", Code = "BadValidator" };
public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password) Task<IdentityResult> IPasswordValidator.ValidateAsync<T>(UserManager<T> manager, T user, string password)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }
public Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role) Task<IdentityResult> IRoleValidator.ValidateAsync<TRole1>(RoleManager<TRole1> manager, TRole1 role)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }
public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user) Task<IdentityResult> IUserValidator.ValidateAsync<TUser1>(UserManager<TUser1> manager, TUser1 user)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }