Revert "Move generics off of Validator/TokenProvider interfaces"

This reverts commit 62a1d49710.
This commit is contained in:
Hao Kung 2015-08-14 12:51:16 -07:00
parent a669ae18b7
commit a98f86681d
25 changed files with 175 additions and 164 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 : IUserTokenProvider public class DataProtectorTokenProvider<TUser> : IUserTokenProvider<TUser> where TUser : class
{ {
/// <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<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class public virtual async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user)
{ {
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<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class public virtual async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user)
{ {
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<TUser>(UserManager<TUser> manager, TUser user) where TUser : class public virtual Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{ {
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<TUser>(string token, UserManager<TUser> manager, TUser user) where TUser : class public virtual Task NotifyAsync(string token, UserManager<TUser> manager, TUser user)
{ {
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -22,7 +22,8 @@ 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 : TotpSecurityStampBasedTokenProvider public class EmailTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser>
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.
@ -60,7 +61,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<TUser>(UserManager<TUser> manager, TUser user) public override async Task<bool> CanGenerateTwoFactorTokenAsync(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);
@ -73,7 +74,8 @@ 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<TUser>(string purpose, UserManager<TUser> manager, TUser user) public override async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager,
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 public interface IPasswordHasher<TUser> where TUser : class
{ {
/// <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>(TUser user, string password) where TUser : class; string HashPassword(TUser user, string password);
/// <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>(TUser user, string hashedPassword, string providedPassword) where TUser : class; PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword);
} }
} }

View File

@ -1,6 +1,7 @@
// 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
@ -9,7 +10,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 public interface IPasswordValidator<TUser> where TUser : class
{ {
/// <summary> /// <summary>
/// Validates a password as an asynchronous operation. /// Validates a password as an asynchronous operation.
@ -18,6 +19,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<TUser>(UserManager<TUser> manager, TUser user, string password) where TUser : class; Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password);
} }
} }

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 public interface IRoleValidator<TRole> where TRole : class
{ {
/// <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<TRole>(RoleManager<TRole> manager, TRole role) where TRole : class; Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role);
} }
} }

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 public interface IUserTokenProvider<TUser> where TUser : class
{ {
/// <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<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class; Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user);
/// <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<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class; Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user);
/// <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<TUser>(UserManager<TUser> manager, TUser user) where TUser : class; Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user);
} }
} }

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 public interface IUserValidator<TUser> where TUser : class
{ {
/// <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<TUser>(UserManager<TUser> manager, TUser user) where TUser : class; Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user);
} }
} }

View File

@ -60,10 +60,9 @@ 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<TValidator>() where TValidator : class, IUserValidator public virtual IdentityBuilder AddUserValidator<T>() where T : class
{ {
Services.AddScoped<IUserValidator, TValidator>(); return AddScoped(typeof(IUserValidator<>).MakeGenericType(UserType), typeof(T));
return this;
} }
/// <summary> /// <summary>
@ -71,10 +70,9 @@ 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<TValidator>() where TValidator : class, IRoleValidator public virtual IdentityBuilder AddRoleValidator<T>() where T : class
{ {
Services.AddScoped<IRoleValidator, TValidator>(); return AddScoped(typeof(IRoleValidator<>).MakeGenericType(RoleType), typeof(T));
return this;
} }
/// <summary> /// <summary>
@ -93,10 +91,9 @@ 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<TValidator>() where TValidator : class,IPasswordValidator public virtual IdentityBuilder AddPasswordValidator<T>() where T : class
{ {
Services.AddScoped<IPasswordValidator, TValidator>(); return AddScoped(typeof(IPasswordValidator<>).MakeGenericType(UserType), typeof(T));
return this;
} }
/// <summary> /// <summary>
@ -124,10 +121,19 @@ 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, IUserTokenProvider public virtual IdentityBuilder AddTokenProvider<TProvider>() where TProvider : class
{ {
Services.AddScoped<IUserTokenProvider, TProvider>(); return AddTokenProvider(typeof(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>
@ -141,9 +147,9 @@ namespace Microsoft.AspNet.Identity
options.Name = Resources.DefaultTokenProvider; options.Name = Resources.DefaultTokenProvider;
}); });
return AddTokenProvider<DataProtectorTokenProvider>() return AddTokenProvider(typeof(DataProtectorTokenProvider<>).MakeGenericType(UserType))
.AddTokenProvider<PhoneNumberTokenProvider>() .AddTokenProvider(typeof(PhoneNumberTokenProvider<>).MakeGenericType(UserType))
.AddTokenProvider<EmailTokenProvider>(); .AddTokenProvider(typeof(EmailTokenProvider<>).MakeGenericType(UserType));
} }
/// <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, UserValidator>()); services.TryAdd(ServiceDescriptor.Scoped<IUserValidator<TUser>, UserValidator<TUser>>());
services.TryAdd(ServiceDescriptor.Scoped<IPasswordValidator, PasswordValidator>()); services.TryAdd(ServiceDescriptor.Scoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>());
services.TryAdd(ServiceDescriptor.Scoped<IPasswordHasher, PasswordHasher>()); services.TryAdd(ServiceDescriptor.Scoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>());
services.TryAdd(ServiceDescriptor.Scoped<ILookupNormalizer, UpperInvariantLookupNormalizer>()); services.TryAdd(ServiceDescriptor.Scoped<ILookupNormalizer, UpperInvariantLookupNormalizer>());
services.TryAdd(ServiceDescriptor.Scoped<IRoleValidator, RoleValidator>()); services.TryAdd(ServiceDescriptor.Scoped<IRoleValidator<TRole>, RoleValidator<TRole>>());
// 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: IPasswordHasher public class PasswordHasher<TUser> : IPasswordHasher<TUser> where TUser : class
{ {
/* ======================= /* =======================
* 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>(TUser user, string password) where TUser : class public virtual string HashPassword(TUser user, string password)
{ {
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>(TUser user, string hashedPassword, string providedPassword) where TUser : class public virtual PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
{ {
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 : IPasswordValidator public class PasswordValidator<TUser> : IPasswordValidator<TUser> where TUser : class
{ {
/// <summary> /// <summary>
/// Constructions a new instance of <see cref="PasswordValidator"/>. /// Constructions a new instance of <see cref="PasswordValidator{TUser}"/>.
/// </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<TUser>(UserManager<TUser> manager, TUser user, string password) where TUser : class public virtual Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password)
{ {
if (password == null) if (password == null)
{ {

View File

@ -23,7 +23,8 @@ 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 : TotpSecurityStampBasedTokenProvider public class PhoneNumberTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser>
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"/>.
@ -62,7 +63,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<TUser>(UserManager<TUser> manager, TUser user) public override async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {
@ -82,7 +83,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<TUser>(string purpose, UserManager<TUser> manager, TUser user) public override async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {

View File

@ -4,9 +4,11 @@
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;
@ -32,7 +34,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> roleValidators, IEnumerable<IRoleValidator<TRole>> roleValidators,
ILookupNormalizer keyNormalizer, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IdentityErrorDescriber errors,
ILogger<RoleManager<TRole>> logger, ILogger<RoleManager<TRole>> logger,
@ -75,7 +77,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> RoleValidators { get; } = new List<IRoleValidator>(); internal IList<IRoleValidator<TRole>> RoleValidators { get; } = new List<IRoleValidator<TRole>>();
/// <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 : IRoleValidator public class RoleValidator<TRole> : IRoleValidator<TRole> where TRole : class
{ {
/// <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<TRole>(RoleManager<TRole> manager, TRole role) where TRole : class public virtual async Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role)
{ {
if (manager == null) if (manager == null)
{ {
@ -49,8 +49,8 @@ namespace Microsoft.AspNet.Identity
return IdentityResult.Success; return IdentityResult.Success;
} }
private async Task ValidateRoleName<TRole>(RoleManager<TRole> manager, TRole role, private async Task ValidateRoleName(RoleManager<TRole> manager, TRole role,
ICollection<IdentityError> errors) where TRole : class ICollection<IdentityError> errors)
{ {
var roleName = await manager.GetRoleNameAsync(role); var roleName = await manager.GetRoleNameAsync(role);
if (string.IsNullOrWhiteSpace(roleName)) if (string.IsNullOrWhiteSpace(roleName))

View File

@ -9,7 +9,8 @@ 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 : IUserTokenProvider public abstract class TotpSecurityStampBasedTokenProvider<TUser> : IUserTokenProvider<TUser>
where TUser : class
{ {
/// <summary> /// <summary>
/// Gets the name of the token provider. /// Gets the name of the token provider.
@ -36,7 +37,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<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class public virtual async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {
@ -60,7 +61,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<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class public virtual async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {
@ -86,7 +87,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<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class public virtual async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {
@ -107,6 +108,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<TUser>(UserManager<TUser> manager, TUser user) where TUser : class; public abstract Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user);
} }
} }

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> _tokenProviders = private readonly Dictionary<string, IUserTokenProvider<TUser>> _tokenProviders =
new Dictionary<string, IUserTokenProvider>(); new Dictionary<string, IUserTokenProvider<TUser>>();
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 passwordHasher, IPasswordHasher<TUser> passwordHasher,
IEnumerable<IUserValidator> userValidators, IEnumerable<IUserValidator<TUser>> userValidators,
IEnumerable<IPasswordValidator> passwordValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators,
ILookupNormalizer keyNormalizer, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IdentityErrorDescriber errors,
IEnumerable<IUserTokenProvider> tokenProviders, IEnumerable<IUserTokenProvider<TUser>> 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 PasswordHasher { get; set; } internal IPasswordHasher<TUser> PasswordHasher { get; set; }
internal IList<IUserValidator> UserValidators { get; } = new List<IUserValidator>(); internal IList<IUserValidator<TUser>> UserValidators { get; } = new List<IUserValidator<TUser>>();
internal IList<IPasswordValidator> PasswordValidators { get; } = new List<IPasswordValidator>(); internal IList<IPasswordValidator<TUser>> PasswordValidators { get; } = new List<IPasswordValidator<TUser>>();
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 provider) public virtual void RegisterTokenProvider(IUserTokenProvider<TUser> provider)
{ {
ThrowIfDisposed(); ThrowIfDisposed();
if (provider == null) if (provider == null)

View File

@ -7,6 +7,8 @@ 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
@ -15,7 +17,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 : IUserValidator public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class
{ {
/// <summary> /// <summary>
/// Creates a new instance of <see cref="UserValidator{TUser}"/>/ /// Creates a new instance of <see cref="UserValidator{TUser}"/>/
@ -38,7 +40,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<TUser>(UserManager<TUser> manager, TUser user) where TUser : class public virtual async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
{ {
if (manager == null) if (manager == null)
{ {
@ -57,7 +59,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<TUser>(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors) where TUser : class private async Task ValidateUserName(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors)
{ {
var userName = await manager.GetUserNameAsync(user); var userName = await manager.GetUserNameAsync(user);
if (string.IsNullOrWhiteSpace(userName)) if (string.IsNullOrWhiteSpace(userName))
@ -81,7 +83,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<TUser>(UserManager<TUser> manager, TUser user, List<IdentityError> errors) where TUser : class private async Task ValidateEmail(UserManager<TUser> manager, TUser user, List<IdentityError> errors)
{ {
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>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<TestRole>>() 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>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<TestUser>>() 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>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<TestUser>>() 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>() as UserValidator; var userValidator = provider.GetRequiredService<IUserValidator<TestUser>>() as UserValidator<TestUser>;
Assert.NotNull(userValidator); Assert.NotNull(userValidator);
var pwdValidator = provider.GetRequiredService<IPasswordValidator>() as PasswordValidator; var pwdValidator = provider.GetRequiredService<IPasswordValidator<TestUser>>() as PasswordValidator<TestUser>;
Assert.NotNull(pwdValidator); Assert.NotNull(pwdValidator);
var hasher = provider.GetRequiredService<IPasswordHasher>() as PasswordHasher; var hasher = provider.GetRequiredService<IPasswordHasher<TestUser>>() as PasswordHasher<TestUser>;
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>>(); var tokenProviders = provider.GetRequiredService<IEnumerable<IUserTokenProvider<TestUser>>>();
Assert.Equal(3, tokenProviders.Count()); Assert.Equal(3, tokenProviders.Count());
} }
private class MyUberThingy : IUserValidator, IPasswordValidator, IRoleValidator, IUserStore<TestUser>, IRoleStore<TestRole> private class MyUberThingy : IUserValidator<TestUser>, IPasswordValidator<TestUser>, IRoleValidator<TestRole>, 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,21 +221,6 @@ 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();
@ -255,7 +240,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> roleValidators) : base(store, null, null, null, null, null) IEnumerable<IRoleValidator<TestRole>> 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 TestPasswordHasher(compatMode: (PasswordHasherCompatibilityMode)(-1)); new PasswordHasher(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 TestPasswordHasher(iterCount: iterCount); new PasswordHasher(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 TestPasswordHasher(compatMode: compatMode); var hasher = new PasswordHasher(compatMode: compatMode);
// Act & assert - success case // Act & assert - success case
var hashedPassword = hasher.HashPassword<object>(null, "password 1"); var hashedPassword = hasher.HashPassword(null, "password 1");
var successResult = hasher.VerifyHashedPassword<object>(null, hashedPassword, "password 1"); var successResult = hasher.VerifyHashedPassword(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<object>(null, hashedPassword, "password 2"); var failedResult = hasher.VerifyHashedPassword(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 TestPasswordHasher(compatMode: null); var hasher = new PasswordHasher(compatMode: null);
// Act // Act
string retVal = hasher.HashPassword<object>(null, "my password"); string retVal = hasher.HashPassword(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 TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2); var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2);
// Act // Act
string retVal = hasher.HashPassword<object>(null, "my password"); string retVal = hasher.HashPassword(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 TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3); var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3);
// Act // Act
string retVal = hasher.HashPassword<object>(null, "my password"); string retVal = hasher.HashPassword(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<object>(null, hashedPassword, "my password"); var result = hasher.VerifyHashedPassword(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 TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2); var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV2);
// Act // Act
var result = hasher.VerifyHashedPassword<object>(null, hashedPassword, "my password"); var result = hasher.VerifyHashedPassword(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 TestPasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3); var hasher = new PasswordHasher(compatMode: PasswordHasherCompatibilityMode.IdentityV3);
// Act // Act
var actualResult = hasher.VerifyHashedPassword<object>(null, hashedPassword, "my password"); var actualResult = hasher.VerifyHashedPassword(null, hashedPassword, "my password");
// Assert // Assert
Assert.Equal(expectedResult, actualResult); Assert.Equal(expectedResult, actualResult);
} }
private sealed class TestPasswordHasher : PasswordHasher private sealed class PasswordHasher : PasswordHasher<object>
{ {
public TestPasswordHasher(PasswordHasherCompatibilityMode? compatMode = null, int? iterCount = null) public PasswordHasher(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(); var validator = new PasswordValidator<TestUser>();
// Act // Act
// Assert // Assert
await Assert.ThrowsAsync<ArgumentNullException>("password", () => validator.ValidateAsync<object>(null, null, null)); await Assert.ThrowsAsync<ArgumentNullException>("password", () => validator.ValidateAsync(null, null, null));
await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync<object>(null, null, "foo")); await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync(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(); var valid = new PasswordValidator<TestUser>();
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(); var valid = new PasswordValidator<TestUser>();
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(); var valid = new PasswordValidator<TestUser>();
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(); var valid = new PasswordValidator<TestUser>();
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(); var valid = new PasswordValidator<TestUser>();
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(); var validator = new RoleValidator<TestRole>();
var manager = MockHelpers.TestRoleManager<TestRole>(); var manager = MockHelpers.TestRoleManager<TestRole>();
// Act // Act
// Assert // Assert
await Assert.ThrowsAsync<ArgumentNullException>("manager", async () => await validator.ValidateAsync<object>(null, null)); await Assert.ThrowsAsync<ArgumentNullException>("manager", async () => await validator.ValidateAsync(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(); var validator = new RoleValidator<TestRole>();
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>(); var hasher = new Mock<IPasswordHasher<TestUser>>();
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()); manager.PasswordValidators.Add(new BadPasswordValidator<TestUser>());
IdentityResultAssert.IsFailure(await manager.CreateAsync(new TestUser(), "password"), IdentityResultAssert.IsFailure(await manager.CreateAsync(new TestUser(), "password"),
BadPasswordValidator.ErrorMessage); BadPasswordValidator<TestUser>.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 : IPasswordValidator private class BadPasswordValidator<TUser> : IPasswordValidator<TUser> where TUser : class
{ {
public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad." }; public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad." };
Task<IdentityResult> IPasswordValidator.ValidateAsync<TUser>(UserManager<TUser> manager, TUser user, string password) public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }
@ -1090,21 +1090,26 @@ namespace Microsoft.AspNet.Identity.Test
} }
} }
private class NoOpTokenProvider : IUserTokenProvider private class NoOpTokenProvider : IUserTokenProvider<TestUser>
{ {
public string Name { get; } = "Noop"; public string Name { get; } = "Noop";
public Task<string> GenerateAsync<TUser>(string purpose, UserManager<TUser> manager, TUser user) where TUser : class public Task<string> GenerateAsync(string purpose, UserManager<TestUser> manager, TestUser user)
{ {
return Task.FromResult("Test"); return Task.FromResult("Test");
} }
public Task<bool> ValidateAsync<TUser>(string purpose, string token, UserManager<TUser> manager, TUser user) where TUser : class public Task<bool> ValidateAsync(string purpose, string token, UserManager<TestUser> manager, TestUser user)
{ {
return Task.FromResult(true); return Task.FromResult(true);
} }
public Task<bool> CanGenerateTwoFactorTokenAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class public Task NotifyAsync(string token, UserManager<TestUser> manager, TestUser user)
{
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(); var validator = new UserValidator<TestUser>();
// Act // Act
// Assert // Assert
await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync<object>(null, null)); await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync(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(); var validator = new UserValidator<TestUser>();
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(); var validator = new UserValidator<TestUser>();
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(); var validator = new UserValidator<TestUser>();
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()); mgr.Object.UserValidators.Add(new UserValidator<TUser>());
mgr.Object.PasswordValidators.Add(new PasswordValidator()); mgr.Object.PasswordValidators.Add(new PasswordValidator<TUser>());
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>(); var roles = new List<IRoleValidator<TRole>>();
roles.Add(new RoleValidator()); roles.Add(new RoleValidator<TRole>());
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>(); var userValidators = new List<IUserValidator<TUser>>();
var validator = new Mock<IUserValidator>(); var validator = new Mock<IUserValidator<TUser>>();
userValidators.Add(validator.Object); userValidators.Add(validator.Object);
var pwdValidators = new List<PasswordValidator>(); var pwdValidators = new List<PasswordValidator<TUser>>();
pwdValidators.Add(new PasswordValidator()); pwdValidators.Add(new PasswordValidator<TUser>());
var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher(), var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher<TUser>(),
userValidators, pwdValidators, new UpperInvariantLookupNormalizer(), userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), Enumerable.Empty<IUserTokenProvider>(), new IdentityErrorDescriber(), Enumerable.Empty<IUserTokenProvider<TUser>>(),
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>(); var roles = new List<IRoleValidator<TRole>>();
roles.Add(new RoleValidator()); roles.Add(new RoleValidator<TRole>());
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()); manager.UserValidators.Add(new UserValidator<TUser>());
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,21 +646,26 @@ namespace Microsoft.AspNet.Identity.Test
Assert.False(await manager.IsEmailConfirmedAsync(user)); Assert.False(await manager.IsEmailConfirmedAsync(user));
} }
private class StaticTokenProvider : IUserTokenProvider private class StaticTokenProvider : IUserTokenProvider<TUser>
{ {
public string Name { get; } = "Static"; public string Name { get; } = "Static";
async Task<string> IUserTokenProvider.GenerateAsync<TUser1>(string purpose, UserManager<TUser1> manager, TUser1 user) public async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user)
{ {
return MakeToken(purpose, await manager.GetUserIdAsync(user)); return MakeToken(purpose, await manager.GetUserIdAsync(user));
} }
async Task<bool> IUserTokenProvider.ValidateAsync<TUser1>(string purpose, string token, UserManager<TUser1> manager, TUser1 user) public async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user)
{ {
return token == MakeToken(purpose, await manager.GetUserIdAsync(user)); return token == MakeToken(purpose, await manager.GetUserIdAsync(user));
} }
Task<bool> IUserTokenProvider.CanGenerateTwoFactorTokenAsync<TUser1>(UserManager<TUser1> manager, TUser1 user) public Task NotifyAsync(string token, UserManager<TUser> manager, TUser user)
{
return Task.FromResult(0);
}
public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{ {
return Task.FromResult(true); return Task.FromResult(true);
} }
@ -976,21 +981,22 @@ namespace Microsoft.AspNet.Identity.Test
Assert.True(await manager.RoleExistsAsync(roleName)); Assert.True(await manager.RoleExistsAsync(roleName));
} }
private class AlwaysBadValidator : IUserValidator, IRoleValidator, IPasswordValidator private class AlwaysBadValidator : IUserValidator<TUser>, IRoleValidator<TRole>,
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" };
Task<IdentityResult> IPasswordValidator.ValidateAsync<T>(UserManager<T> manager, T user, string password) public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }
Task<IdentityResult> IRoleValidator.ValidateAsync<TRole1>(RoleManager<TRole1> manager, TRole1 role) public Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }
Task<IdentityResult> IUserValidator.ValidateAsync<TUser1>(UserManager<TUser1> manager, TUser1 user) public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
{ {
return Task.FromResult(IdentityResult.Failed(ErrorMessage)); return Task.FromResult(IdentityResult.Failed(ErrorMessage));
} }