Sql implementation + moving in memory stores to test

- Identity.Entity now means only Sql Server EF Identity implementation
- Identity.Entity.InMemory moved to a test project
(Identity.Entity.InMemory.Test)
- Identity.InMemory which was the identity in memory implementation also
moved to a test project (Identity.InMemory.Test)
- IClaimsFactory was promoted to a top level service and now adds any
claims found in a Role that a user belongs to.
- EF implementation now supports logins, claims, roles, two factor,
lockouts
- Initial pass at style cop (mostly line endings since resharper no
worky :()
This commit is contained in:
Hao Kung 2014-06-23 14:53:06 -07:00
parent 1b5566010b
commit bc4c53f086
90 changed files with 7738 additions and 1943 deletions

View File

@ -7,8 +7,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{0F647068-660
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{52D59F18-62D2-4D17-8CF2-BE192445AF8E}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.InMemory", "src\Microsoft.AspNet.Identity.InMemory\Microsoft.AspNet.Identity.InMemory.kproj", "{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity", "src\Microsoft.AspNet.Identity\Microsoft.AspNet.Identity.kproj", "{1729302E-A58E-4652-B639-5B6B68DA2748}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.EntityFramework", "src\Microsoft.AspNet.Identity.EntityFramework\Microsoft.AspNet.Identity.EntityFramework.kproj", "{AD42BAFB-1993-4FAF-A280-3711A9F33E2F}"
@ -23,6 +21,8 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.I
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.EntityFramework.Test", "test\Microsoft.AspNet.Identity.EntityFramework.Test\Microsoft.AspNet.Identity.EntityFramework.Test.kproj", "{B4C067C1-F934-493C-9DBC-19E8CA305613}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.EntityFramework.InMemory.Test", "test\Microsoft.AspNet.Identity.EntityFramework.InMemory.Test\Microsoft.AspNet.Identity.EntityFramework.InMemory.Test.kproj", "{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -33,16 +33,6 @@ Global
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Debug|x86.ActiveCfg = Debug|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Release|Any CPU.Build.0 = Release|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74}.Release|x86.ActiveCfg = Release|Any CPU
{1729302E-A58E-4652-B639-5B6B68DA2748}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1729302E-A58E-4652-B639-5B6B68DA2748}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1729302E-A58E-4652-B639-5B6B68DA2748}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
@ -113,12 +103,21 @@ Global
{B4C067C1-F934-493C-9DBC-19E8CA305613}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{B4C067C1-F934-493C-9DBC-19E8CA305613}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{B4C067C1-F934-493C-9DBC-19E8CA305613}.Release|x86.ActiveCfg = Release|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Debug|x86.ActiveCfg = Debug|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Release|Any CPU.Build.0 = Release|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{01A9DA71-5C42-4ED5-AD0C-D6FAF11C0A74} = {0F647068-6602-4E24-B1DC-8ED91481A50A}
{1729302E-A58E-4652-B639-5B6B68DA2748} = {0F647068-6602-4E24-B1DC-8ED91481A50A}
{AD42BAFB-1993-4FAF-A280-3711A9F33E2F} = {0F647068-6602-4E24-B1DC-8ED91481A50A}
{7B4CFF5A-1948-45EC-B170-6EB7C039B2F9} = {0F647068-6602-4E24-B1DC-8ED91481A50A}
@ -126,5 +125,6 @@ Global
{823453CC-5846-4D49-B343-15BC0074CA60} = {52D59F18-62D2-4D17-8CF2-BE192445AF8E}
{65161409-C4C4-4D63-A73B-231FCFF4D503} = {52D59F18-62D2-4D17-8CF2-BE192445AF8E}
{B4C067C1-F934-493C-9DBC-19E8CA305613} = {52D59F18-62D2-4D17-8CF2-BE192445AF8E}
{813B36FE-BBA5-4449-B157-6EBBA5ED02CA} = {52D59F18-62D2-4D17-8CF2-BE192445AF8E}
EndGlobalSection
EndGlobal

View File

@ -1,14 +1,13 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Security;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity.Security
namespace Microsoft.AspNet.Identity.Authentication
{
public class HttpAuthenticationManager : IAuthenticationManager
{

View File

@ -1,10 +1,10 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Identity.Security;
using Microsoft.Framework.DependencyInjection;
using Microsoft.AspNet.Identity.Authentication;
using Microsoft.AspNet.Identity;
namespace Microsoft.AspNet.Identity
namespace Microsoft.Framework.DependencyInjection
{
public static class IdentityBuilderExtensions
{

View File

@ -1,31 +1,20 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Identity.Entity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Framework.DependencyInjection;
// Move to DI namespace?
namespace Microsoft.AspNet.Identity
namespace Microsoft.Framework.DependencyInjection
{
public static class EntityIdentityBuilderExtensions
{
public static IdentityBuilder<TUser, TRole> AddEntityFrameworkInMemory<TUser, TRole, TDbContext>(this IdentityBuilder<TUser, TRole> builder)
where TUser : EntityUser
where TRole : EntityRole
where TDbContext : DbContext
{
builder.Services.AddScoped<TDbContext>();
builder.Services.AddScoped<IUserStore<TUser>, InMemoryUserStore<TUser, TDbContext>>();
builder.Services.AddScoped<IRoleStore<TRole>, EntityRoleStore<TRole, TDbContext>>();
return builder;
}
// todo: add overloads
public static IdentityBuilder<TUser, IdentityRole> AddEntityFramework<TUser, TContext>(this IdentityBuilder<TUser, IdentityRole> builder)
where TUser : User where TContext : DbContext
{
builder.Services.AddScoped<IUserStore<TUser>, UserStore<TUser, TContext>>();
builder.Services.AddScoped<IUserStore<TUser>, UserStore<TUser, IdentityRole, TContext>>();
builder.Services.AddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole, TContext>>();
builder.Services.AddScoped<TContext>();
return builder;
}

View File

@ -1,66 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Identity.Entity
{
/// <summary>
/// Represents a Role entity
/// </summary>
public class EntityRole : EntityRole<string, IdentityUserRole>
{
/// <summary>
/// Constructor
/// </summary>
public EntityRole()
{
Id = Guid.NewGuid().ToString();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="roleName"></param>
public EntityRole(string roleName)
: this()
{
Name = roleName;
}
}
/// <summary>
/// Represents a Role entity
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TUserRole"></typeparam>
public class EntityRole<TKey, TUserRole>
where TUserRole : IdentityUserRole<TKey>
where TKey : IEquatable<TKey>
{
/// <summary>
/// Constructor
/// </summary>
public EntityRole()
{
Users = new List<TUserRole>();
}
/// <summary>
/// Navigation property for users in the role
/// </summary>
public virtual ICollection<TUserRole> Users { get; private set; }
/// <summary>
/// Role id
/// </summary>
public virtual TKey Id { get; set; }
/// <summary>
/// Role name
/// </summary>
public virtual string Name { get; set; }
}
}

View File

@ -1,189 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace Microsoft.AspNet.Identity.Entity
{
public class EntityRoleStore<TRole> : EntityRoleStore<TRole, IdentityContext>
where TRole : EntityRole
{
public EntityRoleStore(IdentityContext context) : base(context) { }
}
public class EntityRoleStore<TRole, TContext> : EntityRoleStore<TRole, string, TContext>
where TRole : EntityRole
where TContext : DbContext
{
public EntityRoleStore(TContext context) : base(context) { }
}
public class EntityRoleStore<TRole, TKey, TContext> :
IQueryableRoleStore<TRole>
where TRole : EntityRole
where TKey : IEquatable<TKey>
where TContext : DbContext
{
private bool _disposed;
public EntityRoleStore(TContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
AutoSaveChanges = true;
}
public DbContext Context { get; private set; }
/// <summary>
/// If true will call SaveChanges after CreateAsync/UpdateAsync/DeleteAsync
/// </summary>
public bool AutoSaveChanges { get; set; }
private async Task SaveChanges(CancellationToken cancellationToken)
{
if (AutoSaveChanges)
{
await Context.SaveChangesAsync(cancellationToken);
}
}
public virtual Task<TRole> GetRoleAggregate(Expression<Func<TRole, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
// TODO: return Roles.SingleOrDefaultAsync(filter, cancellationToken);
return Task.FromResult(Roles.SingleOrDefault(filter));
}
public async virtual Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
await Context.AddAsync(role, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
await Context.UpdateAsync(role, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
Context.Delete(role);
await SaveChanges(cancellationToken);
}
public Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
return Task.FromResult(role.Id);
}
public Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
return Task.FromResult(role.Name);
}
public Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
role.Name = roleName;
return Task.FromResult(0);
}
public virtual TKey ConvertId(string userId)
{
return (TKey)Convert.ChangeType(userId, typeof(TKey));
}
/// <summary>
/// Find a role by id
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TRole> FindByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var roleId = ConvertId(id);
return GetRoleAggregate(u => u.Id.Equals(roleId), cancellationToken);
}
/// <summary>
/// Find a role by name
/// </summary>
/// <param name="name"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TRole> FindByNameAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetRoleAggregate(u => u.Name.ToUpper() == name.ToUpper(), cancellationToken);
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Dispose the store
/// </summary>
public void Dispose()
{
_disposed = true;
}
public IQueryable<TRole> Roles
{
get { return Context.Set<TRole>(); }
}
}
}

View File

@ -1,86 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.SqlServer;
using Microsoft.Data.Entity.InMemory;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
namespace Microsoft.AspNet.Identity.Entity
{
public class IdentityContext :
IdentityContext<EntityUser, EntityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public IdentityContext() { }
public IdentityContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
}
public class IdentityContext<TUser> :
IdentityContext<TUser, EntityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
where TUser : EntityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public IdentityContext() { }
public IdentityContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
}
public class IdentityContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim> : DbContext
where TUser : EntityUser<TKey, TUserLogin, TUserRole, TUserClaim>
where TRole : EntityRole<TKey, TUserRole>
where TUserLogin : IdentityUserLogin<TKey>
where TUserRole : IdentityUserRole<TKey>
where TUserClaim : IdentityUserClaim<TKey>
where TKey : IEquatable<TKey>
{
public DbSet<TUser> Users { get; set; }
public DbSet<TRole> Roles { get; set; }
public IdentityContext(IServiceProvider serviceProvider)
: base(serviceProvider) { }
public IdentityContext() { }
protected override void OnConfiguring(DbContextOptions builder)
{
//#if NET45
// builder.SqlServerConnectionString(@"Server=(localdb)\v11.0;Database=IdentityEF5-5-1;Trusted_Connection=True;");
//#else
builder.UseInMemoryStore();
//#endif
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>()
.Key(u => u.Id)
.Properties(ps => ps.Property(u => u.UserName));
//.ToTable("AspNetUsers");
builder.Entity<TRole>()
.Key(r => r.Id);
//.ToTable("AspNetRoles");
builder.Entity<TUserRole>()
.Key(u => u.Id)
//TODO: .Key(r => new { r.UserId, r.RoleId })
.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ForeignKeys(fk => fk.ForeignKey<TRole>(f => f.RoleId));
//.ToTable("AspNetUserRoles");
builder.Entity<TUserLogin>()
.Key(u => u.Id)
//TODO: .Key(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId));
//.ToTable("AspNetUserLogins");
builder.Entity<TUserClaim>()
.Key(c => c.Id)
.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId));
//.ToTable("AspNetUserClaims");
}
}
}

View File

@ -0,0 +1,106 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.AspNet.Identity.EntityFramework
{
public class IdentityDbContext :
IdentityDbContext<User, IdentityRole>
{
public IdentityDbContext() { }
public IdentityDbContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentityDbContext(IServiceProvider serviceProvider, string nameOrConnectionString) : base(serviceProvider, nameOrConnectionString) { }
public IdentityDbContext(DbContextOptions options) : base(options) { }
public IdentityDbContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
}
public class IdentityDbContext<TUser> :
IdentityDbContext<TUser, IdentityRole>
where TUser : User
{
public IdentityDbContext() { }
public IdentityDbContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentityDbContext(IServiceProvider serviceProvider, string nameOrConnectionString) : base(serviceProvider, nameOrConnectionString) { }
public IdentityDbContext(DbContextOptions options) : base(options) { }
public IdentityDbContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
}
public class IdentityDbContext<TUser, TRole> : DbContext
where TUser : User
where TRole : IdentityRole
{
public DbSet<TUser> Users { get; set; }
public DbSet<IdentityUserClaim> UserClaims { get; set; }
public DbSet<IdentityUserLogin> UserLogins { get; set; }
public DbSet<IdentityUserRole> UserRoles { get; set; }
public DbSet<TRole> Roles { get; set; }
public DbSet<IdentityRoleClaim> RoleClaims { get; set; }
private readonly string _nameOrConnectionString;
public IdentityDbContext() { }
public IdentityDbContext(IServiceProvider serviceProvider, string nameOrConnectionString) : base(serviceProvider)
{
_nameOrConnectionString = nameOrConnectionString;
}
public IdentityDbContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentityDbContext(DbContextOptions options) : base(options) { }
public IdentityDbContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
protected override void OnConfiguring(DbContextOptions builder)
{
if (!string.IsNullOrEmpty(_nameOrConnectionString))
{
builder.UseSqlServer(_nameOrConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>()
.Key(u => u.Id)
.Properties(ps => ps.Property(u => u.UserName))
.ToTable("AspNetUsers");
builder.Entity<TRole>()
.Key(r => r.Id)
.Properties(ps => ps.Property(r => r.Name))
.ToTable("AspNetRoles");
builder.Entity<IdentityUserClaim>()
.Key(uc => uc.Id)
.ToTable("AspNetUserClaims");
var userType = builder.Model.GetEntityType(typeof(TUser));
var roleType = builder.Model.GetEntityType(typeof(TRole));
var userClaimType = builder.Model.GetEntityType(typeof(IdentityUserClaim));
var roleClaimType = builder.Model.GetEntityType(typeof(IdentityRoleClaim));
var userRoleType = builder.Model.GetEntityType(typeof(IdentityUserRole));
var ucfk = userClaimType.AddForeignKey(userType.GetKey(), new[] { userClaimType.GetProperty("UserId") });
userType.AddNavigation(new Navigation(ucfk, "Claims", false));
//userClaimType.AddNavigation(new Navigation(ucfk, "User", true));
//var urfk = userRoleType.AddForeignKey(userType.GetKey(), new[] { userRoleType.GetProperty("UserId") });
//userType.AddNavigation(new Navigation(urfk, "Roles", false));
//var urfk2 = userRoleType.AddForeignKey(roleType.GetKey(), new[] { userRoleType.GetProperty("RoleId") });
//roleType.AddNavigation(new Navigation(urfk2, "Users", false));
var rcfk = roleClaimType.AddForeignKey(roleType.GetKey(), new[] { roleClaimType.GetProperty("RoleId") });
roleType.AddNavigation(new Navigation(rcfk, "Claims", false));
builder.Entity<IdentityUserRole>()
.Key(r => new { r.UserId, r.RoleId })
//.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
//.ForeignKeys(fk => fk.ForeignKey<TRole>(f => f.RoleId));
.ToTable("AspNetUserRoles");
builder.Entity<IdentityUserLogin>()
.Key(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
//.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId));
.ToTable("AspNetUserLogins");
}
}
}

View File

@ -1,60 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.AspNet.Identity.Entity
{
public class IdentitySqlContext :
IdentitySqlContext<User>
{
public IdentitySqlContext() { }
public IdentitySqlContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentitySqlContext(IServiceProvider serviceProvider, string nameOrConnectionString) : base(serviceProvider, nameOrConnectionString) { }
public IdentitySqlContext(DbContextOptions options) : base(options) { }
public IdentitySqlContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
}
public class IdentitySqlContext<TUser> : DbContext
where TUser : User
{
public DbSet<TUser> Users { get; set; }
public DbSet<IdentityUserClaim> UserClaims { get; set; }
//public DbSet<TRole> Roles { get; set; }
private readonly string _nameOrConnectionString;
public IdentitySqlContext() { }
public IdentitySqlContext(IServiceProvider serviceProvider, string nameOrConnectionString) : base(serviceProvider)
{
_nameOrConnectionString = nameOrConnectionString;
}
public IdentitySqlContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentitySqlContext(DbContextOptions options) : base(options) { }
public IdentitySqlContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
protected override void OnConfiguring(DbContextOptions builder)
{
if (!string.IsNullOrEmpty(_nameOrConnectionString))
{
builder.UseSqlServer(_nameOrConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>()
.Key(u => u.Id)
.Properties(ps => ps.Property(u => u.UserName))
.ToTable("AspNetUsers");
builder.Entity<IdentityUserClaim>()
.Key(uc => uc.Id)
// TODO: this throws a length exception currently, investigate
//.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ToTable("AspNetUserClaims");
}
}
}

View File

@ -18,18 +18,15 @@
</PropertyGroup>
<ItemGroup>
<Content Include="project.json" />
<Content Include="Resources.resx" />
</ItemGroup>
<ItemGroup>
<Compile Include="EntityRole.cs" />
<Compile Include="EntityRoleStore.cs" />
<Compile Include="EntityUser.cs" />
<Compile Include="EntityIdentityBuilderExtensions.cs" />
<Compile Include="IdentityContext.cs" />
<Compile Include="IdentitySqlContext.cs" />
<Compile Include="InMemoryUserStore.cs" />
<Compile Include="IdentityDbContext.cs" />
<Compile Include="Properties\Resources.Designer.cs" />
<Compile Include="RoleStore.cs" />
<Compile Include="SqlUserStore.cs" />
<Compile Include="User.cs" />
<Compile Include="UserStore.cs" />
</ItemGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -0,0 +1,62 @@
// <auto-generated />
namespace Microsoft.AspNet.Identity.EntityFramework
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNet.Identity.EntityFramework.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// Role {0} does not exist.
/// </summary>
internal static string RoleNotFound
{
get { return GetString("RoleNotFound"); }
}
/// <summary>
/// Role {0} does not exist.
/// </summary>
internal static string FormatRoleNotFound(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("RoleNotFound"), p0);
}
/// <summary>
/// Value cannot be null or empty.
/// </summary>
internal static string ValueCannotBeNullOrEmpty
{
get { return GetString("ValueCannotBeNullOrEmpty"); }
}
/// <summary>
/// Value cannot be null or empty.
/// </summary>
internal static string FormatValueCannotBeNullOrEmpty()
{
return GetString("ValueCannotBeNullOrEmpty");
}
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="RoleNotFound" xml:space="preserve">
<value>Role {0} does not exist.</value>
<comment>error when a role does not exist</comment>
</data>
<data name="ValueCannotBeNullOrEmpty" xml:space="preserve">
<value>Value cannot be null or empty.</value>
<comment>error when something cannot be null or empty</comment>
</data>
</root>

View File

@ -2,27 +2,38 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace Microsoft.AspNet.Identity.Entity
namespace Microsoft.AspNet.Identity.EntityFramework
{
public class RoleStore<TRole> : RoleStore<TRole, string> where TRole : EntityRole
public class RoleStore<TRole> : RoleStore<TRole, string, DbContext> where TRole : IdentityRole
{
public RoleStore(DbContext context) : base(context) { }
}
public class RoleStore<TRole, TKey> :
IQueryableRoleStore<TRole>
where TRole : EntityRole
public class RoleStore<TRole, TContext> : RoleStore<TRole, string, TContext>
where TRole : IdentityRole
where TContext : DbContext
{
public RoleStore(TContext context) : base(context) { }
}
public class RoleStore<TRole, TKey, TContext> :
IQueryableRoleStore<TRole>,
IRoleClaimStore<TRole>
where TRole : IdentityRole
where TKey : IEquatable<TKey>
where TContext : DbContext
{
private bool _disposed;
public RoleStore(DbContext context)
public RoleStore(TContext context)
{
if (context == null)
{
@ -32,7 +43,7 @@ namespace Microsoft.AspNet.Identity.Entity
AutoSaveChanges = true;
}
public DbContext Context { get; private set; }
public TContext Context { get; private set; }
/// <summary>
/// If true will call SaveChanges after CreateAsync/UpdateAsync/DeleteAsync
@ -49,8 +60,7 @@ namespace Microsoft.AspNet.Identity.Entity
public virtual Task<TRole> GetRoleAggregate(Expression<Func<TRole, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
// TODO: return Roles.SingleOrDefaultAsync(filter, cancellationToken);
return Task.FromResult(Roles.SingleOrDefault(filter));
return Task.FromResult(Roles.FirstOrDefault(filter));
}
public async virtual Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
@ -123,7 +133,6 @@ namespace Microsoft.AspNet.Identity.Entity
return Task.FromResult(0);
}
public virtual TKey ConvertId(string userId)
{
return (TKey)Convert.ChangeType(userId, typeof(TKey));
@ -172,9 +181,56 @@ namespace Microsoft.AspNet.Identity.Entity
_disposed = true;
}
public Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
IList<Claim> result = RoleClaims.Where(rc => rc.RoleId == role.Id).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult(result);
}
public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
RoleClaims.Add(new IdentityRoleClaim { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value });
return Task.FromResult(0);
}
public Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
{
throw new ArgumentNullException("role");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
var claims = RoleClaims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToList();
foreach (var c in claims)
{
RoleClaims.Remove(c);
}
return Task.FromResult(0);
}
public IQueryable<TRole> Roles
{
get { return Context.Set<TRole>(); }
}
private DbSet<IdentityRoleClaim> RoleClaims { get { return Context.Set<IdentityRoleClaim>(); } }
}
}

View File

@ -1,384 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace Microsoft.AspNet.Identity.Entity
{
public class UserStore<TUser> : UserStore<TUser, DbContext> where TUser : User
{
public UserStore(DbContext context) : base(context) { }
}
public class UserStore<TUser, TContext> :
//IUserRoleStore<TUser>,
IUserPasswordStore<TUser>,
IQueryableUserStore<TUser>,
IUserClaimStore<TUser>
where TUser : User
where TContext : DbContext
{
private bool _disposed;
public UserStore(TContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
AutoSaveChanges = true;
}
public TContext Context { get; private set; }
/// <summary>
/// If true will call SaveChanges after CreateAsync/UpdateAsync/DeleteAsync
/// </summary>
public bool AutoSaveChanges { get; set; }
private Task SaveChanges(CancellationToken cancellationToken)
{
return AutoSaveChanges ? Context.SaveChangesAsync(cancellationToken) : Task.FromResult(0);
}
protected virtual Task<TUser> GetUserAggregate(Expression<Func<TUser, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(Users.SingleOrDefault(filter));
// TODO: return Users.SingleOrDefaultAsync(filter, cancellationToken);
//Include(u => u.Roles)
//.Include(u => u.Claims)
//.Include(u => u.Logins)
}
public Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(Convert.ToString(user.Id, CultureInfo.InvariantCulture));
}
public Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.UserName);
}
public Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.UserName = userName;
return Task.FromResult(0);
}
public async virtual Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await Context.AddAsync(user, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await Context.UpdateAsync(user, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
Context.Delete(user);
await SaveChanges(cancellationToken);
}
/// <summary>
/// Find a user by id
/// </summary>
/// <param name="userId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.Id.Equals(userId), cancellationToken);
}
/// <summary>
/// Find a user by name
/// </summary>
/// <param name="userName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.UserName.ToUpper() == userName.ToUpper(), cancellationToken);
}
public IQueryable<TUser> Users
{
get { return Context.Set<TUser>(); }
}
/// <summary>
/// Set the password hash for a user
/// </summary>
/// <param name="user"></param>
/// <param name="passwordHash"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
/// <summary>
/// Get the password hash for a user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PasswordHash);
}
/// <summary>
/// Returns true if the user has a password set
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(user.PasswordHash != null);
}
///// <summary>
///// Add a user to a role
///// </summary>
///// <param name="user"></param>
///// <param name="roleName"></param>
///// <param name="cancellationToken"></param>
///// <returns></returns>
//public virtual Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
//{
// cancellationToken.ThrowIfCancellationRequested();
// ThrowIfDisposed();
// if (user == null)
// {
// throw new ArgumentNullException("user");
// }
// // TODO:
// //if (String.IsNullOrWhiteSpace(roleName))
// //{
// // throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
// //}
// var roleEntity = Context.Set<TRole>().SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
// if (roleEntity == null)
// {
// throw new InvalidOperationException("Role Not Found");
// //TODO: String.Format(CultureInfo.CurrentCulture, IdentityResources.RoleNotFound, roleName));
// }
// var ur = new TUserRole { UserId = user.Id, RoleId = roleEntity.Id };
// user.Roles.Add(ur);
// roleEntity.Users.Add(ur);
// return Task.FromResult(0);
//}
///// <summary>
///// Remove a user from a role
///// </summary>
///// <param name="user"></param>
///// <param name="roleName"></param>
///// <param name="cancellationToken"></param>
///// <returns></returns>
//public virtual Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
//{
// cancellationToken.ThrowIfCancellationRequested();
// ThrowIfDisposed();
// if (user == null)
// {
// throw new ArgumentNullException("user");
// }
// //if (String.IsNullOrWhiteSpace(roleName))
// //{
// // throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
// //}
// var roleEntity = Context.Set<TRole>().SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
// if (roleEntity != null)
// {
// var userRole = user.Roles.FirstOrDefault(r => roleEntity.Id.Equals(r.RoleId));
// if (userRole != null)
// {
// user.Roles.Remove(userRole);
// roleEntity.Users.Remove(userRole);
// }
// }
// return Task.FromResult(0);
//}
///// <summary>
///// Get the names of the roles a user is a member of
///// </summary>
///// <param name="user"></param>
///// <param name="cancellationToken"></param>
///// <returns></returns>
//public virtual Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
//{
// cancellationToken.ThrowIfCancellationRequested();
// ThrowIfDisposed();
// if (user == null)
// {
// throw new ArgumentNullException("user");
// }
// var query = from userRoles in user.Roles
// join roles in Context.Set<TRole>()
// on userRoles.RoleId equals roles.Id
// select roles.Name;
// return Task.FromResult<IList<string>>(query.ToList());
//}
///// <summary>
///// Returns true if the user is in the named role
///// </summary>
///// <param name="user"></param>
///// <param name="roleName"></param>
///// <param name="cancellationToken"></param>
///// <returns></returns>
//public virtual Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
//{
// cancellationToken.ThrowIfCancellationRequested();
// ThrowIfDisposed();
// if (user == null)
// {
// throw new ArgumentNullException("user");
// }
// //if (String.IsNullOrWhiteSpace(roleName))
// //{
// // throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
// //}
// var any =
// Context.Set<TRole>().Where(r => r.Name.ToUpper() == roleName.ToUpper())
// .Where(r => r.Users.Any(ur => ur.UserId.Equals(user.Id)))
// .Count() > 0;
// return Task.FromResult(any);
//}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Dispose the store
/// </summary>
public void Dispose()
{
_disposed = true;
}
private DbSet<IdentityUserClaim> UserClaims { get { return Context.Set<IdentityUserClaim>(); } }
public Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IList<Claim> result = UserClaims.Where(uc => uc.UserId == user.Id).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult(result);
}
public Task AddClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = new CancellationToken())
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
UserClaims.Add(new IdentityUserClaim { UserId = user.Id, ClaimType = claim.Type, ClaimValue = claim.Value });
return Task.FromResult(0);
}
public Task RemoveClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = new CancellationToken())
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
var claims = UserClaims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToList();
foreach (var c in claims)
{
UserClaims.Remove(c);
}
return Task.FromResult(0);
}
}
}

View File

@ -2,14 +2,18 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Identity.Entity
namespace Microsoft.AspNet.Identity.EntityFramework
{
public class User
{
public User()
{
Id = Guid.NewGuid().ToString();
Claims = new List<IdentityUserClaim>();
Roles = new List<IdentityUserRole>();
Logins = new List<IdentityUserLogin>();
}
public User(string userName) : this()
@ -20,10 +24,71 @@ namespace Microsoft.AspNet.Identity.Entity
public virtual string Id { get; set; }
public virtual string UserName { get; set; }
/// <summary>
/// Email
/// </summary>
public virtual string Email { get; set; }
/// <summary>
/// True if the email is confirmed, default is false
/// </summary>
public virtual bool EmailConfirmed { get; set; }
/// <summary>
/// The salted/hashed form of the user password
/// </summary>
public virtual string PasswordHash { get; set; }
/// <summary>
/// A random value that should change whenever a users credentials have changed (password changed, login removed)
/// </summary>
public virtual string SecurityStamp { get; set; }
/// <summary>
/// PhoneNumber for the user
/// </summary>
public virtual string PhoneNumber { get; set; }
/// <summary>
/// True if the phone number is confirmed, default is false
/// </summary>
public virtual bool PhoneNumberConfirmed { get; set; }
/// <summary>
/// Is two factor enabled for the user
/// </summary>
public virtual bool TwoFactorEnabled { get; set; }
/// <summary>
/// DateTime in UTC when lockout ends, any time in the past is considered not locked out.
/// </summary>
public virtual DateTime? LockoutEnd { get; set; }
/// <summary>
/// Is lockout enabled for this user
/// </summary>
public virtual bool LockoutEnabled { get; set; }
/// <summary>
/// Used to record failures for the purposes of lockout
/// </summary>
public virtual int AccessFailedCount { get; set; }
/// <summary>
/// Roles for the user
/// </summary>
public virtual ICollection<IdentityUserRole> Roles { get; private set; }
/// <summary>
/// Claims for the user
/// </summary>
public virtual ICollection<IdentityUserClaim> Claims { get; private set; }
/// <summary>
/// Associated logins for the user
/// </summary>
public virtual ICollection<IdentityUserLogin> Logins { get; private set; }
}
}

View File

@ -0,0 +1,852 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace Microsoft.AspNet.Identity.EntityFramework
{
public class UserStore : UserStore<User>
{
public UserStore(DbContext context) : base(context) { }
}
public class UserStore<TUser> : UserStore<TUser, IdentityRole, DbContext> where TUser : User
{
public UserStore(DbContext context) : base(context) { }
}
public class UserStore<TUser, TRole, TContext> :
IUserLoginStore<TUser>,
IUserRoleStore<TUser>,
IUserClaimStore<TUser>,
IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserEmailStore<TUser>,
IUserLockoutStore<TUser>,
IUserPhoneNumberStore<TUser>,
IQueryableUserStore<TUser>,
IUserTwoFactorStore<TUser>
where TUser : User
where TRole : IdentityRole
where TContext : DbContext
{
private bool _disposed;
public UserStore(TContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
AutoSaveChanges = true;
}
public TContext Context { get; private set; }
/// <summary>
/// If true will call SaveChanges after CreateAsync/UpdateAsync/DeleteAsync
/// </summary>
public bool AutoSaveChanges { get; set; }
private Task SaveChanges(CancellationToken cancellationToken)
{
return AutoSaveChanges ? Context.SaveChangesAsync(cancellationToken) : Task.FromResult(0);
}
protected virtual Task<TUser> GetUserAggregate(Expression<Func<TUser, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(Users.FirstOrDefault(filter));
// TODO: return Users.FirstOrDefaultAsync(filter, cancellationToken);
//Include(u => u.Roles)
//.Include(u => u.Claims)
//.Include(u => u.Logins)
}
public Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(Convert.ToString(user.Id, CultureInfo.InvariantCulture));
}
public Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.UserName);
}
public Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.UserName = userName;
return Task.FromResult(0);
}
public async virtual Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await Context.AddAsync(user, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await Context.UpdateAsync(user, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
Context.Delete(user);
await SaveChanges(cancellationToken);
}
/// <summary>
/// Find a user by id
/// </summary>
/// <param name="userId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.Id.Equals(userId), cancellationToken);
}
/// <summary>
/// Find a user by name
/// </summary>
/// <param name="userName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.UserName.ToUpper() == userName.ToUpper(), cancellationToken);
}
public IQueryable<TUser> Users
{
get { return Context.Set<TUser>(); }
}
/// <summary>
/// Set the password hash for a user
/// </summary>
/// <param name="user"></param>
/// <param name="passwordHash"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
/// <summary>
/// Get the password hash for a user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PasswordHash);
}
/// <summary>
/// Returns true if the user has a password set
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(user.PasswordHash != null);
}
/// <summary>
/// Add a user to a role
/// </summary>
/// <param name="user"></param>
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (String.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, "roleName");
}
var roleEntity = Roles.SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
if (roleEntity == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.RoleNotFound, roleName));
}
var ur = new IdentityUserRole { UserId = user.Id, RoleId = roleEntity.Id };
// TODO: rely on fixup?
UserRoles.Add(ur);
user.Roles.Add(ur);
roleEntity.Users.Add(ur);
return Task.FromResult(0);
}
/// <summary>
/// Remove a user from a role
/// </summary>
/// <param name="user"></param>
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (String.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, "roleName");
}
var roleEntity = Roles.SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
if (roleEntity != null)
{
var userRole = UserRoles.FirstOrDefault(r => roleEntity.Id.Equals(r.RoleId) && r.UserId == user.Id);
if (userRole != null)
{
UserRoles.Remove(userRole);
user.Roles.Remove(userRole);
}
}
return Task.FromResult(0);
}
/// <summary>
/// Get the names of the roles a user is a member of
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var userId = user.Id;
// TODO: var query = from userRole in UserRoles
var query = from userRole in user.Roles
join role in Roles on userRole.RoleId equals role.Id
select role.Name;
//return await query.ToListAsync();
return query.ToList();
}
/// <summary>
/// Returns true if the user is in the named role
/// </summary>
/// <param name="user"></param>
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (String.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, "roleName");
}
//var role = await Roles.SingleOrDefaultAsync(r => r.Name.ToUpper() == roleName.ToUpper());
var role = Roles.SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
if (role != null)
{
var userId = user.Id;
var roleId = role.Id;
return user.Roles.Any(ur => ur.RoleId.Equals(roleId));
//return await UserRoles.AnyAsync(ur => ur.RoleId.Equals(roleId) && ur.UserId.Equals(userId));
//return UserRoles.Any(ur => ur.RoleId.Equals(roleId) && ur.UserId.Equals(userId));
}
return false;
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Dispose the store
/// </summary>
public void Dispose()
{
_disposed = true;
}
private DbSet<TRole> Roles { get { return Context.Set<TRole>(); } }
private DbSet<IdentityUserClaim> UserClaims { get { return Context.Set<IdentityUserClaim>(); } }
private DbSet<IdentityUserRole> UserRoles { get { return Context.Set<IdentityUserRole>(); } }
private DbSet<IdentityUserLogin> UserLogins { get { return Context.Set<IdentityUserLogin>(); } }
public Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IList<Claim> result = UserClaims.Where(uc => uc.UserId == user.Id).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult(result);
}
public Task AddClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = new CancellationToken())
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
UserClaims.Add(new IdentityUserClaim { UserId = user.Id, ClaimType = claim.Type, ClaimValue = claim.Value });
return Task.FromResult(0);
}
public Task RemoveClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = new CancellationToken())
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
var claims = UserClaims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToList();
foreach (var c in claims)
{
UserClaims.Remove(c);
}
return Task.FromResult(0);
}
public async virtual Task AddLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
var l = new IdentityUserLogin
{
UserId = user.Id,
ProviderKey = login.ProviderKey,
LoginProvider = login.LoginProvider
};
// TODO: fixup so we don't have to update both
UserLogins.Add(l);
user.Logins.Add(l);
}
public virtual Task RemoveLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
var provider = login.LoginProvider;
var key = login.ProviderKey;
var userId = user.Id;
// todo: ensure logins loaded
var entry = UserLogins.SingleOrDefault(l => l.UserId == userId && l.LoginProvider == provider && l.ProviderKey == key);
if (entry != null)
{
UserLogins.Remove(entry);
user.Logins.Remove(entry);
}
return Task.FromResult(0);
}
public virtual Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
// todo: ensure logins loaded
IList<UserLoginInfo> result =
user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey)).ToList();
return Task.FromResult(result);
}
public async virtual Task<TUser> FindByLoginAsync(UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (login == null)
{
throw new ArgumentNullException("login");
}
// todo: ensure logins loaded
var provider = login.LoginProvider;
var key = login.ProviderKey;
// TODO: use FirstOrDefaultAsync
var userLogin =
UserLogins.FirstOrDefault(l => l.LoginProvider == provider && l.ProviderKey == key);
if (userLogin != null)
{
return await GetUserAggregate(u => u.Id.Equals(userLogin.UserId), cancellationToken);
}
return null;
}
/// <summary>
/// Returns whether the user email is confirmed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetEmailConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.EmailConfirmed);
}
/// <summary>
/// Set IsConfirmed on the user
/// </summary>
/// <param name="user"></param>
/// <param name="confirmed"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
/// <summary>
/// Set the user email
/// </summary>
/// <param name="user"></param>
/// <param name="email"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetEmailAsync(TUser user, string email, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.Email = email;
return Task.FromResult(0);
}
/// <summary>
/// Get the user's email
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetEmailAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.Email);
}
/// <summary>
/// Find an user by email
/// </summary>
/// <param name="email"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByEmailAsync(string email, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.Email == email, cancellationToken);
// todo: ToUpper blows up with Null Ref
//return GetUserAggregate(u => u.Email.ToUpper() == email.ToUpper(), cancellationToken);
}
/// <summary>
/// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be considered
/// not locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return
Task.FromResult(user.LockoutEnd.HasValue
? new DateTimeOffset(DateTime.SpecifyKind(user.LockoutEnd.Value, DateTimeKind.Utc))
: new DateTimeOffset());
}
/// <summary>
/// Locks a user out until the specified end date (set to a past date, to unlock a user)
/// </summary>
/// <param name="user"></param>
/// <param name="lockoutEnd"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnd = lockoutEnd == DateTimeOffset.MinValue ? (DateTime?)null : lockoutEnd.UtcDateTime;
return Task.FromResult(0);
}
/// <summary>
/// Used to record when an attempt to access the user has failed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Used to reset the account access count, typically after the account is successfully accessed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
/// <summary>
/// Returns the current number of failed access attempts. This number usually will be reset whenever the password is
/// verified or the account is locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Returns whether the user can be locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.LockoutEnabled);
}
/// <summary>
/// Sets whether the user can be locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
/// <summary>
/// Set the user's phone number
/// </summary>
/// <param name="user"></param>
/// <param name="phoneNumber"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumber = phoneNumber;
return Task.FromResult(0);
}
/// <summary>
/// Get a user's phone number
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PhoneNumber);
}
/// <summary>
/// Returns whether the user phoneNumber is confirmed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PhoneNumberConfirmed);
}
/// <summary>
/// Set PhoneNumberConfirmed on the user
/// </summary>
/// <param name="user"></param>
/// <param name="confirmed"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumberConfirmed = confirmed;
return Task.FromResult(0);
}
/// <summary>
/// Set the security stamp for the user
/// </summary>
/// <param name="user"></param>
/// <param name="stamp"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetSecurityStampAsync(TUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
/// <summary>
/// Get the security stamp for a user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.SecurityStamp);
}
/// <summary>
/// Set whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"></param>
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.TwoFactorEnabled = enabled;
return Task.FromResult(0);
}
/// <summary>
/// Gets whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.TwoFactorEnabled);
}
}
}

View File

@ -2,7 +2,6 @@
"version": "3.0.0-*",
"dependencies": {
"Microsoft.AspNet.Identity": "",
"EntityFramework.InMemory": "7.0.0-*",
"EntityFramework.SqlServer": "7.0.0-*",
"System.Security.Claims" : "1.0.0-*"
},

View File

@ -1,22 +0,0 @@
{
"version": "3.0.0-*",
"dependencies": {
"Microsoft.AspNet.Identity": "",
"Microsoft.Framework.DependencyInjection" : "1.0.0-*",
"System.Security.Claims": "1.0.0-*"
},
"configurations": {
"net45": {},
"k10": {
"dependencies": {
"System.Collections": "4.0.0.0",
"System.Linq": "4.0.0.0",
"System.Linq.Expressions": "4.0.0.0",
"System.Linq.Queryable": "4.0.0.0",
"System.Reflection": "4.0.10.0",
"System.Runtime": "4.0.20.0",
"System.Threading.Tasks": "4.0.10.0"
}
}
}
}

View File

@ -1,10 +1,7 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using System.Security.Claims;
using Microsoft.Framework.ConfigurationModel;
namespace Microsoft.AspNet.Identity
{

View File

@ -5,7 +5,6 @@ using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity
{
@ -13,9 +12,27 @@ namespace Microsoft.AspNet.Identity
/// Creates a ClaimsIdentity from a User
/// </summary>
/// <typeparam name="TUser"></typeparam>
public class ClaimsIdentityFactory<TUser> : IClaimsIdentityFactory<TUser>
public class ClaimsIdentityFactory<TUser, TRole> : IClaimsIdentityFactory<TUser>
where TUser : class
where TRole : class
{
public ClaimsIdentityFactory(UserManager<TUser> userManager, RoleManager<TRole> roleManager)
{
if (userManager == null)
{
throw new ArgumentNullException("userManager");
}
if (roleManager == null)
{
throw new ArgumentNullException("roleManager");
}
UserManager = userManager;
RoleManager = roleManager;
}
public UserManager<TUser> UserManager { get; private set; }
public RoleManager<TRole> RoleManager { get; private set; }
/// <summary>
/// CreateAsync a ClaimsIdentity from a user
/// </summary>
@ -24,37 +41,43 @@ namespace Microsoft.AspNet.Identity
/// <param name="authenticationType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<ClaimsIdentity> CreateAsync(UserManager<TUser> manager, TUser user,
public virtual async Task<ClaimsIdentity> CreateAsync(TUser user,
string authenticationType, CancellationToken cancellationToken = default(CancellationToken))
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
if (user == null)
{
throw new ArgumentNullException("user");
}
var userId = await manager.GetUserIdAsync(user, cancellationToken);
var userName = await manager.GetUserNameAsync(user, cancellationToken);
var id = new ClaimsIdentity(authenticationType, manager.Options.ClaimType.UserName, manager.Options.ClaimType.Role);
id.AddClaim(new Claim(manager.Options.ClaimType.UserId, userId));
id.AddClaim(new Claim(manager.Options.ClaimType.UserName, userName, ClaimValueTypes.String));
if (manager.SupportsUserSecurityStamp)
var userId = await UserManager.GetUserIdAsync(user, cancellationToken);
var userName = await UserManager.GetUserNameAsync(user, cancellationToken);
var id = new ClaimsIdentity(authenticationType, UserManager.Options.ClaimType.UserName,
UserManager.Options.ClaimType.Role);
id.AddClaim(new Claim(UserManager.Options.ClaimType.UserId, userId));
id.AddClaim(new Claim(UserManager.Options.ClaimType.UserName, userName, ClaimValueTypes.String));
if (UserManager.SupportsUserSecurityStamp)
{
id.AddClaim(new Claim(manager.Options.ClaimType.SecurityStamp, await manager.GetSecurityStampAsync(user, cancellationToken)));
id.AddClaim(new Claim(UserManager.Options.ClaimType.SecurityStamp,
await UserManager.GetSecurityStampAsync(user, cancellationToken)));
}
if (manager.SupportsUserRole)
if (UserManager.SupportsUserRole)
{
var roles = await manager.GetRolesAsync(user, cancellationToken);
var roles = await UserManager.GetRolesAsync(user, cancellationToken);
foreach (var roleName in roles)
{
id.AddClaim(new Claim(manager.Options.ClaimType.Role, roleName, ClaimValueTypes.String));
id.AddClaim(new Claim(UserManager.Options.ClaimType.Role, roleName, ClaimValueTypes.String));
if (RoleManager.SupportsRoleClaims)
{
var role = await RoleManager.FindByNameAsync(roleName);
if (role != null)
{
id.AddClaims(await RoleManager.GetClaimsAsync(role, cancellationToken));
}
}
}
}
if (manager.SupportsUserClaim)
if (UserManager.SupportsUserClaim)
{
id.AddClaims(await manager.GetClaimsAsync(user, cancellationToken));
id.AddClaims(await UserManager.GetClaimsAsync(user, cancellationToken));
}
return id;
}

View File

@ -10,8 +10,8 @@ namespace Microsoft.AspNet.Identity
internal static class Crypto
{
private const int Pbkdf2IterCount = 1000; // default for Rfc2898DeriveBytes
private const int Pbkdf2SubkeyLength = 256/8; // 256 bits
private const int SaltSize = 128/8; // 128 bits
private const int Pbkdf2SubkeyLength = 256 / 8; // 256 bits
private const int SaltSize = 128 / 8; // 128 bits
/* =======================
* HASHED PASSWORD FORMATS

View File

@ -5,6 +5,6 @@ namespace Microsoft.AspNet.Identity
{
public static class DefaultAuthenticationTypes
{
public static readonly string ApplicationCookie = typeof(DefaultAuthenticationTypes).Namespace+".Application";
public static readonly string ApplicationCookie = typeof(DefaultAuthenticationTypes).Namespace + ".Application";
}
}

View File

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
@ -16,13 +15,13 @@ namespace Microsoft.AspNet.Identity
where TUser : class
{
/// <summary>
/// Create a ClaimsIdentity from an user using a UserManager
/// Create a ClaimsIdentity from an user
/// </summary>
/// <param name="manager"></param>
/// <param name="user"></param>
/// <param name="authenticationType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<ClaimsIdentity> CreateAsync(UserManager<TUser> manager, TUser user, string authenticationType, CancellationToken cancellationToken = default(CancellationToken));
Task<ClaimsIdentity> CreateAsync(TUser user, string authenticationType,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -15,6 +15,7 @@ namespace Microsoft.AspNet.Identity
/// Validate the item
/// </summary>
/// <returns></returns>
Task<IdentityResult> ValidateAsync(string password, UserManager<TUser> manager, CancellationToken cancellationToken = default(CancellationToken));
Task<IdentityResult> ValidateAsync(string password, UserManager<TUser> manager,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -0,0 +1,45 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Stores role specific claims
/// </summary>
/// <typeparam name="TRole"></typeparam>
public interface IRoleClaimStore<TRole> : IRoleStore<TRole> where TRole : class
{
/// <summary>
/// Returns the claims for the role
/// </summary>
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<Claim>> GetClaimsAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add a new role claim
/// </summary>
/// <param name="role"></param>
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Remove a role claim
/// </summary>
/// <param name="role"></param>
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task RemoveClaimAsync(TRole role, Claim claim,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -60,7 +60,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken));
Task SetRoleNameAsync(TRole role, string roleName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds a role by id

View File

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
@ -11,7 +10,6 @@ namespace Microsoft.AspNet.Identity
/// Used to validate a role
/// </summary>
/// <typeparam name="TRole"></typeparam>
/// <typeparam name="TKey"></typeparam>
public interface IRoleValidator<TRole> where TRole : class
{
/// <summary>
@ -21,6 +19,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role, CancellationToken cancellationToken = default(CancellationToken));
Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -15,12 +15,13 @@ namespace Microsoft.AspNet.Identity
public interface IUserClaimStore<TUser> : IUserStore<TUser> where TUser : class
{
/// <summary>
/// Returns the claims for the user with the issuer set
/// Returns the claims for the user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<IList<Claim>> GetClaimsAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add a new user claim
@ -38,6 +39,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task RemoveClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken));
Task RemoveClaimAsync(TUser user, Claim claim,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -35,7 +35,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> GetEmailConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> GetEmailConfirmedAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets whether the user email is confirmed
@ -44,7 +45,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="confirmed"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken));
Task SetEmailConfirmedAsync(TUser user, bool confirmed,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the user associated with this email

View File

@ -8,19 +8,20 @@ using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Stores information which can be used to implement account lockout, including access failures and lockout status
/// Stores information which can be used to implement account lockout, including access failures and lockout status
/// </summary>
/// <typeparam name="TUser"></typeparam>
public interface IUserLockoutStore<TUser> : IUserStore<TUser> where TUser : class
{
/// <summary>
/// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be considered
/// not locked out.
/// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be
/// considered not locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Locks a user out until the specified end date (set to a past date, to unlock a user)
@ -29,7 +30,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="lockoutEnd"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd, CancellationToken cancellationToken = default(CancellationToken));
Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Used to record when an attempt to access the user has failed
@ -37,7 +39,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<int> IncrementAccessFailedCountAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Used to reset the account access count, typically after the account is successfully accessed
@ -48,13 +51,14 @@ namespace Microsoft.AspNet.Identity
Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the current number of failed access attempts. This number usually will be reset whenever the password is
/// verified or the account is locked out.
/// Returns the current number of failed access attempts. This number usually will be reset whenever the
/// password is verified or the account is locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<int> GetAccessFailedCountAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns whether the user can be locked out.
@ -62,7 +66,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> GetLockoutEnabledAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets whether the user can be locked out.
@ -71,6 +76,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken));
Task SetLockoutEnabledAsync(TUser user, bool enabled,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -20,7 +20,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="login"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task AddLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken));
Task AddLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes the user login with the specified combination if it exists, returns true if found and removed
@ -29,7 +30,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="login"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task RemoveLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken));
Task RemoveLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the linked accounts for this user
@ -37,7 +39,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the user associated with this login
@ -45,6 +48,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="login"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<TUser> FindByLoginAsync(UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken));
Task<TUser> FindByLoginAsync(UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -19,7 +19,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="passwordHash"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken));
Task SetPasswordHashAsync(TUser user, string passwordHash,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the user password hash
@ -27,7 +28,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<string> GetPasswordHashAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns true if a user has a password set

View File

@ -19,7 +19,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="phoneNumber"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken));
Task SetPhoneNumberAsync(TUser user, string phoneNumber,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the user phoneNumber
@ -35,7 +36,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> GetPhoneNumberConfirmedAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets whether the user phone number is confirmed
@ -44,6 +46,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="confirmed"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken));
Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -20,7 +20,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken));
Task AddToRoleAsync(TUser user, string roleName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes the role for the user
@ -29,7 +30,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken));
Task RemoveFromRoleAsync(TUser user, string roleName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the roles for this user
@ -37,7 +39,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<IList<string>> GetRolesAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns true if a user is in a role
@ -46,6 +49,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> IsInRoleAsync(TUser user, string roleName,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -19,7 +19,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="stamp"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetSecurityStampAsync(TUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken));
Task SetSecurityStampAsync(TUser user, string stamp,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the user security stamp
@ -27,6 +28,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<string> GetSecurityStampAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -11,7 +11,6 @@ namespace Microsoft.AspNet.Identity
/// Interface that exposes basic user management apis
/// </summary>
/// <typeparam name="TUser"></typeparam>
/// <typeparam name="TKey"></typeparam>
public interface IUserStore<TUser> : IDisposable where TUser : class
{
/// <summary>
@ -37,7 +36,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="userName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken = default(CancellationToken));
Task SetUserNameAsync(TUser user, string userName,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Insert a new user
@ -78,6 +78,5 @@ namespace Microsoft.AspNet.Identity
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<TUser> FindByNameAsync(string name, CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -20,7 +20,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// ValidateAsync and unprotect a token, returns null if invalid
@ -31,7 +32,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Notifies the user that a token has been generated, i.e. via email or sms, or can no-op
@ -41,7 +43,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task NotifyAsync(string token, UserManager<TUser> manager, TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task NotifyAsync(string token, UserManager<TUser> manager, TUser user,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns true if provider can be used for this user, i.e. could require a user to have an email
@ -50,6 +53,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsValidProviderForUserAsync(UserManager<TUser> manager, TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> IsValidProviderForUserAsync(UserManager<TUser> manager, TUser user,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -19,7 +19,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken));
Task SetTwoFactorEnabledAsync(TUser user, bool enabled,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns whether two factor is enabled for the user
@ -27,6 +28,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> GetTwoFactorEnabledAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -20,6 +20,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, CancellationToken cancellationToken = default(CancellationToken));
Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user,
CancellationToken cancellationToken = default(CancellationToken));
}
}

View File

@ -1,9 +1,9 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using System;
namespace Microsoft.AspNet.Identity
{
@ -44,30 +44,9 @@ namespace Microsoft.AspNet.Identity
return AddInstance(func);
}
public class OptionsSetup<TOptions> : IOptionsSetup<TOptions>
{
public Action<TOptions> SetupAction { get; private set; }
public OptionsSetup(Action<TOptions> setupAction)
{
if (setupAction == null)
{
throw new ArgumentNullException("setupAction");
}
SetupAction = setupAction;
}
public void Setup(TOptions options)
{
SetupAction(options);
}
public int Order { get; set; }
}
public IdentityBuilder<TUser, TRole> SetupOptions(Action<IdentityOptions> action, int order)
{
Services.AddSetup(new OptionsSetup<IdentityOptions>(action) {Order = order});
Services.AddSetup(new OptionsSetup<IdentityOptions>(action) { Order = order });
return this;
}
@ -88,10 +67,10 @@ namespace Microsoft.AspNet.Identity
return this;
}
//public IdentityBuilder<TUser, TRole> UseTwoFactorProviders(Func<IDictionary<string, IUserTokenProvider<TUser>>> func)
//public IdentityBuilder<TUser, TRole> UseTwoFactorProviders(Func<IDictionary<string,
//IUserTokenProvider<TUser>>> func)
//{
// return Use(func);
//}
}
}

View File

@ -1,17 +1,13 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using Microsoft.Framework.ConfigurationModel;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Configuration for lockout
/// Configuration for identity
/// </summary>
public class IdentityOptions
{
public IdentityOptions()
{
ClaimType = new ClaimTypeOptions();

View File

@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Identity
/// Failure constructor that takes error messages
/// </summary>
/// <param name="errors"></param>
public IdentityResult(params string[] errors) : this((IEnumerable<string>) errors)
public IdentityResult(params string[] errors) : this((IEnumerable<string>)errors)
{
}
@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Identity
{
if (errors == null || !errors.Any())
{
errors = new[] {Resources.DefaultError};
errors = new[] { Resources.DefaultError };
}
Succeeded = false;
Errors = errors;

View File

@ -42,6 +42,7 @@ namespace Microsoft.AspNet.Identity
public IdentityRole()
{
Users = new List<IdentityUserRole<TKey>>();
Claims = new List<IdentityRoleClaim<TKey>>();
}
/// <summary>
@ -49,6 +50,11 @@ namespace Microsoft.AspNet.Identity
/// </summary>
public virtual ICollection<IdentityUserRole<TKey>> Users { get; private set; }
/// <summary>
/// Navigation property for claims in the role
/// </summary>
public virtual ICollection<IdentityRoleClaim<TKey>> Claims { get; private set; }
/// <summary>
/// Role id
/// </summary>

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Identity
{
public class IdentityRoleClaim : IdentityRoleClaim<string> { }
/// <summary>
/// EntityType that represents one specific role claim
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class IdentityRoleClaim<TKey> where TKey : IEquatable<TKey>
{
/// <summary>
/// Primary key
/// </summary>
public virtual int Id { get; set; }
/// <summary>
/// User Id for the role this claim belongs to
/// </summary>
public virtual TKey RoleId { get; set; }
/// <summary>
/// Claim type
/// </summary>
public virtual string ClaimType { get; set; }
/// <summary>
/// Claim value
/// </summary>
public virtual string ClaimValue { get; set; }
}
}

View File

@ -1,16 +1,16 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Identity;
using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.ConfigurationModel;
using System;
using Microsoft.AspNet.Identity;
using Microsoft.Framework.ConfigurationModel;
namespace Microsoft.Framework.DependencyInjection
{
public static class IdentityServiceCollectionExtensions
{
public static IdentityBuilder<IdentityUser, IdentityRole> AddIdentity(this ServiceCollection services, IConfiguration identityConfig)
public static IdentityBuilder<IdentityUser, IdentityRole> AddIdentity(this ServiceCollection services,
IConfiguration identityConfig)
{
services.SetupOptions<IdentityOptions>(identityConfig);
return services.AddIdentity<IdentityUser, IdentityRole>();
@ -21,7 +21,8 @@ namespace Microsoft.Framework.DependencyInjection
return services.AddIdentity<IdentityUser, IdentityRole>();
}
public static IdentityBuilder<TUser, TRole> AddIdentity<TUser, TRole>(this ServiceCollection services, IConfiguration identityConfig)
public static IdentityBuilder<TUser, TRole> AddIdentity<TUser, TRole>(this ServiceCollection services,
IConfiguration identityConfig)
where TUser : class
where TRole : class
{
@ -38,25 +39,26 @@ namespace Microsoft.Framework.DependencyInjection
services.AddScoped<UserManager<TUser>>();
services.AddScoped<SignInManager<TUser>>();
services.AddScoped<RoleManager<TRole>>();
services.AddScoped<IClaimsIdentityFactory<TUser>, ClaimsIdentityFactory<TUser, TRole>>();
return new IdentityBuilder<TUser, TRole>(services);
}
public static IdentityBuilder<TUser, TRole> AddIdentity<TUser, TRole>(this ServiceCollection services, Action<IdentityBuilder<TUser, TRole>> actionBuilder)
public static IdentityBuilder<TUser, TRole> AddIdentity<TUser, TRole>(this ServiceCollection services,
Action<IdentityBuilder<TUser, TRole>> actionBuilder)
where TUser : class
where TRole : class
{
services.AddIdentity<TUser, TRole>();
var builder = new IdentityBuilder<TUser, TRole>(services);
var builder = services.AddIdentity<TUser, TRole>();
actionBuilder(builder);
return builder;
}
public static IdentityBuilder<TUser, TRole> AddIdentity<TUser, TRole>(this ServiceCollection services, IConfiguration identityConfig, Action<IdentityBuilder<TUser, TRole>> actionBuilder)
public static IdentityBuilder<TUser, TRole> AddIdentity<TUser, TRole>(this ServiceCollection services,
IConfiguration identityConfig, Action<IdentityBuilder<TUser, TRole>> actionBuilder)
where TUser : class
where TRole : class
{
services.AddIdentity<TUser, TRole>(identityConfig);
var builder = new IdentityBuilder<TUser, TRole>(services);
var builder = services.AddIdentity<TUser, TRole>(identityConfig);
actionBuilder(builder);
return builder;
}
@ -67,19 +69,22 @@ namespace Microsoft.Framework.DependencyInjection
return services.AddIdentity<TUser, IdentityRole>();
}
public static IdentityBuilder<TUser, IdentityRole> AddIdentity<TUser>(this ServiceCollection services, IConfiguration identityConfig)
public static IdentityBuilder<TUser, IdentityRole> AddIdentity<TUser>(this ServiceCollection services,
IConfiguration identityConfig)
where TUser : class
{
return services.AddIdentity<TUser, IdentityRole>(identityConfig);
}
public static IdentityBuilder<TUser, IdentityRole> AddIdentity<TUser>(this ServiceCollection services, Action<IdentityBuilder<TUser, IdentityRole>> actionBuilder)
public static IdentityBuilder<TUser, IdentityRole> AddIdentity<TUser>(this ServiceCollection services,
Action<IdentityBuilder<TUser, IdentityRole>> actionBuilder)
where TUser : class
{
return services.AddIdentity<TUser, IdentityRole>(actionBuilder);
}
public static IdentityBuilder<TUser, IdentityRole> AddIdentity<TUser>(this ServiceCollection services, IConfiguration identityConfig, Action<IdentityBuilder<TUser, IdentityRole>> actionBuilder)
public static IdentityBuilder<TUser, IdentityRole> AddIdentity<TUser>(this ServiceCollection services,
IConfiguration identityConfig, Action<IdentityBuilder<TUser, IdentityRole>> actionBuilder)
where TUser : class
{
return services.AddIdentity<TUser, IdentityRole>(identityConfig, actionBuilder);

View File

@ -13,21 +13,19 @@ namespace Microsoft.AspNet.Identity
/// </summary>
public class IdentityServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultUserServices<TUser>() where TUser : class
{
return GetDefaultUserServices<TUser>(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultUserServices<TUser>(IConfiguration configuration) where TUser : class
public static IEnumerable<IServiceDescriptor> GetDefaultUserServices<TUser>(IConfiguration configuration)
where TUser : class
{
var describe = new ServiceDescriber(configuration);
// TODO: review defaults for validators should get picked up from config?
yield return describe.Transient<IUserValidator<TUser>, UserValidator<TUser>>();
yield return describe.Transient<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
yield return describe.Transient<IPasswordHasher, PasswordHasher>();
yield return describe.Transient<IClaimsIdentityFactory<TUser>, ClaimsIdentityFactory<TUser>>();
// TODO: rationalize email/sms/usertoken services
}
@ -37,11 +35,10 @@ namespace Microsoft.AspNet.Identity
return GetDefaultRoleServices<TRole>(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultRoleServices<TRole>(IConfiguration configuration) where TRole : class
public static IEnumerable<IServiceDescriptor> GetDefaultRoleServices<TRole>(IConfiguration configuration)
where TRole : class
{
var describe = new ServiceDescriber(configuration);
// TODO: review defaults for validators should get picked up from config?
yield return describe.Instance<IRoleValidator<TRole>>(new RoleValidator<TRole>());
}
}

View File

@ -48,7 +48,7 @@ namespace Microsoft.AspNet.Identity
public virtual string PasswordHash { get; set; }
/// <summary>
/// A random value that should change whenever a users credentials have changed (password changed, login removed)
/// A random value that should change whenever a users credentials change (password changed, login removed)
/// </summary>
public virtual string SecurityStamp { get; set; }
@ -96,6 +96,5 @@ namespace Microsoft.AspNet.Identity
/// Associated logins for the user
/// </summary>
public virtual ICollection<IdentityUserLogin<TKey>> Logins { get; private set; }
}
}

View File

@ -19,7 +19,7 @@ namespace Microsoft.AspNet.Identity
public virtual int Id { get; set; }
/// <summary>
/// User Id for the user who owns this login
/// User Id for the user who owns this claim
/// </summary>
public virtual TKey UserId { get; set; }

View File

@ -13,13 +13,6 @@ namespace Microsoft.AspNet.Identity
/// <typeparam name="TKey"></typeparam>
public class IdentityUserLogin<TKey> where TKey : IEquatable<TKey>
{
// TODO: Remove
public virtual string Id
{
get;
set;
}
/// <summary>
/// The login provider for the login (i.e. facebook, google)
/// </summary>

View File

@ -13,13 +13,6 @@ namespace Microsoft.AspNet.Identity
/// <typeparam name="TKey"></typeparam>
public class IdentityUserRole<TKey> where TKey : IEquatable<TKey>
{
// TODO: Remove
public virtual string Id
{
get;
set;
}
/// <summary>
/// UserId for the user that is in the role
/// </summary>

View File

@ -13,30 +13,17 @@ namespace Microsoft.AspNet.Identity
EnabledByDefault = false;
MaxFailedAccessAttempts = 5;
}
public void Copy(LockoutOptions options)
{
if (options == null)
{
return;
}
DefaultLockoutTimeSpan = options.DefaultLockoutTimeSpan;
EnabledByDefault = options.EnabledByDefault;
MaxFailedAccessAttempts = options.MaxFailedAccessAttempts;
}
/// <summary>
/// If true, will enable user lockout when users are created
/// </summary>
public bool EnabledByDefault { get; set; }
/// <summary>
/// Number of access attempts allowed for a user before lockout (if enabled)
/// </summary>
public int MaxFailedAccessAttempts { get; set; }
/// <summary>
/// Default amount of time an user is locked out for after MaxFailedAccessAttempsBeforeLockout is reached
/// </summary>

View File

@ -32,6 +32,7 @@
<Compile Include="IdentityOptions.cs" />
<Compile Include="IdentityResult.cs" />
<Compile Include="IdentityRole.cs" />
<Compile Include="IdentityRoleClaim.cs" />
<Compile Include="IdentityServiceCollectionExtensions.cs" />
<Compile Include="IdentityServices.cs" />
<Compile Include="IdentityUser.cs" />
@ -43,6 +44,7 @@
<Compile Include="IPasswordValidator.cs" />
<Compile Include="IQueryableRoleStore.cs" />
<Compile Include="IQueryableUserStore.cs" />
<Compile Include="IRoleClaimStore.cs" />
<Compile Include="IRoleStore.cs" />
<Compile Include="IRoleValidator.cs" />
<Compile Include="IUserClaimStore.cs" />
@ -62,7 +64,7 @@
<Compile Include="PasswordOptions.cs" />
<Compile Include="PasswordValidator.cs" />
<Compile Include="PasswordVerificationResult.cs" />
<Compile Include="Resources.Designer.cs" />
<Compile Include="Properties\Resources.Designer.cs" />
<Compile Include="Rfc6238AuthenticationService.cs" />
<Compile Include="RoleManager.cs" />
<Compile Include="RoleValidator.cs" />

View File

@ -1,8 +1,6 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.ConfigurationModel;
namespace Microsoft.AspNet.Identity
{
public class PasswordOptions

View File

@ -22,7 +22,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="manager"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<IdentityResult> ValidateAsync(string password, UserManager<TUser> manager, CancellationToken cancellationToken = default(CancellationToken))
public virtual Task<IdentityResult> ValidateAsync(string password, UserManager<TUser> manager,
CancellationToken cancellationToken = default(CancellationToken))
{
if (password == null)
{
@ -36,7 +37,8 @@ namespace Microsoft.AspNet.Identity
var options = manager.Options.Password;
if (string.IsNullOrWhiteSpace(password) || password.Length < options.RequiredLength)
{
errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PasswordTooShort, options.RequiredLength));
errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PasswordTooShort,
options.RequiredLength));
}
if (options.RequireNonLetterOrDigit && password.All(IsLetterOrDigit))
{

View File

@ -0,0 +1,590 @@
// <auto-generated />
namespace Microsoft.AspNet.Identity
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNet.Identity.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// An unknown failure has occured.
/// </summary>
internal static string DefaultError
{
get { return GetString("DefaultError"); }
}
/// <summary>
/// An unknown failure has occured.
/// </summary>
internal static string FormatDefaultError()
{
return GetString("DefaultError");
}
/// <summary>
/// Email '{0}' is already taken.
/// </summary>
internal static string DuplicateEmail
{
get { return GetString("DuplicateEmail"); }
}
/// <summary>
/// Email '{0}' is already taken.
/// </summary>
internal static string FormatDuplicateEmail(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("DuplicateEmail"), p0);
}
/// <summary>
/// Name {0} is already taken.
/// </summary>
internal static string DuplicateName
{
get { return GetString("DuplicateName"); }
}
/// <summary>
/// Name {0} is already taken.
/// </summary>
internal static string FormatDuplicateName(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("DuplicateName"), p0);
}
/// <summary>
/// A user with that external login already exists.
/// </summary>
internal static string ExternalLoginExists
{
get { return GetString("ExternalLoginExists"); }
}
/// <summary>
/// A user with that external login already exists.
/// </summary>
internal static string FormatExternalLoginExists()
{
return GetString("ExternalLoginExists");
}
/// <summary>
/// Email '{0}' is invalid.
/// </summary>
internal static string InvalidEmail
{
get { return GetString("InvalidEmail"); }
}
/// <summary>
/// Email '{0}' is invalid.
/// </summary>
internal static string FormatInvalidEmail(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("InvalidEmail"), p0);
}
/// <summary>
/// Invalid token.
/// </summary>
internal static string InvalidToken
{
get { return GetString("InvalidToken"); }
}
/// <summary>
/// Invalid token.
/// </summary>
internal static string FormatInvalidToken()
{
return GetString("InvalidToken");
}
/// <summary>
/// User name {0} is invalid, can only contain letters or digits.
/// </summary>
internal static string InvalidUserName
{
get { return GetString("InvalidUserName"); }
}
/// <summary>
/// User name {0} is invalid, can only contain letters or digits.
/// </summary>
internal static string FormatInvalidUserName(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("InvalidUserName"), p0);
}
/// <summary>
/// Lockout is not enabled for this user.
/// </summary>
internal static string LockoutNotEnabled
{
get { return GetString("LockoutNotEnabled"); }
}
/// <summary>
/// Lockout is not enabled for this user.
/// </summary>
internal static string FormatLockoutNotEnabled()
{
return GetString("LockoutNotEnabled");
}
/// <summary>
/// No IUserTokenProvider is registered.
/// </summary>
internal static string NoTokenProvider
{
get { return GetString("NoTokenProvider"); }
}
/// <summary>
/// No IUserTokenProvider is registered.
/// </summary>
internal static string FormatNoTokenProvider()
{
return GetString("NoTokenProvider");
}
/// <summary>
/// No IUserTwoFactorProvider for '{0}' is registered.
/// </summary>
internal static string NoTwoFactorProvider
{
get { return GetString("NoTwoFactorProvider"); }
}
/// <summary>
/// No IUserTwoFactorProvider for '{0}' is registered.
/// </summary>
internal static string FormatNoTwoFactorProvider(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("NoTwoFactorProvider"), p0);
}
/// <summary>
/// Incorrect password.
/// </summary>
internal static string PasswordMismatch
{
get { return GetString("PasswordMismatch"); }
}
/// <summary>
/// Incorrect password.
/// </summary>
internal static string FormatPasswordMismatch()
{
return GetString("PasswordMismatch");
}
/// <summary>
/// Passwords must have at least one digit ('0'-'9').
/// </summary>
internal static string PasswordRequireDigit
{
get { return GetString("PasswordRequireDigit"); }
}
/// <summary>
/// Passwords must have at least one digit ('0'-'9').
/// </summary>
internal static string FormatPasswordRequireDigit()
{
return GetString("PasswordRequireDigit");
}
/// <summary>
/// Passwords must have at least one lowercase ('a'-'z').
/// </summary>
internal static string PasswordRequireLower
{
get { return GetString("PasswordRequireLower"); }
}
/// <summary>
/// Passwords must have at least one lowercase ('a'-'z').
/// </summary>
internal static string FormatPasswordRequireLower()
{
return GetString("PasswordRequireLower");
}
/// <summary>
/// Passwords must have at least one non letter or digit character.
/// </summary>
internal static string PasswordRequireNonLetterOrDigit
{
get { return GetString("PasswordRequireNonLetterOrDigit"); }
}
/// <summary>
/// Passwords must have at least one non letter or digit character.
/// </summary>
internal static string FormatPasswordRequireNonLetterOrDigit()
{
return GetString("PasswordRequireNonLetterOrDigit");
}
/// <summary>
/// Passwords must have at least one uppercase ('A'-'Z').
/// </summary>
internal static string PasswordRequireUpper
{
get { return GetString("PasswordRequireUpper"); }
}
/// <summary>
/// Passwords must have at least one uppercase ('A'-'Z').
/// </summary>
internal static string FormatPasswordRequireUpper()
{
return GetString("PasswordRequireUpper");
}
/// <summary>
/// Passwords must be at least {0} characters.
/// </summary>
internal static string PasswordTooShort
{
get { return GetString("PasswordTooShort"); }
}
/// <summary>
/// Passwords must be at least {0} characters.
/// </summary>
internal static string FormatPasswordTooShort(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("PasswordTooShort"), p0);
}
/// <summary>
/// {0} cannot be null or empty.
/// </summary>
internal static string PropertyTooShort
{
get { return GetString("PropertyTooShort"); }
}
/// <summary>
/// {0} cannot be null or empty.
/// </summary>
internal static string FormatPropertyTooShort(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("PropertyTooShort"), p0);
}
/// <summary>
/// Role {0} does not exist.
/// </summary>
internal static string RoleNotFound
{
get { return GetString("RoleNotFound"); }
}
/// <summary>
/// Role {0} does not exist.
/// </summary>
internal static string FormatRoleNotFound(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("RoleNotFound"), p0);
}
/// <summary>
/// Store does not implement IQueryableRoleStore&lt;TRole&gt;.
/// </summary>
internal static string StoreNotIQueryableRoleStore
{
get { return GetString("StoreNotIQueryableRoleStore"); }
}
/// <summary>
/// Store does not implement IQueryableRoleStore&lt;TRole&gt;.
/// </summary>
internal static string FormatStoreNotIQueryableRoleStore()
{
return GetString("StoreNotIQueryableRoleStore");
}
/// <summary>
/// Store does not implement IQueryableUserStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIQueryableUserStore
{
get { return GetString("StoreNotIQueryableUserStore"); }
}
/// <summary>
/// Store does not implement IQueryableUserStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIQueryableUserStore()
{
return GetString("StoreNotIQueryableUserStore");
}
/// <summary>
/// Store does not implement IRoleClaimStore&lt;TRole&gt;.
/// </summary>
internal static string StoreNotIRoleClaimStore
{
get { return GetString("StoreNotIRoleClaimStore"); }
}
/// <summary>
/// Store does not implement IRoleClaimStore&lt;TRole&gt;.
/// </summary>
internal static string FormatStoreNotIRoleClaimStore()
{
return GetString("StoreNotIRoleClaimStore");
}
/// <summary>
/// Store does not implement IUserClaimStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserClaimStore
{
get { return GetString("StoreNotIUserClaimStore"); }
}
/// <summary>
/// Store does not implement IUserClaimStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserClaimStore()
{
return GetString("StoreNotIUserClaimStore");
}
/// <summary>
/// Store does not implement IUserConfirmationStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserConfirmationStore
{
get { return GetString("StoreNotIUserConfirmationStore"); }
}
/// <summary>
/// Store does not implement IUserConfirmationStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserConfirmationStore()
{
return GetString("StoreNotIUserConfirmationStore");
}
/// <summary>
/// Store does not implement IUserEmailStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserEmailStore
{
get { return GetString("StoreNotIUserEmailStore"); }
}
/// <summary>
/// Store does not implement IUserEmailStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserEmailStore()
{
return GetString("StoreNotIUserEmailStore");
}
/// <summary>
/// Store does not implement IUserLockoutStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserLockoutStore
{
get { return GetString("StoreNotIUserLockoutStore"); }
}
/// <summary>
/// Store does not implement IUserLockoutStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserLockoutStore()
{
return GetString("StoreNotIUserLockoutStore");
}
/// <summary>
/// Store does not implement IUserLoginStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserLoginStore
{
get { return GetString("StoreNotIUserLoginStore"); }
}
/// <summary>
/// Store does not implement IUserLoginStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserLoginStore()
{
return GetString("StoreNotIUserLoginStore");
}
/// <summary>
/// Store does not implement IUserPasswordStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserPasswordStore
{
get { return GetString("StoreNotIUserPasswordStore"); }
}
/// <summary>
/// Store does not implement IUserPasswordStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserPasswordStore()
{
return GetString("StoreNotIUserPasswordStore");
}
/// <summary>
/// Store does not implement IUserPhoneNumberStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserPhoneNumberStore
{
get { return GetString("StoreNotIUserPhoneNumberStore"); }
}
/// <summary>
/// Store does not implement IUserPhoneNumberStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserPhoneNumberStore()
{
return GetString("StoreNotIUserPhoneNumberStore");
}
/// <summary>
/// Store does not implement IUserRoleStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserRoleStore
{
get { return GetString("StoreNotIUserRoleStore"); }
}
/// <summary>
/// Store does not implement IUserRoleStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserRoleStore()
{
return GetString("StoreNotIUserRoleStore");
}
/// <summary>
/// Store does not implement IUserSecurityStampStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserSecurityStampStore
{
get { return GetString("StoreNotIUserSecurityStampStore"); }
}
/// <summary>
/// Store does not implement IUserSecurityStampStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserSecurityStampStore()
{
return GetString("StoreNotIUserSecurityStampStore");
}
/// <summary>
/// Store does not implement IUserTwoFactorStore&lt;TUser&gt;.
/// </summary>
internal static string StoreNotIUserTwoFactorStore
{
get { return GetString("StoreNotIUserTwoFactorStore"); }
}
/// <summary>
/// Store does not implement IUserTwoFactorStore&lt;TUser&gt;.
/// </summary>
internal static string FormatStoreNotIUserTwoFactorStore()
{
return GetString("StoreNotIUserTwoFactorStore");
}
/// <summary>
/// User already has a password set.
/// </summary>
internal static string UserAlreadyHasPassword
{
get { return GetString("UserAlreadyHasPassword"); }
}
/// <summary>
/// User already has a password set.
/// </summary>
internal static string FormatUserAlreadyHasPassword()
{
return GetString("UserAlreadyHasPassword");
}
/// <summary>
/// User already in role.
/// </summary>
internal static string UserAlreadyInRole
{
get { return GetString("UserAlreadyInRole"); }
}
/// <summary>
/// User already in role.
/// </summary>
internal static string FormatUserAlreadyInRole()
{
return GetString("UserAlreadyInRole");
}
/// <summary>
/// User {0} does not exist.
/// </summary>
internal static string UserNameNotFound
{
get { return GetString("UserNameNotFound"); }
}
/// <summary>
/// User {0} does not exist.
/// </summary>
internal static string FormatUserNameNotFound(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("UserNameNotFound"), p0);
}
/// <summary>
/// User is not in role.
/// </summary>
internal static string UserNotInRole
{
get { return GetString("UserNotInRole"); }
}
/// <summary>
/// User is not in role.
/// </summary>
internal static string FormatUserNotInRole()
{
return GetString("UserNotInRole");
}
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -1,382 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.AspNet.Identity {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
#if NET45
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.AspNet.Identity.Resources", typeof(Resources).Assembly);
#else
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.AspNet.Identity.Resources", System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(Resources)).Assembly);
#endif
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to An unknown failure has occured..
/// </summary>
internal static string DefaultError {
get {
return ResourceManager.GetString("DefaultError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Email &apos;{0}&apos; is already taken..
/// </summary>
internal static string DuplicateEmail {
get {
return ResourceManager.GetString("DuplicateEmail", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name {0} is already taken..
/// </summary>
internal static string DuplicateName {
get {
return ResourceManager.GetString("DuplicateName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A user with that external login already exists..
/// </summary>
internal static string ExternalLoginExists {
get {
return ResourceManager.GetString("ExternalLoginExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Email &apos;{0}&apos; is invalid..
/// </summary>
internal static string InvalidEmail {
get {
return ResourceManager.GetString("InvalidEmail", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid token..
/// </summary>
internal static string InvalidToken {
get {
return ResourceManager.GetString("InvalidToken", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User name {0} is invalid, can only contain letters or digits..
/// </summary>
internal static string InvalidUserName {
get {
return ResourceManager.GetString("InvalidUserName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Lockout is not enabled for this user..
/// </summary>
internal static string LockoutNotEnabled {
get {
return ResourceManager.GetString("LockoutNotEnabled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No IUserTokenProvider is registered..
/// </summary>
internal static string NoTokenProvider {
get {
return ResourceManager.GetString("NoTokenProvider", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No IUserTwoFactorProvider for &apos;{0}&apos; is registered..
/// </summary>
internal static string NoTwoFactorProvider {
get {
return ResourceManager.GetString("NoTwoFactorProvider", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incorrect password..
/// </summary>
internal static string PasswordMismatch {
get {
return ResourceManager.GetString("PasswordMismatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one digit (&apos;0&apos;-&apos;9&apos;)..
/// </summary>
internal static string PasswordRequireDigit {
get {
return ResourceManager.GetString("PasswordRequireDigit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one lowercase (&apos;a&apos;-&apos;z&apos;)..
/// </summary>
internal static string PasswordRequireLower {
get {
return ResourceManager.GetString("PasswordRequireLower", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one non letter or digit character..
/// </summary>
internal static string PasswordRequireNonLetterOrDigit {
get {
return ResourceManager.GetString("PasswordRequireNonLetterOrDigit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one uppercase (&apos;A&apos;-&apos;Z&apos;)..
/// </summary>
internal static string PasswordRequireUpper {
get {
return ResourceManager.GetString("PasswordRequireUpper", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must be at least {0} characters..
/// </summary>
internal static string PasswordTooShort {
get {
return ResourceManager.GetString("PasswordTooShort", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} cannot be null or empty..
/// </summary>
internal static string PropertyTooShort {
get {
return ResourceManager.GetString("PropertyTooShort", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role {0} does not exist..
/// </summary>
internal static string RoleNotFound {
get {
return ResourceManager.GetString("RoleNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IQueryableRoleStore&lt;TRole&gt;..
/// </summary>
internal static string StoreNotIQueryableRoleStore {
get {
return ResourceManager.GetString("StoreNotIQueryableRoleStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IQueryableUserStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIQueryableUserStore {
get {
return ResourceManager.GetString("StoreNotIQueryableUserStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserClaimStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserClaimStore {
get {
return ResourceManager.GetString("StoreNotIUserClaimStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserConfirmationStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserConfirmationStore {
get {
return ResourceManager.GetString("StoreNotIUserConfirmationStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserEmailStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserEmailStore {
get {
return ResourceManager.GetString("StoreNotIUserEmailStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserLockoutStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserLockoutStore {
get {
return ResourceManager.GetString("StoreNotIUserLockoutStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserLoginStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserLoginStore {
get {
return ResourceManager.GetString("StoreNotIUserLoginStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserPasswordStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserPasswordStore {
get {
return ResourceManager.GetString("StoreNotIUserPasswordStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserPhoneNumberStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserPhoneNumberStore {
get {
return ResourceManager.GetString("StoreNotIUserPhoneNumberStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserRoleStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserRoleStore {
get {
return ResourceManager.GetString("StoreNotIUserRoleStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserSecurityStampStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserSecurityStampStore {
get {
return ResourceManager.GetString("StoreNotIUserSecurityStampStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserTwoFactorStore&lt;TUser&gt;..
/// </summary>
internal static string StoreNotIUserTwoFactorStore {
get {
return ResourceManager.GetString("StoreNotIUserTwoFactorStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User already has a password set..
/// </summary>
internal static string UserAlreadyHasPassword {
get {
return ResourceManager.GetString("UserAlreadyHasPassword", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User already in role..
/// </summary>
internal static string UserAlreadyInRole {
get {
return ResourceManager.GetString("UserAlreadyInRole", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to UserId not found..
/// </summary>
internal static string UserIdNotFound {
get {
return ResourceManager.GetString("UserIdNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User {0} does not exist..
/// </summary>
internal static string UserNameNotFound {
get {
return ResourceManager.GetString("UserNameNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User is not in role..
/// </summary>
internal static string UserNotInRole {
get {
return ResourceManager.GetString("UserNotInRole", resourceCulture);
}
}
}
}

View File

@ -197,6 +197,10 @@
<value>Store does not implement IQueryableUserStore&lt;TUser&gt;.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIRoleClaimStore" xml:space="preserve">
<value>Store does not implement IRoleClaimStore&lt;TRole&gt;.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserClaimStore" xml:space="preserve">
<value>Store does not implement IUserClaimStore&lt;TUser&gt;.</value>
<comment>error when the store does not implement this interface</comment>

View File

@ -2,11 +2,12 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
namespace Microsoft.AspNet.Identity
{
@ -21,7 +22,7 @@ namespace Microsoft.AspNet.Identity
/// <summary>
/// Constructor
/// </summary>
/// <param name="store">The IRoleStore is responsible for commiting changes via the UpdateAsync/CreateAsync methods</param>
/// <param name="store">The IRoleStore commits changes via the UpdateAsync/CreateAsync methods</param>
/// <param name="roleValidator"></param>
public RoleManager(IRoleStore<TRole> store, IRoleValidator<TRole> roleValidator)
{
@ -75,6 +76,18 @@ namespace Microsoft.AspNet.Identity
}
}
/// <summary>
/// Returns true if the store is an IUserClaimStore
/// </summary>
public virtual bool SupportsRoleClaims
{
get
{
ThrowIfDisposed();
return Store is IRoleClaimStore<TRole>;
}
}
/// <summary>
/// Dispose this object
/// </summary>
@ -86,7 +99,8 @@ namespace Microsoft.AspNet.Identity
private async Task<IdentityResult> ValidateRoleInternal(TRole role, CancellationToken cancellationToken)
{
return (RoleValidator == null) ? IdentityResult.Success : await RoleValidator.ValidateAsync(this, role, cancellationToken);
return (RoleValidator == null) ? IdentityResult.Success :
await RoleValidator.ValidateAsync(this, role, cancellationToken);
}
/// <summary>
@ -95,7 +109,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> CreateAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
@ -118,7 +133,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> UpdateAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
@ -141,7 +157,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> DeleteAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
@ -159,7 +176,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> RoleExistsAsync(string roleName, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> RoleExistsAsync(string roleName,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (roleName == null)
@ -176,7 +194,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<TRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<TRole> FindByIdAsync(string roleId,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return await Store.FindByIdAsync(roleId, cancellationToken);
@ -188,7 +207,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetRoleNameAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return await Store.GetRoleNameAsync(role, cancellationToken);
@ -201,7 +221,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="name"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetRoleNameAsync(TRole role, string name, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetRoleNameAsync(TRole role, string name,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
await Store.SetRoleNameAsync(role, name, cancellationToken);
@ -214,7 +235,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetRoleIdAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return await Store.GetRoleIdAsync(role, cancellationToken);
@ -226,7 +248,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<TRole> FindByNameAsync(string roleName, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<TRole> FindByNameAsync(string roleName,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (roleName == null)
@ -237,6 +260,79 @@ namespace Microsoft.AspNet.Identity
return await Store.FindByNameAsync(roleName, cancellationToken);
}
// IRoleClaimStore methods
private IRoleClaimStore<TRole> GetClaimStore()
{
var cast = Store as IRoleClaimStore<TRole>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIRoleClaimStore);
}
return cast;
}
/// <summary>
/// Add a user claim
/// </summary>
/// <param name="role"></param>
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddClaimAsync(TRole role, Claim claim,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
if (claim == null)
{
throw new ArgumentNullException("claim");
}
if (role == null)
{
throw new ArgumentNullException("role");
}
await claimStore.AddClaimAsync(role, claim, cancellationToken);
return await UpdateAsync(role, cancellationToken);
}
/// <summary>
/// Remove a user claim
/// </summary>
/// <param name="role"></param>
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveClaimAsync(TRole role, Claim claim,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
if (role == null)
{
throw new ArgumentNullException("role");
}
await claimStore.RemoveClaimAsync(role, claim, cancellationToken);
return await UpdateAsync(role, cancellationToken);
}
/// <summary>
/// Get a role's claims
/// </summary>
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<Claim>> GetClaimsAsync(TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
if (role == null)
{
throw new ArgumentNullException("role");
}
return await claimStore.GetClaimsAsync(role, cancellationToken);
}
private void ThrowIfDisposed()
{
if (_disposed)

View File

@ -22,7 +22,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role,
CancellationToken cancellationToken = default(CancellationToken))
{
if (manager == null)
{
@ -52,7 +53,8 @@ namespace Microsoft.AspNet.Identity
else
{
var owner = await manager.FindByNameAsync(roleName);
if (owner != null && !string.Equals(await manager.GetRoleIdAsync(owner), await manager.GetRoleIdAsync(role)))
if (owner != null &&
!string.Equals(await manager.GetRoleIdAsync(owner), await manager.GetRoleIdAsync(role)))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateName, roleName));
}

View File

@ -13,7 +13,8 @@ namespace Microsoft.AspNet.Identity
/// <typeparam name="TUser"></typeparam>
public class SignInManager<TUser> where TUser : class
{
public SignInManager(UserManager<TUser> userManager, IAuthenticationManager authenticationManager)
public SignInManager(UserManager<TUser> userManager, IAuthenticationManager authenticationManager,
IClaimsIdentityFactory<TUser> claimsFactory)
{
if (userManager == null)
{
@ -23,8 +24,13 @@ namespace Microsoft.AspNet.Identity
{
throw new ArgumentNullException("authenticationManager");
}
if (claimsFactory == null)
{
throw new ArgumentNullException("claimsFactory");
}
UserManager = userManager;
AuthenticationManager = authenticationManager;
ClaimsFactory = claimsFactory;
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie;
}
@ -33,11 +39,12 @@ namespace Microsoft.AspNet.Identity
public UserManager<TUser> UserManager { get; private set; }
public IAuthenticationManager AuthenticationManager { get; private set; }
public IClaimsIdentityFactory<TUser> ClaimsFactory { get; private set; }
// Should this be a func?
public virtual async Task<ClaimsIdentity> CreateUserIdentityAsync(TUser user)
{
return await UserManager.CreateIdentityAsync(user, AuthenticationType);
return await ClaimsFactory.CreateAsync(user, AuthenticationType);
}
public virtual async Task SignInAsync(TUser user, bool isPersistent)
@ -52,7 +59,8 @@ namespace Microsoft.AspNet.Identity
AuthenticationManager.SignOut(AuthenticationType);
}
public virtual async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
public virtual async Task<SignInStatus> PasswordSignInAsync(string userName, string password,
bool isPersistent, bool shouldLockout)
{
var user = await UserManager.FindByNameAsync(userName);
if (user == null)

View File

@ -9,7 +9,6 @@ using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Identity
@ -23,7 +22,6 @@ namespace Microsoft.AspNet.Identity
private readonly Dictionary<string, IUserTokenProvider<TUser>> _factors =
new Dictionary<string, IUserTokenProvider<TUser>>();
private IClaimsIdentityFactory<TUser> _claimsFactory;
private TimeSpan _defaultLockout = TimeSpan.Zero;
private bool _disposed;
private IPasswordHasher _passwordHasher;
@ -40,7 +38,7 @@ namespace Microsoft.AspNet.Identity
/// <param name="claimsIdentityFactory"></param>
public UserManager(IUserStore<TUser> store, IOptionsAccessor<IdentityOptions> optionsAccessor,
IPasswordHasher passwordHasher, IUserValidator<TUser> userValidator,
IPasswordValidator<TUser> passwordValidator, IClaimsIdentityFactory<TUser> claimsIdentityFactory)
IPasswordValidator<TUser> passwordValidator)
{
if (store == null)
{
@ -54,24 +52,11 @@ namespace Microsoft.AspNet.Identity
{
throw new ArgumentNullException("passwordHasher");
}
if (userValidator == null)
{
throw new ArgumentNullException("userValidator");
}
if (passwordValidator == null)
{
throw new ArgumentNullException("passwordValidator");
}
if (claimsIdentityFactory == null)
{
throw new ArgumentNullException("claimsIdentityFactory");
}
Store = store;
Options = optionsAccessor.Options;
PasswordHasher = passwordHasher;
UserValidator = userValidator;
PasswordValidator = passwordValidator;
ClaimsIdentityFactory = claimsIdentityFactory;
// TODO: Email/Sms/Token services
}
@ -111,27 +96,6 @@ namespace Microsoft.AspNet.Identity
/// </summary>
public IPasswordValidator<TUser> PasswordValidator { get; set; }
/// <summary>
/// Used to create claims identities from users
/// </summary>
public IClaimsIdentityFactory<TUser> ClaimsIdentityFactory
{
get
{
ThrowIfDisposed();
return _claimsFactory;
}
set
{
ThrowIfDisposed();
if (value == null)
{
throw new ArgumentNullException("value");
}
_claimsFactory = value;
}
}
/// <summary>
/// Used to send email
/// </summary>
@ -163,7 +127,6 @@ namespace Microsoft.AspNet.Identity
}
_options = value;
}
}
/// <summary>
@ -319,23 +282,6 @@ namespace Microsoft.AspNet.Identity
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a ClaimsIdentity representing the user
/// </summary>
/// <param name="user"></param>
/// <param name="authenticationType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return ClaimsIdentityFactory.CreateAsync(this, user, authenticationType, cancellationToken);
}
private async Task<IdentityResult> ValidateUserInternal(TUser user, CancellationToken cancellationToken)
{
return (UserValidator == null)
@ -349,7 +295,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> CreateAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
await UpdateSecurityStampInternal(user, cancellationToken);
@ -372,7 +319,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> UpdateAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -394,7 +342,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> DeleteAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -411,7 +360,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="userId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
public virtual Task<TUser> FindByIdAsync(string userId,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return Store.FindByIdAsync(userId, cancellationToken);
@ -423,7 +373,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="userName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
public virtual Task<TUser> FindByNameAsync(string userName,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (userName == null)
@ -451,7 +402,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="password"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> CreateAsync(TUser user, string password, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> CreateAsync(TUser user, string password,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
@ -477,7 +429,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetUserNameAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -494,7 +447,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="userName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetUserNameAsync(TUser user, string userName,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -511,7 +465,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetUserIdAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return await Store.GetUserIdAsync(user, cancellationToken);
@ -524,7 +479,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="password"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<TUser> FindByUserNamePasswordAsync(string userName, string password, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<TUser> FindByUserNamePasswordAsync(string userName, string password,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var user = await FindByNameAsync(userName, cancellationToken);
@ -542,7 +498,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="password"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> CheckPasswordAsync(TUser user, string password, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> CheckPasswordAsync(TUser user, string password,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
@ -559,7 +516,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> HasPasswordAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
@ -577,7 +535,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="password"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddPasswordAsync(TUser user, string password, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> AddPasswordAsync(TUser user, string password,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
@ -633,7 +592,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemovePasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> RemovePasswordAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
@ -664,7 +624,7 @@ namespace Microsoft.AspNet.Identity
}
/// <summary>
/// By default, retrieves the hashed password from the user store and calls PasswordHasher.VerifyHashPassword
/// By default, retrieves the hashed password from the user store and calls PasswordHasher.VerifyHashPassword
/// </summary>
/// <param name="store"></param>
/// <param name="user"></param>
@ -695,7 +655,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetSecurityStampAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var securityStore = GetSecurityStore();
@ -712,7 +673,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> UpdateSecurityStampAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> UpdateSecurityStampAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
GetSecurityStore();
@ -730,7 +692,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GeneratePasswordResetTokenAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GeneratePasswordResetTokenAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return await GenerateUserTokenAsync("ResetPassword", user, cancellationToken);
@ -744,7 +707,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="newPassword"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ResetPasswordAsync(TUser user, string token, string newPassword, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> ResetPasswordAsync(TUser user, string token, string newPassword,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -794,7 +758,8 @@ namespace Microsoft.AspNet.Identity
/// Returns the user associated with this login
/// </summary>
/// <returns></returns>
public virtual Task<TUser> FindByLoginAsync(UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
public virtual Task<TUser> FindByLoginAsync(UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return GetLoginStore().FindByLoginAsync(login, cancellationToken);
@ -807,7 +772,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="login"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> RemoveLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
@ -831,7 +797,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="login"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> AddLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
@ -858,7 +825,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
@ -887,7 +855,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> AddClaimAsync(TUser user, Claim claim,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
@ -910,7 +879,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> RemoveClaimAsync(TUser user, Claim claim,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
@ -928,7 +898,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IList<Claim>> GetClaimsAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
@ -956,7 +927,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddToRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> AddToRoleAsync(TUser user, string role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
@ -980,7 +952,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roles"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddToRolesAsync(TUser user, IEnumerable<string> roles, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> AddToRolesAsync(TUser user, IEnumerable<string> roles,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
@ -1011,7 +984,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveFromRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> RemoveFromRoleAsync(TUser user, string role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
@ -1034,7 +1008,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="roles"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveFromRolesAsync(TUser user, IEnumerable<string> roles, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> RemoveFromRolesAsync(TUser user, IEnumerable<string> roles,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
@ -1063,7 +1038,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IList<string>> GetRolesAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
@ -1081,7 +1057,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsInRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> IsInRoleAsync(TUser user, string role,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
@ -1109,7 +1086,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetEmailAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetEmailAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetEmailStore();
@ -1127,7 +1105,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="email"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetEmailAsync(TUser user, string email, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetEmailAsync(TUser user, string email,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetEmailStore();
@ -1147,7 +1126,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="email"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByEmailAsync(string email, CancellationToken cancellationToken = default(CancellationToken))
public virtual Task<TUser> FindByEmailAsync(string email,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetEmailStore();
@ -1164,7 +1144,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GenerateEmailConfirmationTokenAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual Task<string> GenerateEmailConfirmationTokenAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
return GenerateUserTokenAsync("Confirmation", user, cancellationToken);
@ -1177,7 +1158,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="token"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ConfirmEmailAsync(TUser user, string token, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> ConfirmEmailAsync(TUser user, string token,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetEmailStore();
@ -1199,7 +1181,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsEmailConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> IsEmailConfirmedAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetEmailStore();
@ -1227,7 +1210,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GetPhoneNumberAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetPhoneNumberStore();
@ -1245,7 +1229,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="phoneNumber"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetPhoneNumberAsync(TUser user, string phoneNumber,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetPhoneNumberStore();
@ -1267,7 +1252,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="token"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ChangePhoneNumberAsync(TUser user, string phoneNumber, string token, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> ChangePhoneNumberAsync(TUser user, string phoneNumber, string token,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetPhoneNumberStore();
@ -1291,7 +1277,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> IsPhoneNumberConfirmedAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetPhoneNumberStore();
@ -1355,7 +1342,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="token"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> VerifyUserTokenAsync(TUser user, string purpose, string token, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> VerifyUserTokenAsync(TUser user, string purpose, string token,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (UserTokenProvider == null)
@ -1377,7 +1365,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GenerateUserTokenAsync(string purpose, TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GenerateUserTokenAsync(string purpose, TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (UserTokenProvider == null)
@ -1416,7 +1405,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -1442,7 +1432,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="token"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> VerifyTwoFactorTokenAsync(TUser user, string twoFactorProvider, string token, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> VerifyTwoFactorTokenAsync(TUser user, string twoFactorProvider, string token,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -1451,8 +1442,8 @@ namespace Microsoft.AspNet.Identity
}
if (!_factors.ContainsKey(twoFactorProvider))
{
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Resources.NoTwoFactorProvider,
twoFactorProvider));
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
Resources.NoTwoFactorProvider, twoFactorProvider));
}
// Make sure the token is valid
var provider = _factors[twoFactorProvider];
@ -1466,7 +1457,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="twoFactorProvider"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> GenerateTwoFactorTokenAsync(TUser user, string twoFactorProvider, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<string> GenerateTwoFactorTokenAsync(TUser user, string twoFactorProvider,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -1475,8 +1467,8 @@ namespace Microsoft.AspNet.Identity
}
if (!_factors.ContainsKey(twoFactorProvider))
{
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Resources.NoTwoFactorProvider,
twoFactorProvider));
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
Resources.NoTwoFactorProvider, twoFactorProvider));
}
return await _factors[twoFactorProvider].GenerateAsync(twoFactorProvider, this, user, cancellationToken);
}
@ -1499,8 +1491,8 @@ namespace Microsoft.AspNet.Identity
}
if (!_factors.ContainsKey(twoFactorProvider))
{
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Resources.NoTwoFactorProvider,
twoFactorProvider));
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
Resources.NoTwoFactorProvider, twoFactorProvider));
}
await _factors[twoFactorProvider].NotifyAsync(token, this, user, cancellationToken);
return IdentityResult.Success;
@ -1523,7 +1515,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> GetTwoFactorEnabledAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserTwoFactorStore();
@ -1541,7 +1534,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetTwoFactorEnabledAsync(TUser user, bool enabled,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserTwoFactorStore();
@ -1564,7 +1558,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="body"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task SendEmailAsync(TUser user, string subject, string body, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task SendEmailAsync(TUser user, string subject, string body,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -1590,7 +1585,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="message"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task SendSmsAsync(TUser user, string message, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task SendSmsAsync(TUser user, string message,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@ -1625,7 +1621,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsLockedOutAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> IsLockedOutAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1648,7 +1645,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetLockoutEnabledAsync(TUser user, bool enabled,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1666,7 +1664,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<bool> GetLockoutEnabledAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1683,7 +1682,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1701,7 +1701,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="lockoutEnd"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1718,14 +1719,15 @@ namespace Microsoft.AspNet.Identity
}
/// <summary>
/// Increments the access failed count for the user and if the failed access account is greater than or equal
/// to the MaxFailedAccessAttempsBeforeLockout, the user will be locked out for the next DefaultAccountLockoutTimeSpan
/// and the AccessFailedCount will be reset to 0.
/// Increments the access failed count for the user and if the failed access account is greater than or equal
/// to the MaxFailedAccessAttempsBeforeLockout, the user will be locked out for the next
/// DefaultAccountLockoutTimeSpan and the AccessFailedCount will be reset to 0.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AccessFailedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> AccessFailedAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1739,8 +1741,8 @@ namespace Microsoft.AspNet.Identity
{
return await UpdateAsync(user, cancellationToken);
}
await
store.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.Add(Options.Lockout.DefaultLockoutTimeSpan), cancellationToken);
await store.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.Add(Options.Lockout.DefaultLockoutTimeSpan),
cancellationToken);
await store.ResetAccessFailedCountAsync(user, cancellationToken);
return await UpdateAsync(user, cancellationToken);
}
@ -1751,7 +1753,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> ResetAccessFailedCountAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
@ -1769,7 +1772,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<int> GetAccessFailedCountAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var store = GetUserLockoutStore();

View File

@ -1,8 +1,6 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.ConfigurationModel;
namespace Microsoft.AspNet.Identity
{
public class UserOptions

View File

@ -1,14 +1,14 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
#if NET45
using System.Net.Mail;
#endif
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#if NET45
using System.Net.Mail;
#endif
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity
@ -26,7 +26,8 @@ namespace Microsoft.AspNet.Identity
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
if (manager == null)
{
@ -102,7 +103,8 @@ namespace Microsoft.AspNet.Identity
else
{
var owner = await manager.FindByNameAsync(userName);
if (owner != null && !string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
if (owner != null &&
!string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateName, userName));
}
@ -130,7 +132,8 @@ namespace Microsoft.AspNet.Identity
}
#endif
var owner = await manager.FindByEmailAsync(email);
if (owner != null && !string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
if (owner != null &&
!string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateEmail, email));
}

View File

@ -1,10 +1,10 @@
{
"version": "3.0.0-*",
"version": "0.1-alpha-*",
"dependencies": {
"Microsoft.Framework.ConfigurationModel": "1.0.0-*",
"Microsoft.Framework.DependencyInjection" : "1.0.0-*",
"Microsoft.Framework.OptionsModel": "1.0.0-*",
"System.Security.Claims" : "1.0.0-*"
"Microsoft.Framework.ConfigurationModel": "0.1-alpha-*",
"Microsoft.Framework.DependencyInjection" : "0.1-alpha-*",
"Microsoft.Framework.OptionsModel": "0.1-alpha-*",
"System.Security.Claims" : "0.1-alpha-*"
},
"configurations": {
"net45": {},

View File

@ -16,7 +16,7 @@ using System.Threading.Tasks;
using Xunit;
using Microsoft.AspNet.Builder;
namespace Microsoft.AspNet.Identity.Security.Test
namespace Microsoft.AspNet.Identity.Authentication.Test
{
public class ApplicationUser : IdentityUser { }
@ -118,9 +118,11 @@ namespace Microsoft.AspNet.Identity.Security.Test
[Fact]
public void ConstructorNullChecks()
{
Assert.Throws<ArgumentNullException>("userManager", () => new SignInManager<IdentityUser>(null, null));
Assert.Throws<ArgumentNullException>("userManager", () => new SignInManager<IdentityUser>(null, null, null));
var userManager = MockHelpers.MockUserManager<IdentityUser>().Object;
Assert.Throws<ArgumentNullException>("authenticationManager", () => new SignInManager<IdentityUser>(userManager, null));
Assert.Throws<ArgumentNullException>("authenticationManager", () => new SignInManager<IdentityUser>(userManager, null, null));
var authManager = new Mock<IAuthenticationManager>().Object;
Assert.Throws<ArgumentNullException>("claimsFactory", () => new SignInManager<IdentityUser>(userManager, authManager, null));
}
//TODO: Mock fails in K (this works fine in net45)
@ -165,7 +167,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "bogus", false, false);
@ -187,14 +191,16 @@ namespace Microsoft.AspNet.Identity.Security.Test
manager.Setup(m => m.IsLockedOutAsync(user, CancellationToken.None)).ReturnsAsync(false).Verifiable();
manager.Setup(m => m.FindByNameAsync(user.UserName, CancellationToken.None)).ReturnsAsync(user).Verifiable();
manager.Setup(m => m.CheckPasswordAsync(user, "password", CancellationToken.None)).ReturnsAsync(true).Verifiable();
manager.Setup(m => m.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie, CancellationToken.None)).ReturnsAsync(new ClaimsIdentity("Microsoft.AspNet.Identity")).Verifiable();
var context = new Mock<HttpContext>();
var response = new Mock<HttpResponse>();
context.Setup(c => c.Response).Returns(response.Object).Verifiable();
response.Setup(r => r.SignIn(It.IsAny<ClaimsIdentity>(), It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Verifiable();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
claimsFactory.Setup(m => m.CreateAsync(user, DefaultAuthenticationTypes.ApplicationCookie, CancellationToken.None)).ReturnsAsync(new ClaimsIdentity("Microsoft.AspNet.Identity")).Verifiable();
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "password", isPersistent, false);
@ -205,6 +211,7 @@ namespace Microsoft.AspNet.Identity.Security.Test
context.VerifyAll();
response.VerifyAll();
contextAccessor.VerifyAll();
claimsFactory.VerifyAll();
}
[Fact]
@ -223,7 +230,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
context.Setup(c => c.Response).Returns(response.Object).Verifiable();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "password", false, false);
@ -255,7 +264,8 @@ namespace Microsoft.AspNet.Identity.Security.Test
context.Setup(c => c.Response).Returns(response.Object).Verifiable();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), new ClaimsIdentityFactory<TestUser, TestRole>(manager.Object, roleManager.Object));
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "password", false, false);
@ -281,6 +291,8 @@ namespace Microsoft.AspNet.Identity.Security.Test
manager.Setup(m => m.IsLockedOutAsync(user, CancellationToken.None)).ReturnsAsync(false).Verifiable();
manager.Setup(m => m.FindByIdAsync(user.Id, CancellationToken.None)).ReturnsAsync(user).Verifiable();
manager.Setup(m => m.VerifyTwoFactorTokenAsync(user, provider, code, CancellationToken.None)).ReturnsAsync(true).Verifiable();
manager.Setup(m => m.GetUserIdAsync(user, CancellationToken.None)).ReturnsAsync(user.Id).Verifiable();
manager.Setup(m => m.GetUserNameAsync(user, CancellationToken.None)).ReturnsAsync(user.UserName).Verifiable();
var context = new Mock<HttpContext>();
var response = new Mock<HttpResponse>();
response.Setup(r => r.SignIn(It.IsAny<ClaimsIdentity>(), It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Verifiable();
@ -291,7 +303,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
context.Setup(c => c.AuthenticateAsync(HttpAuthenticationManager.TwoFactorUserIdAuthenticationType)).ReturnsAsync(authResult).Verifiable();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new ClaimsIdentityFactory<TestUser, TestRole>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory);
// Act
var result = await helper.TwoFactorSignInAsync(provider, code, isPersistent);
@ -344,7 +358,6 @@ namespace Microsoft.AspNet.Identity.Security.Test
manager.Setup(m => m.FindByNameAsync(user.UserName, CancellationToken.None)).ReturnsAsync(user).Verifiable();
manager.Setup(m => m.GetUserIdAsync(user, CancellationToken.None)).ReturnsAsync(user.Id).Verifiable();
manager.Setup(m => m.CheckPasswordAsync(user, "password", CancellationToken.None)).ReturnsAsync(true).Verifiable();
manager.Setup(m => m.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie, CancellationToken.None)).ReturnsAsync(new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie)).Verifiable();
var context = new Mock<HttpContext>();
var response = new Mock<HttpResponse>();
context.Setup(c => c.Response).Returns(response.Object).Verifiable();
@ -356,7 +369,10 @@ namespace Microsoft.AspNet.Identity.Security.Test
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var signInService = new HttpAuthenticationManager(contextAccessor.Object);
var helper = new SignInManager<TestUser>(manager.Object, signInService);
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
claimsFactory.Setup(m => m.CreateAsync(user, DefaultAuthenticationTypes.ApplicationCookie, CancellationToken.None)).ReturnsAsync(new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie)).Verifiable();
var helper = new SignInManager<TestUser>(manager.Object, signInService, claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "password", isPersistent, false);
@ -367,10 +383,11 @@ namespace Microsoft.AspNet.Identity.Security.Test
context.VerifyAll();
response.VerifyAll();
contextAccessor.VerifyAll();
claimsFactory.VerifyAll();
}
[Theory]
[InlineData("Microsoft.AspNet.Identity.Security.Application")]
[InlineData("Microsoft.AspNet.Identity.Authentication.Application")]
[InlineData("Foo")]
public void SignOutCallsContextResponseSignOut(string authenticationType)
{
@ -382,7 +399,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
response.Setup(r => r.SignOut(authenticationType)).Verifiable();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object))
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object)
{
AuthenticationType = authenticationType
};
@ -408,7 +427,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "bogus", false, false);
@ -426,7 +447,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync("bogus", "bogus", false, false);
@ -455,7 +478,9 @@ namespace Microsoft.AspNet.Identity.Security.Test
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IContextAccessor<HttpContext>>();
contextAccessor.Setup(a => a.Value).Returns(context.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object));
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var claimsFactory = new Mock<ClaimsIdentityFactory<TestUser, TestRole>>(manager.Object, roleManager.Object);
var helper = new SignInManager<TestUser>(manager.Object, new HttpAuthenticationManager(contextAccessor.Object), claimsFactory.Object);
// Act
var result = await helper.PasswordSignInAsync(user.UserName, "bogus", false, true);

View File

@ -6,7 +6,7 @@ using System.Security.Claims;
using System.Security.Principal;
using Xunit;
namespace Microsoft.AspNet.Identity.Security.Test
namespace Microsoft.AspNet.Identity.Authentication.Test
{
public class IdentityExtensionsTest
{

View File

@ -0,0 +1,24 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.EntityFramework.InMemory.Test;
using Microsoft.Data.Entity;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity
{
public static class EntityIdentityBuilderExtensions
{
public static IdentityBuilder<TUser, TRole> AddEntityFrameworkInMemory<TUser, TRole, TDbContext>(this IdentityBuilder<TUser, TRole> builder)
where TUser : InMemoryUser
where TRole : IdentityRole
where TDbContext : DbContext
{
builder.Services.AddScoped<TDbContext>();
builder.Services.AddScoped<IUserStore<TUser>, InMemoryUserStore<TUser, TDbContext>>();
builder.Services.AddScoped<IRoleStore<TRole>, RoleStore<TRole, TDbContext>>();
return builder;
}
}
}

View File

@ -0,0 +1,82 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
{
public class InMemoryContext :
InMemoryContext<InMemoryUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public InMemoryContext() { }
public InMemoryContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
}
public class InMemoryContext<TUser> :
InMemoryContext<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
where TUser : InMemoryUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public InMemoryContext() { }
public InMemoryContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
}
public class InMemoryContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim> : DbContext
where TUser : InMemoryUser<TKey, TUserLogin, TUserRole, TUserClaim>
where TRole : IdentityRole<TKey>
where TUserLogin : IdentityUserLogin<TKey>
where TUserRole : IdentityUserRole<TKey>
where TUserClaim : IdentityUserClaim<TKey>
where TKey : IEquatable<TKey>
{
public DbSet<TUser> Users { get; set; }
public DbSet<TRole> Roles { get; set; }
public DbSet<IdentityRoleClaim> RoleClaims { get; set; }
public InMemoryContext(IServiceProvider serviceProvider)
: base(serviceProvider) { }
public InMemoryContext() { }
protected override void OnConfiguring(DbContextOptions builder)
{
builder.UseInMemoryStore();
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>()
.Key(u => u.Id)
.Properties(ps => ps.Property(u => u.UserName))
.ToTable("AspNetUsers");
builder.Entity<TRole>()
.Key(r => r.Id)
.ToTable("AspNetRoles");
builder.Entity<TUserRole>()
.Key(r => new { r.UserId, r.RoleId })
.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ForeignKeys(fk => fk.ForeignKey<TRole>(f => f.RoleId))
.ToTable("AspNetUserRoles");
builder.Entity<TUserLogin>()
.Key(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ToTable("AspNetUserLogins");
builder.Entity<TUserClaim>()
.Key(c => c.Id)
.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ToTable("AspNetUserClaims");
builder.Entity<IdentityRoleClaim>()
.Key(c => c.Id)
.ForeignKeys(fk => fk.ForeignKey<TRole>(f => f.RoleId))
.ToTable("AspNetRoleClaims");
}
}
}

View File

@ -0,0 +1,106 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
{
public class InMemoryUser : InMemoryUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public InMemoryUser()
{
Id = Guid.NewGuid().ToString();
}
public InMemoryUser(string userName)
: this()
{
UserName = userName;
}
}
public class InMemoryUser<TKey, TLogin, TRole, TClaim>
where TLogin : IdentityUserLogin<TKey>
where TRole : IdentityUserRole<TKey>
where TClaim : IdentityUserClaim<TKey>
where TKey : IEquatable<TKey>
{
public InMemoryUser()
{
Claims = new List<TClaim>();
Roles = new List<TRole>();
Logins = new List<TLogin>();
}
public virtual TKey Id { get; set; }
public virtual string UserName { get; set; }
/// <summary>
/// Email
/// </summary>
public virtual string Email { get; set; }
/// <summary>
/// True if the email is confirmed, default is false
/// </summary>
public virtual bool EmailConfirmed { get; set; }
/// <summary>
/// The salted/hashed form of the user password
/// </summary>
public virtual string PasswordHash { get; set; }
/// <summary>
/// A random value that should change whenever a users credentials have changed (password changed, login removed)
/// </summary>
public virtual string SecurityStamp { get; set; }
/// <summary>
/// PhoneNumber for the user
/// </summary>
public virtual string PhoneNumber { get; set; }
/// <summary>
/// True if the phone number is confirmed, default is false
/// </summary>
public virtual bool PhoneNumberConfirmed { get; set; }
/// <summary>
/// Is two factor enabled for the user
/// </summary>
public virtual bool TwoFactorEnabled { get; set; }
/// <summary>
/// DateTime in UTC when lockout ends, any time in the past is considered not locked out.
/// </summary>
public virtual DateTime? LockoutEnd { get; set; }
/// <summary>
/// Is lockout enabled for this user
/// </summary>
public virtual bool LockoutEnabled { get; set; }
/// <summary>
/// Used to record failures for the purposes of lockout
/// </summary>
public virtual int AccessFailedCount { get; set; }
/// <summary>
/// Navigation property for user roles
/// </summary>
public virtual ICollection<TRole> Roles { get; private set; }
/// <summary>
/// Navigation property for user claims
/// </summary>
public virtual ICollection<TClaim> Claims { get; private set; }
/// <summary>
/// Navigation property for user logins
/// </summary>
public virtual ICollection<TLogin> Logins { get; private set; }
}
}

View File

@ -0,0 +1,883 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
{
public class InMemoryUserStore : InMemoryUserStore<InMemoryUser, InMemoryContext>
{
public InMemoryUserStore(InMemoryContext context) : base(context) { }
}
public class InMemoryUserStore<TUser> : InMemoryUserStore<TUser, InMemoryContext>
where TUser : InMemoryUser
{
public InMemoryUserStore(InMemoryContext context) : base(context) { }
}
public class InMemoryUserStore<TUser, TContext> : InMemoryUserStore<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim, TContext>
where TUser:InMemoryUser
where TContext : DbContext
{
public InMemoryUserStore(TContext context) : base(context) { }
}
public class InMemoryUserStore<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim, TContext> :
IUserLoginStore<TUser>,
IUserClaimStore<TUser>,
IUserRoleStore<TUser>,
IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>,
IQueryableUserStore<TUser>,
IUserEmailStore<TUser>,
IUserPhoneNumberStore<TUser>,
IUserTwoFactorStore<TUser>,
IUserLockoutStore<TUser>
where TKey : IEquatable<TKey>
where TUser : InMemoryUser<TKey, TUserLogin, TUserRole, TUserClaim>
where TRole : IdentityRole<TKey>
where TUserLogin : IdentityUserLogin<TKey>, new()
where TUserRole : IdentityUserRole<TKey>, new()
where TUserClaim : IdentityUserClaim<TKey>, new()
where TContext : DbContext
{
private bool _disposed;
public InMemoryUserStore(TContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
AutoSaveChanges = true;
}
public TContext Context { get; private set; }
/// <summary>
/// If true will call SaveChanges after CreateAsync/UpdateAsync/DeleteAsync
/// </summary>
public bool AutoSaveChanges { get; set; }
private Task SaveChanges(CancellationToken cancellationToken)
{
return AutoSaveChanges ? Context.SaveChangesAsync(cancellationToken) : Task.FromResult(0);
}
protected virtual Task<TUser> GetUserAggregate(Expression<Func<TUser, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(Users.SingleOrDefault(filter));
// TODO: return Users.SingleOrDefaultAsync(filter, cancellationToken);
//Include(u => u.Roles)
//.Include(u => u.Claims)
//.Include(u => u.Logins)
}
public Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(Convert.ToString(user.Id, CultureInfo.InvariantCulture));
}
public Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.UserName);
}
public Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken = new CancellationToken())
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.UserName = userName;
return Task.FromResult(0);
}
public async virtual Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await Context.AddAsync(user, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await Context.UpdateAsync(user, cancellationToken);
await SaveChanges(cancellationToken);
}
public async virtual Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
Context.Delete(user);
await SaveChanges(cancellationToken);
}
public virtual TKey ConvertUserId(string userId)
{
return (TKey)Convert.ChangeType(userId, typeof(TKey));
}
/// <summary>
/// Find a user by id
/// </summary>
/// <param name="userId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var id = ConvertUserId(userId);
return GetUserAggregate(u => u.Id.Equals(id), cancellationToken);
}
/// <summary>
/// Find a user by name
/// </summary>
/// <param name="userName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.UserName.ToUpper() == userName.ToUpper(), cancellationToken);
}
public IQueryable<TUser> Users
{
get { return Context.Set<TUser>(); }
}
public async virtual Task AddLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
var l = new TUserLogin
{
UserId = user.Id,
ProviderKey = login.ProviderKey,
LoginProvider = login.LoginProvider
};
await Context.Set<TUserLogin>().AddAsync(l, cancellationToken);
user.Logins.Add(l);
}
public virtual Task RemoveLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
var provider = login.LoginProvider;
var key = login.ProviderKey;
var entry = user.Logins.SingleOrDefault(l => l.LoginProvider == provider && l.ProviderKey == key);
if (entry != null)
{
user.Logins.Remove(entry);
Context.Set<TUserLogin>().Remove(entry);
}
return Task.FromResult(0);
}
public virtual Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IList<UserLoginInfo> result =
user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey)).ToList();
return Task.FromResult(result);
}
public async virtual Task<TUser> FindByLoginAsync(UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (login == null)
{
throw new ArgumentNullException("login");
}
var provider = login.LoginProvider;
var key = login.ProviderKey;
// TODO: use FirstOrDefaultAsync
var userLogin =
Context.Set<TUserLogin>().FirstOrDefault(l => l.LoginProvider == provider && l.ProviderKey == key);
if (userLogin != null)
{
return await GetUserAggregate(u => u.Id.Equals(userLogin.UserId), cancellationToken);
}
return null;
}
/// <summary>
/// Set the password hash for a user
/// </summary>
/// <param name="user"></param>
/// <param name="passwordHash"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
/// <summary>
/// Get the password hash for a user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PasswordHash);
}
/// <summary>
/// Returns true if the user has a password set
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(user.PasswordHash != null);
}
/// <summary>
/// Return the claims for a user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IList<Claim> result = user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult(result);
}
/// <summary>
/// Add a claim to a user
/// </summary>
/// <param name="user"></param>
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task AddClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
user.Claims.Add(new TUserClaim { UserId = user.Id, ClaimType = claim.Type, ClaimValue = claim.Value });
return Task.FromResult(0);
}
/// <summary>
/// Remove a claim from a user
/// </summary>
/// <param name="user"></param>
/// <param name="claim"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task RemoveClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
var claims =
user.Claims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToList();
foreach (var c in claims)
{
user.Claims.Remove(c);
}
// TODO:these claims might not exist in the dbset
//var query =
// _userClaims.Where(
// uc => uc.UserId.Equals(user.Id) && uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type);
//foreach (var c in query)
//{
// _userClaims.Remove(c);
//}
return Task.FromResult(0);
}
/// <summary>
/// Returns whether the user email is confirmed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetEmailConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.EmailConfirmed);
}
/// <summary>
/// Set IsConfirmed on the user
/// </summary>
/// <param name="user"></param>
/// <param name="confirmed"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
/// <summary>
/// Set the user email
/// </summary>
/// <param name="user"></param>
/// <param name="email"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetEmailAsync(TUser user, string email, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.Email = email;
return Task.FromResult(0);
}
/// <summary>
/// Get the user's email
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetEmailAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.Email);
}
/// <summary>
/// FindByLoginAsync a user by email
/// </summary>
/// <param name="email"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<TUser> FindByEmailAsync(string email, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return Task.FromResult(Users.SingleOrDefault(u => u.Email.ToUpper() == email.ToUpper()));
//return GetUserAggregate(u => u.Email.ToUpper() == email.ToUpper(), cancellationToken);
}
/// <summary>
/// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be considered
/// not locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return
Task.FromResult(user.LockoutEnd.HasValue
? new DateTimeOffset(DateTime.SpecifyKind(user.LockoutEnd.Value, DateTimeKind.Utc))
: new DateTimeOffset());
}
/// <summary>
/// Locks a user out until the specified end date (set to a past date, to unlock a user)
/// </summary>
/// <param name="user"></param>
/// <param name="lockoutEnd"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnd = lockoutEnd == DateTimeOffset.MinValue ? (DateTime?)null : lockoutEnd.UtcDateTime;
return Task.FromResult(0);
}
/// <summary>
/// Used to record when an attempt to access the user has failed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Used to reset the account access count, typically after the account is successfully accessed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
/// <summary>
/// Returns the current number of failed access attempts. This number usually will be reset whenever the password is
/// verified or the account is locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Returns whether the user can be locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.LockoutEnabled);
}
/// <summary>
/// Sets whether the user can be locked out.
/// </summary>
/// <param name="user"></param>
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
/// <summary>
/// Set the user's phone number
/// </summary>
/// <param name="user"></param>
/// <param name="phoneNumber"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumber = phoneNumber;
return Task.FromResult(0);
}
/// <summary>
/// Get a user's phone number
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PhoneNumber);
}
/// <summary>
/// Returns whether the user phoneNumber is confirmed
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.PhoneNumberConfirmed);
}
/// <summary>
/// Set PhoneNumberConfirmed on the user
/// </summary>
/// <param name="user"></param>
/// <param name="confirmed"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumberConfirmed = confirmed;
return Task.FromResult(0);
}
/// <summary>
/// Add a user to a role
/// </summary>
/// <param name="user"></param>
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
// TODO:
//if (String.IsNullOrWhiteSpace(roleName))
//{
// throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
//}
var roleEntity = Context.Set<TRole>().SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
if (roleEntity == null)
{
throw new InvalidOperationException("Role Not Found");
//TODO: String.Format(CultureInfo.CurrentCulture, IdentityResources.RoleNotFound, roleName));
}
var ur = new TUserRole { UserId = user.Id, RoleId = roleEntity.Id };
user.Roles.Add(ur);
roleEntity.Users.Add(ur);
return Task.FromResult(0);
}
/// <summary>
/// Remove a user from a role
/// </summary>
/// <param name="user"></param>
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
//if (String.IsNullOrWhiteSpace(roleName))
//{
// throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
//}
var roleEntity = Context.Set<TRole>().SingleOrDefault(r => r.Name.ToUpper() == roleName.ToUpper());
if (roleEntity != null)
{
var userRole = user.Roles.FirstOrDefault(r => roleEntity.Id.Equals(r.RoleId));
if (userRole != null)
{
user.Roles.Remove(userRole);
roleEntity.Users.Remove(userRole);
}
}
return Task.FromResult(0);
}
/// <summary>
/// Get the names of the roles a user is a member of
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var query = from userRoles in user.Roles
join roles in Context.Set<TRole>()
on userRoles.RoleId equals roles.Id
select roles.Name;
return Task.FromResult<IList<string>>(query.ToList());
}
/// <summary>
/// Returns true if the user is in the named role
/// </summary>
/// <param name="user"></param>
/// <param name="roleName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
//if (String.IsNullOrWhiteSpace(roleName))
//{
// throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
//}
var any =
Context.Set<TRole>().Where(r => r.Name.ToUpper() == roleName.ToUpper())
.Where(r => r.Users.Any(ur => ur.UserId.Equals(user.Id)))
.Count() > 0;
return Task.FromResult(any);
}
/// <summary>
/// Set the security stamp for the user
/// </summary>
/// <param name="user"></param>
/// <param name="stamp"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetSecurityStampAsync(TUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
/// <summary>
/// Get the security stamp for a user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.SecurityStamp);
}
/// <summary>
/// Set whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"></param>
/// <param name="enabled"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.TwoFactorEnabled = enabled;
return Task.FromResult(0);
}
/// <summary>
/// Gets whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult(user.TwoFactorEnabled);
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Dispose the store
/// </summary>
public void Dispose()
{
_disposed = true;
}
}
}

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="__ToolsVersion__" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">12.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>813b36fe-bba5-4449-b157-6ebba5ed02ca</ProjectGuid>
<OutputType>Library</OutputType>
<ActiveTargetFramework>net45</ActiveTargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'" Label="Configuration">
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" Label="Configuration">
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Content Include="project.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="EntityIdentityBuilderExtensions.cs" />
<Compile Include="InMemoryUser.cs" />
<Compile Include="InMemoryContext.cs" />
<Compile Include="InMemoryUserStore.cs" />
<Compile Include="InMemoryUserStoreTest.cs" />
<Compile Include="RoleStoreTest.cs" />
<Compile Include="TestIdentityFactory.cs" />
</ItemGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -0,0 +1,99 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
{
public class RoleStoreTest
{
[Fact]
public async Task CanCreateUsingAddRoleManager()
{
var services = new ServiceCollection();
services.AddEntityFramework().AddInMemoryStore();
var store = new RoleStore<IdentityRole>(new InMemoryContext());
services.AddIdentity<InMemoryUser, IdentityRole>(s =>
{
s.AddRoleStore(() => store);
});
var provider = services.BuildServiceProvider();
var manager = provider.GetService<RoleManager<IdentityRole>>();
Assert.NotNull(manager);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(new IdentityRole("arole")));
}
[Fact]
public async Task CanCreateRoleWithSingletonManager()
{
var services = new ServiceCollection();
services.AddEntityFramework().AddInMemoryStore();
services.AddTransient<InMemoryContext>();
services.AddTransient<IRoleStore<IdentityRole>, RoleStore<IdentityRole, InMemoryContext>>();
services.AddTransient<IRoleValidator<IdentityRole>, RoleValidator<IdentityRole>>();
services.AddSingleton<RoleManager<IdentityRole>>();
var provider = services.BuildServiceProvider();
var manager = provider.GetService<RoleManager<IdentityRole>>();
Assert.NotNull(manager);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(new IdentityRole("someRole")));
}
[Fact]
public async Task RoleStoreMethodsThrowWhenDisposedTest()
{
var store = new RoleStore<IdentityRole>(new InMemoryContext());
store.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.FindByIdAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.FindByNameAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.GetRoleIdAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.GetRoleNameAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.SetRoleNameAsync(null, null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.CreateAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.UpdateAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await store.DeleteAsync(null));
}
[Fact]
public async Task RoleStorePublicNullCheckTest()
{
Assert.Throws<ArgumentNullException>("context", () => new RoleStore<IdentityRole>(null));
var store = new RoleStore<IdentityRole>(new InMemoryContext());
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await store.GetRoleIdAsync(null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await store.GetRoleNameAsync(null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await store.SetRoleNameAsync(null, null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await store.CreateAsync(null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await store.UpdateAsync(null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await store.DeleteAsync(null));
}
[Fact]
public async Task CanUpdateRoleName()
{
var manager = TestIdentityFactory.CreateRoleManager();
var role = new IdentityRole("UpdateRoleName");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
Assert.Null(await manager.FindByNameAsync("New"));
role.Name = "New";
IdentityResultAssert.IsSuccess(await manager.UpdateAsync(role));
Assert.NotNull(await manager.FindByNameAsync("New"));
Assert.Null(await manager.FindByNameAsync("UpdateAsync"));
}
[Fact]
public async Task CanSetUserName()
{
var manager = TestIdentityFactory.CreateRoleManager();
var role = new IdentityRole("UpdateRoleName");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
Assert.Null(await manager.FindByNameAsync("New"));
IdentityResultAssert.IsSuccess(await manager.SetRoleNameAsync(role, "New"));
Assert.NotNull(await manager.FindByNameAsync("New"));
Assert.Null(await manager.FindByNameAsync("UpdateAsync"));
}
}
}

View File

@ -0,0 +1,46 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
{
public static class TestIdentityFactory
{
public static InMemoryContext CreateContext()
{
var services = new ServiceCollection();
services.AddEntityFramework().AddInMemoryStore();
var serviceProvider = services.BuildServiceProvider();
var db = new InMemoryContext(serviceProvider);
db.Database.EnsureCreated();
return db;
}
public static UserManager<InMemoryUser> CreateManager(InMemoryContext context)
{
return MockHelpers.CreateManager<InMemoryUser>(() => new InMemoryUserStore<InMemoryUser>(context));
}
public static UserManager<InMemoryUser> CreateManager()
{
return CreateManager(CreateContext());
}
public static RoleManager<IdentityRole> CreateRoleManager(InMemoryContext context)
{
var services = new ServiceCollection();
services.AddIdentity<InMemoryUser, IdentityRole>(b => b.AddRoleStore(() => new RoleStore<IdentityRole>(context)));
return services.BuildServiceProvider().GetService<RoleManager<IdentityRole>>();
}
public static RoleManager<IdentityRole> CreateRoleManager()
{
return CreateRoleManager(CreateContext());
}
}
}

View File

@ -0,0 +1,30 @@
{
"version": "0.1-alpha-*",
"dependencies": {
"Microsoft.AspNet.Http": "1.0.0-*",
"Microsoft.AspNet.Identity": "",
"Microsoft.AspNet.Identity.EntityFramework": "",
"Microsoft.AspNet.PipelineCore": "1.0.0-*",
"Microsoft.AspNet.RequestContainer": "1.0.0-*",
"Microsoft.AspNet.Security.DataProtection": "1.0.0-*",
"Microsoft.AspNet.Testing": "1.0.0-*",
"EntityFramework.InMemory": "7.0.0-*",
"Microsoft.Framework.OptionsModel" : "1.0.0-*",
"System.Security.Claims": "1.0.0-*",
"Xunit.KRunner": "1.0.0-*"
},
"code": "**\\*.cs;..\\Shared\\*.cs",
"configurations": {
"net451": {
"dependencies": {
"Moq" : "4.2.1312.1622",
"System.Collections": "",
"System.Runtime": ""
}
}
},
"code": "**\\*.cs;..\\Shared\\*.cs",
"commands": {
"test": "Xunit.KRunner"
}
}

View File

@ -21,11 +21,7 @@
<Content Include="project.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="InMemoryUserStoreTest.cs" />
<Compile Include="RoleStoreTest.cs" />
<Compile Include="SqlUserStoreTest.cs" />
<Compile Include="StartupTest.cs" />
<Compile Include="TestIdentityFactory.cs" />
<Compile Include="UserStoreTest.cs" />
</ItemGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
</Project>

View File

@ -1,224 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity.Test;
using Microsoft.Data.Entity;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Microsoft.Framework.OptionsModel;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNet.Identity.Entity.Test
{
public class SqlUserStoreTest
{
private const string ConnectionString = @"Server=(localdb)\v11.0;Database=SqlUserStoreTest;Trusted_Connection=True;";
public class ApplicationUser : User { }
public class ApplicationDbContext : IdentitySqlContext<ApplicationUser>
{
public ApplicationDbContext(IServiceProvider services, IOptionsAccessor<DbContextOptions> options) : base(services, options.Options) { }
}
[TestPriority(0)]
[Fact]
public void RecreateDatabase()
{
CreateContext(true);
}
[Fact]
public async Task EnsureStartupUsageWorks()
{
EnsureDatabase();
IBuilder builder = new Builder.Builder(new ServiceCollection().BuildServiceProvider());
builder.UseServices(services =>
{
services.AddEntityFramework().AddSqlServer();
services.AddIdentity<ApplicationUser>().AddEntityFramework<ApplicationUser, ApplicationDbContext>();
services.SetupOptions<DbContextOptions>(options =>
options.UseSqlServer(ConnectionString));
});
var userStore = builder.ApplicationServices.GetService<IUserStore<ApplicationUser>>();
var userManager = builder.ApplicationServices.GetService<UserManager<ApplicationUser>>();
Assert.NotNull(userStore);
Assert.NotNull(userManager);
const string userName = "admin";
const string password = "1qaz@WSX";
var user = new ApplicationUser { UserName = userName };
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
}
[Fact]
public void CanCreateUserUsingEF()
{
using (var db = CreateContext())
{
var guid = Guid.NewGuid().ToString();
db.Users.Add(new User {Id = guid, UserName = guid});
db.SaveChanges();
Assert.True(db.Users.Any(u => u.UserName == guid));
Assert.NotNull(db.Users.FirstOrDefault(u => u.UserName == guid));
}
}
public static IdentitySqlContext CreateContext(bool delete = false)
{
var services = new ServiceCollection();
services.AddEntityFramework().AddSqlServer();
var serviceProvider = services.BuildServiceProvider();
var db = new IdentitySqlContext(serviceProvider, ConnectionString);
if (delete)
{
db.Database.EnsureDeleted();
}
db.Database.EnsureCreated();
return db;
}
public static void EnsureDatabase()
{
CreateContext();
}
public static ApplicationDbContext CreateAppContext()
{
CreateContext();
var services = new ServiceCollection();
services.AddEntityFramework().AddSqlServer();
services.Add(OptionsServices.GetDefaultServices());
var serviceProvider = services.BuildServiceProvider();
var db = new ApplicationDbContext(serviceProvider, serviceProvider.GetService<IOptionsAccessor<DbContextOptions>>());
db.Database.EnsureCreated();
return db;
}
public static UserManager<User> CreateManager(DbContext context)
{
return MockHelpers.CreateManager(() => new UserStore<User>(context));
}
public static UserManager<User> CreateManager()
{
return CreateManager(CreateContext());
}
[Fact]
public async Task CanCreateUsingManager()
{
var manager = CreateManager();
var guid = Guid.NewGuid().ToString();
var user = new User { UserName = "New"+guid };
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
[Fact]
public async Task CanDeleteUser()
{
var manager = CreateManager();
var user = new User("DeleteAsync");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
Assert.Null(await manager.FindByIdAsync(user.Id));
}
[Fact]
public async Task CanUpdateUserName()
{
var manager = CreateManager();
var oldName = Guid.NewGuid().ToString();
var user = new User(oldName);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
var newName = Guid.NewGuid().ToString();
user.UserName = newName;
IdentityResultAssert.IsSuccess(await manager.UpdateAsync(user));
Assert.NotNull(await manager.FindByNameAsync(newName));
Assert.Null(await manager.FindByNameAsync(oldName));
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
[Fact]
public async Task CanSetUserName()
{
var manager = CreateManager();
var oldName = Guid.NewGuid().ToString();
var user = new User(oldName);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
var newName = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager.SetUserNameAsync(user, newName));
Assert.NotNull(await manager.FindByNameAsync(newName));
Assert.Null(await manager.FindByNameAsync(oldName));
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
[Fact]
public async Task CanChangePassword()
{
var manager = CreateManager();
var user = new User("ChangePasswordTest");
const string password = "password";
const string newPassword = "newpassword";
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, password));
//Assert.Equal(manager.Users.Count(), 1);
//var stamp = user.SecurityStamp;
//Assert.NotNull(stamp);
IdentityResultAssert.IsSuccess(await manager.ChangePasswordAsync(user, password, newPassword));
Assert.Null(await manager.FindByUserNamePasswordAsync(user.UserName, password));
Assert.Equal(user, await manager.FindByUserNamePasswordAsync(user.UserName, newPassword));
//Assert.NotEqual(stamp, user.SecurityStamp);
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
[Fact]
public async Task ClaimsIdentityCreatesExpectedClaims()
{
var manager = CreateManager();
//var role = TestIdentityFactory.CreateRoleManager(context);
var user = new User("Hao");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
//IdentityResultAssert.IsSuccess(await role.CreateAsync(new EntityRole("Admin")));
//IdentityResultAssert.IsSuccess(await role.CreateAsync(new EntityRole("Local")));
//IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(user, "Admin"));
//IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(user, "Local"));
Claim[] userClaims =
{
new Claim("Whatever", "Value"),
new Claim("Whatever2", "Value2")
};
foreach (var c in userClaims)
{
IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c));
}
var identity = await manager.CreateIdentityAsync(user, "test");
var claimsFactory = (ClaimsIdentityFactory<User>)manager.ClaimsIdentityFactory;
Assert.NotNull(claimsFactory);
var claims = identity.Claims.ToList();
Assert.NotNull(claims);
Assert.True(
claims.Any(c => c.Type == manager.Options.ClaimType.UserName && c.Value == user.UserName));
Assert.True(claims.Any(c => c.Type == manager.Options.ClaimType.UserId && c.Value == user.Id.ToString()));
//Assert.True(claims.Any(c => c.Type == manager.Options.ClaimType.Role && c.Value == "Admin"));
//Assert.True(claims.Any(c => c.Type == manager.Options.ClaimType.Role && c.Value == "Local"));
foreach (var cl in userClaims)
{
Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
}
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
}
}

View File

@ -1,77 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Microsoft.Framework.OptionsModel;
using System;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNet.Identity.Entity.Test
{
public class StartupTest
{
public class ApplicationUser : EntityUser { }
public class ApplicationDbContext : IdentityContext<ApplicationUser>
{
public ApplicationDbContext(IServiceProvider services) : base(services) { }
}
[Fact]
public async Task EnsureStartupUsageWorks()
{
EnsureDatabase();
IBuilder builder = new Builder.Builder(new ServiceCollection().BuildServiceProvider());
builder.UseServices(services =>
{
services.AddEntityFramework().AddInMemoryStore();
services.AddIdentity<ApplicationUser, EntityRole>(s =>
{
s.AddEntityFrameworkInMemory<ApplicationUser, EntityRole, ApplicationDbContext>();
});
});
var userStore = builder.ApplicationServices.GetService<IUserStore<ApplicationUser>>();
var roleStore = builder.ApplicationServices.GetService<IRoleStore<EntityRole>>();
var userManager = builder.ApplicationServices.GetService<UserManager<ApplicationUser>>();
var roleManager = builder.ApplicationServices.GetService<RoleManager<EntityRole>>();
Assert.NotNull(userStore);
Assert.NotNull(userManager);
Assert.NotNull(roleStore);
Assert.NotNull(roleManager);
await CreateAdminUser(builder.ApplicationServices);
}
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
{
const string userName = "admin";
const string roleName = "Admins";
const string password = "1qaz@WSX";
var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
var roleManager = serviceProvider.GetService<RoleManager<EntityRole>>();
var user = new ApplicationUser { UserName = userName };
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(new EntityRole { Name = roleName }));
IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(user, roleName));
}
public static void EnsureDatabase()
{
var services = new ServiceCollection();
services.AddEntityFramework().AddInMemoryStore();
var serviceProvider = services.BuildServiceProvider();
var db = new ApplicationDbContext(serviceProvider);
db.Database.EnsureCreated();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Identity.InMemory;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity
{
public static class IdentityBuilderExtensions
{
public static IdentityBuilder<TUser, TRole> AddInMemory<TUser, TRole>(this IdentityBuilder<TUser, TRole> builder)
where TUser : IdentityUser
where TRole : IdentityRole
{
builder.Services.AddSingleton<IUserStore<TUser>, InMemoryUserStore<TUser>>();
builder.Services.AddScoped<UserManager<TUser>, UserManager<TUser>>();
builder.Services.AddSingleton<IRoleStore<TRole>, InMemoryRoleStore<TRole>>();
builder.Services.AddScoped<RoleManager<TRole>, RoleManager<TRole>>();
return builder;
}
}
}

View File

@ -0,0 +1,105 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity.InMemory
{
public class InMemoryRoleStore<TRole> : IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : IdentityRole
{
private readonly Dictionary<string, TRole> _roles = new Dictionary<string, TRole>();
public Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
_roles[role.Id] = role;
return Task.FromResult(0);
}
public Task DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null || !_roles.ContainsKey(role.Id))
{
throw new InvalidOperationException("Unknown role");
}
_roles.Remove(role.Id);
return Task.FromResult(0);
}
public Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken = new CancellationToken())
{
return Task.FromResult(role.Id);
}
public Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken = new CancellationToken())
{
return Task.FromResult(role.Name);
}
public Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken = new CancellationToken())
{
role.Name = roleName;
return Task.FromResult(0);
}
public Task UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
_roles[role.Id] = role;
return Task.FromResult(0);
}
public Task<TRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken))
{
if (_roles.ContainsKey(roleId))
{
return Task.FromResult(_roles[roleId]);
}
return Task.FromResult<TRole>(null);
}
public Task<TRole> FindByNameAsync(string roleName, CancellationToken cancellationToken = default(CancellationToken))
{
return
Task.FromResult(
Roles.SingleOrDefault(r => String.Equals(r.Name, roleName, StringComparison.OrdinalIgnoreCase)));
}
public void Dispose()
{
}
public Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
var claims = role.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult<IList<Claim>>(claims);
}
public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = claim.Type, ClaimValue = claim.Value, RoleId = role.Id });
return Task.FromResult(0);
}
public Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
var entity =
role.Claims.FirstOrDefault(
ur => ur.RoleId == role.Id && ur.ClaimType == claim.Type && ur.ClaimValue == claim.Value);
if (entity != null)
{
role.Claims.Remove(entity);
}
return Task.FromResult(0);
}
public IQueryable<TRole> Roles
{
get { return _roles.Values.AsQueryable(); }
}
}
}

View File

@ -0,0 +1,329 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNet.Identity.InMemory
{
public class InMemoryUserStore<TUser> :
IUserLoginStore<TUser>,
IUserRoleStore<TUser>,
IUserClaimStore<TUser>,
IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserEmailStore<TUser>,
IUserLockoutStore<TUser>,
IUserPhoneNumberStore<TUser>,
IQueryableUserStore<TUser>,
IUserTwoFactorStore<TUser>
where TUser : IdentityUser
{
private readonly Dictionary<UserLoginInfo, TUser> _logins =
new Dictionary<UserLoginInfo, TUser>(new LoginComparer());
private readonly Dictionary<string, TUser> _users = new Dictionary<string, TUser>();
public IQueryable<TUser> Users
{
get { return _users.Values.AsQueryable(); }
}
public Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
var claims = user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
return Task.FromResult<IList<Claim>>(claims);
}
public Task AddClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
user.Claims.Add(new IdentityUserClaim<string> { ClaimType = claim.Type, ClaimValue = claim.Value, UserId = user.Id });
return Task.FromResult(0);
}
public Task RemoveClaimAsync(TUser user, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
var entity =
user.Claims.FirstOrDefault(
uc => uc.UserId == user.Id && uc.ClaimType == claim.Type && uc.ClaimValue == claim.Value);
if (entity != null)
{
user.Claims.Remove(entity);
}
return Task.FromResult(0);
}
public Task SetEmailAsync(TUser user, string email, CancellationToken cancellationToken = default(CancellationToken))
{
user.Email = email;
return Task.FromResult(0);
}
public Task<string> GetEmailAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.Email);
}
public Task<bool> GetEmailConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.EmailConfirmed);
}
public Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
user.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
public Task<TUser> FindByEmailAsync(string email, CancellationToken cancellationToken = default(CancellationToken))
{
return
Task.FromResult(
Users.FirstOrDefault(u => String.Equals(u.Email, email, StringComparison.OrdinalIgnoreCase)));
}
public Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.LockoutEnd);
}
public Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd, CancellationToken cancellationToken = default(CancellationToken))
{
user.LockoutEnd = lockoutEnd;
return Task.FromResult(0);
}
public Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
public Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
public Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.AccessFailedCount);
}
public Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.LockoutEnabled);
}
public Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
public Task AddLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
user.Logins.Add(new IdentityUserLogin<string>
{
UserId = user.Id,
LoginProvider = login.LoginProvider,
ProviderKey = login.ProviderKey
});
_logins[login] = user;
return Task.FromResult(0);
}
public Task RemoveLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
var loginEntity =
user.Logins.SingleOrDefault(
l =>
l.ProviderKey == login.ProviderKey && l.LoginProvider == login.LoginProvider &&
l.UserId == user.Id);
if (loginEntity != null)
{
user.Logins.Remove(loginEntity);
}
_logins[login] = null;
return Task.FromResult(0);
}
public Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
var logins = user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey)).ToList();
return Task.FromResult<IList<UserLoginInfo>>(logins);
}
public Task<TUser> FindByLoginAsync(UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
if (_logins.ContainsKey(login))
{
return Task.FromResult(_logins[login]);
}
return Task.FromResult<TUser>(null);
}
public Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
return Task.FromResult(user.Id);
}
public Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken = new CancellationToken())
{
return Task.FromResult(user.UserName);
}
public Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken = new CancellationToken())
{
user.UserName = userName;
return Task.FromResult(0);
}
public Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
_users[user.Id] = user;
return Task.FromResult(0);
}
public Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
_users[user.Id] = user;
return Task.FromResult(0);
}
public Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
if (_users.ContainsKey(userId))
{
return Task.FromResult(_users[userId]);
}
return Task.FromResult<TUser>(null);
}
public void Dispose()
{
}
public Task<TUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
{
return
Task.FromResult(
Users.FirstOrDefault(u => String.Equals(u.UserName, userName, StringComparison.OrdinalIgnoreCase)));
}
public Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
if (user == null || !_users.ContainsKey(user.Id))
{
throw new InvalidOperationException("Unknown user");
}
_users.Remove(user.Id);
return Task.FromResult(0);
}
public Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken))
{
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
public Task<string> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.PasswordHash != null);
}
public Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken))
{
user.PhoneNumber = phoneNumber;
return Task.FromResult(0);
}
public Task<string> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.PhoneNumber);
}
public Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.PhoneNumberConfirmed);
}
public Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
user.PhoneNumberConfirmed = confirmed;
return Task.FromResult(0);
}
// RoleId == roleName for InMemory
public Task AddToRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
{
user.Roles.Add(new IdentityUserRole<string> { RoleId = role, UserId = user.Id });
return Task.FromResult(0);
}
// RoleId == roleName for InMemory
public Task RemoveFromRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
{
var roleEntity = user.Roles.SingleOrDefault(ur => ur.RoleId == role);
if (roleEntity != null)
{
user.Roles.Remove(roleEntity);
}
return Task.FromResult(0);
}
public Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult<IList<string>>(user.Roles.Select(ur => ur.RoleId).ToList());
}
public Task<bool> IsInRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.Roles.Any(ur => ur.RoleId == role));
}
public Task SetSecurityStampAsync(TUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken))
{
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
public Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.SecurityStamp);
}
public Task SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
user.TwoFactorEnabled = enabled;
return Task.FromResult(0);
}
public Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult(user.TwoFactorEnabled);
}
private class LoginComparer : IEqualityComparer<UserLoginInfo>
{
public bool Equals(UserLoginInfo x, UserLoginInfo y)
{
return x.LoginProvider == y.LoginProvider && x.ProviderKey == y.ProviderKey;
}
public int GetHashCode(UserLoginInfo obj)
{
return (obj.ProviderKey + "--" + obj.LoginProvider).GetHashCode();
}
}
}
}

View File

@ -21,8 +21,11 @@
<Content Include="project.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="IdentityBuilderExtensions.cs" />
<Compile Include="InMemoryRoleStore.cs" />
<Compile Include="InMemoryStoreTest.cs" />
<Compile Include="InMemoryUserStore.cs" />
<Compile Include="StartupTest.cs" />
</ItemGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
</Project>

View File

@ -2,7 +2,6 @@
"dependencies": {
"Microsoft.AspNet.Http" : "1.0.0-*",
"Microsoft.AspNet.Identity" : "",
"Microsoft.AspNet.Identity.InMemory" : "",
"Microsoft.AspNet.PipelineCore" : "1.0.0-*",
"Microsoft.AspNet.RequestContainer" : "1.0.0-*",
"Microsoft.AspNet.Testing" : "1.0.0-*",

View File

@ -6,8 +6,6 @@ using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Moq;
using Xunit;
@ -18,43 +16,64 @@ namespace Microsoft.AspNet.Identity.Test
[Fact]
public async Task CreateIdentityNullChecks()
{
var factory = new ClaimsIdentityFactory<TestUser>();
var manager = MockHelpers.MockUserManager<TestUser>().Object;
await Assert.ThrowsAsync<ArgumentNullException>("manager",
async () => await factory.CreateAsync(null, null, "whatever"));
var userManager = MockHelpers.MockUserManager<TestUser>().Object;
var roleManager = MockHelpers.MockRoleManager<TestRole>().Object;
var factory = new ClaimsIdentityFactory<TestUser, TestRole>(userManager, roleManager);
await Assert.ThrowsAsync<ArgumentNullException>("user",
async () => await factory.CreateAsync(manager, null, "whatever"));
async () => await factory.CreateAsync(null, "whatever"));
await Assert.ThrowsAsync<ArgumentNullException>("value",
async () => await factory.CreateAsync(manager, new TestUser(), null));
async () => await factory.CreateAsync(new TestUser(), null));
}
#if NET45
//TODO: Mock fails in K (this works fine in net45)
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims)
[InlineData(false, false, false)]
[InlineData(false, true, false)]
[InlineData(true, false, false)]
[InlineData(true, true, false)]
[InlineData(true, false, true)]
[InlineData(true, true, true)]
public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims)
{
// Setup
var userManager = MockHelpers.MockUserManager<TestUser>();
var roleManager = MockHelpers.MockRoleManager<TestRole>();
var user = new TestUser { UserName = "Foo" };
userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles);
userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims);
userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles);
userManager.Setup(m => m.GetUserIdAsync(user, CancellationToken.None)).ReturnsAsync(user.Id);
userManager.Setup(m => m.GetUserNameAsync(user, CancellationToken.None)).ReturnsAsync(user.UserName);
var roleClaims = new[] { "Admin", "Local" };
userManager.Setup(m => m.GetRolesAsync(user, CancellationToken.None)).ReturnsAsync(roleClaims);
var roleClaims = new[] { "Admin", "Local" };
if (supportRoles)
{
userManager.Setup(m => m.GetRolesAsync(user, CancellationToken.None)).ReturnsAsync(roleClaims);
roleManager.Setup(m => m.SupportsRoleClaims).Returns(supportRoleClaims);
}
var userClaims = new[] { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") };
userManager.Setup(m => m.GetClaimsAsync(user, CancellationToken.None)).ReturnsAsync(userClaims);
if (supportClaims)
{
userManager.Setup(m => m.GetClaimsAsync(user, CancellationToken.None)).ReturnsAsync(userClaims);
}
userManager.Object.Options = new IdentityOptions();
var admin = new TestRole() { Name = "Admin" };
var local = new TestRole() { Name = "Local" };
var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") };
var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") };
if (supportRoleClaims)
{
roleManager.Setup(m => m.FindByNameAsync("Admin", CancellationToken.None)).ReturnsAsync(admin);
roleManager.Setup(m => m.FindByNameAsync("Local", CancellationToken.None)).ReturnsAsync(local);
roleManager.Setup(m => m.GetClaimsAsync(admin, CancellationToken.None)).ReturnsAsync(adminClaims);
roleManager.Setup(m => m.GetClaimsAsync(local, CancellationToken.None)).ReturnsAsync(localClaims);
}
const string authType = "Microsoft.AspNet.Identity";
var factory = new ClaimsIdentityFactory<TestUser>();
var factory = new ClaimsIdentityFactory<TestUser, TestRole>(userManager.Object, roleManager.Object);
// Act
var identity = await factory.CreateAsync(userManager.Object, user, authType);
var identity = await factory.CreateAsync(user, authType);
// Assert
var manager = userManager.Object;
@ -71,6 +90,16 @@ namespace Microsoft.AspNet.Identity.Test
{
Assert.Equal(supportClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
}
foreach (var cl in adminClaims)
{
Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
}
foreach (var cl in localClaims)
{
Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
}
userManager.VerifyAll();
roleManager.VerifyAll();
}
#endif
}

View File

@ -34,12 +34,6 @@ namespace Microsoft.AspNet.Identity.Test
CanOverride<IPasswordHasher>(new PasswordHasher());
}
[Fact]
public void CanSpecifyClaimsIdentityFactoryInstance()
{
CanOverride<IClaimsIdentityFactory<IdentityUser>>(new ClaimsIdentityFactory<IdentityUser>());
}
[Fact]
public void EnsureDefaultServices()
{
@ -55,9 +49,6 @@ namespace Microsoft.AspNet.Identity.Test
var hasher = provider.GetService<IPasswordHasher>() as PasswordHasher;
Assert.NotNull(hasher);
var claimsFactory = provider.GetService<IClaimsIdentityFactory<IdentityUser>>() as ClaimsIdentityFactory<IdentityUser>;
Assert.NotNull(claimsFactory);
}
private static void CanOverride<TService>(TService instance)

View File

@ -23,8 +23,8 @@ namespace Microsoft.AspNet.Identity.Test
public TestManager(IUserStore<TestUser> store, IOptionsAccessor<IdentityOptions> optionsAccessor,
IPasswordHasher passwordHasher, IUserValidator<TestUser> userValidator,
IPasswordValidator<TestUser> passwordValidator, IClaimsIdentityFactory<TestUser> claimsIdentityFactory)
: base(store, optionsAccessor, passwordHasher, userValidator, passwordValidator, claimsIdentityFactory) { }
IPasswordValidator<TestUser> passwordValidator)
: base(store, optionsAccessor, passwordHasher, userValidator, passwordValidator) { }
}
[Fact]
@ -426,29 +426,18 @@ namespace Microsoft.AspNet.Identity.Test
var passwordHasher = new PasswordHasher();
var userValidator = new UserValidator<TestUser>();
var passwordValidator = new PasswordValidator<TestUser>();
var claimsIdentityFactory = new ClaimsIdentityFactory<TestUser>();
Assert.Throws<ArgumentNullException>("store",
() => new UserManager<TestUser>(null, null, null, null, null, null));
() => new UserManager<TestUser>(null, null, null, null, null));
Assert.Throws<ArgumentNullException>("optionsAccessor",
() => new UserManager<TestUser>(store, null, null, null, null, null));
() => new UserManager<TestUser>(store, null, null, null, null));
Assert.Throws<ArgumentNullException>("passwordHasher",
() => new UserManager<TestUser>(store, optionsAccessor, null, null, null, null));
Assert.Throws<ArgumentNullException>("userValidator",
() => new UserManager<TestUser>(store, optionsAccessor, passwordHasher, null, null, null));
Assert.Throws<ArgumentNullException>("passwordValidator",
() => new UserManager<TestUser>(store, optionsAccessor, passwordHasher, userValidator, null, null));
Assert.Throws<ArgumentNullException>("claimsIdentityFactory",
() => new UserManager<TestUser>(store, optionsAccessor, passwordHasher, userValidator, passwordValidator, null));
() => new UserManager<TestUser>(store, optionsAccessor, null, null, null));
var manager = new UserManager<TestUser>(store, optionsAccessor, passwordHasher, userValidator, passwordValidator, claimsIdentityFactory);
var manager = new UserManager<TestUser>(store, optionsAccessor, passwordHasher, userValidator, passwordValidator);
Assert.Throws<ArgumentNullException>("value", () => manager.ClaimsIdentityFactory = null);
Assert.Throws<ArgumentNullException>("value", () => manager.PasswordHasher = null);
Assert.Throws<ArgumentNullException>("value", () => manager.Options = null);
await
Assert.ThrowsAsync<ArgumentNullException>("user",
async () => await manager.CreateIdentityAsync(null, "whatever"));
await Assert.ThrowsAsync<ArgumentNullException>("user", async () => await manager.CreateAsync(null));
await Assert.ThrowsAsync<ArgumentNullException>("user", async () => await manager.CreateAsync(null, null));
await
@ -580,7 +569,6 @@ namespace Microsoft.AspNet.Identity.Test
{
var manager = MockHelpers.TestUserManager(new NoopUserStore());
manager.Dispose();
Assert.Throws<ObjectDisposedException>(() => manager.ClaimsIdentityFactory);
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.AddClaimAsync(null, null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.AddLoginAsync(null, null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.AddPasswordAsync(null, null));
@ -603,7 +591,6 @@ namespace Microsoft.AspNet.Identity.Test
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.FindByNameAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.CreateAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.CreateAsync(null, null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.CreateIdentityAsync(null, null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.UpdateAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.DeleteAsync(null));
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.UpdateSecurityStampAsync(null));

View File

@ -10,8 +10,8 @@ namespace Microsoft.AspNet.Identity.Test
{
public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptionsAccessor<IdentityOptions> options,
IPasswordHasher passwordHasher, IUserValidator<ApplicationUser> userValidator,
IPasswordValidator<ApplicationUser> passwordValidator, IClaimsIdentityFactory<ApplicationUser> claimsIdentityFactory)
: base(store, options, passwordHasher, userValidator, passwordValidator, claimsIdentityFactory) { }
IPasswordValidator<ApplicationUser> passwordValidator)
: base(store, options, passwordHasher, userValidator, passwordValidator) { }
}
public class ApplicationRoleManager : RoleManager<IdentityRole>

View File

@ -33,7 +33,13 @@ namespace Microsoft.AspNet.Identity.Test
{
var store = new Mock<IUserStore<TUser>>();
var options = new OptionsAccessor<IdentityOptions>(null);
return new Mock<UserManager<TUser>>(store.Object, options, new PasswordHasher(), new UserValidator<TUser>(), new PasswordValidator<TUser>(), new ClaimsIdentityFactory<TUser>());
return new Mock<UserManager<TUser>>(store.Object, options, new PasswordHasher(), new UserValidator<TUser>(), new PasswordValidator<TUser>());
}
public static Mock<RoleManager<TRole>> MockRoleManager<TRole>() where TRole : class
{
var store = new Mock<IRoleStore<TRole>>();
return new Mock<RoleManager<TRole>>(store.Object, new RoleValidator<TRole>());
}
public static UserManager<TUser> TestUserManager<TUser>() where TUser : class
@ -45,7 +51,7 @@ namespace Microsoft.AspNet.Identity.Test
{
var options = new OptionsAccessor<IdentityOptions>(null);
var validator = new Mock<UserValidator<TUser>>();
var userManager = new UserManager<TUser>(store, options, new PasswordHasher(), validator.Object, new PasswordValidator<TUser>(), new ClaimsIdentityFactory<TUser>());
var userManager = new UserManager<TUser>(store, options, new PasswordHasher(), validator.Object, new PasswordValidator<TUser>());
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>(), CancellationToken.None)).Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
return userManager;
}

View File

@ -7,7 +7,6 @@ using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Testing;
using Microsoft.Framework.OptionsModel;
using Xunit;
namespace Microsoft.AspNet.Identity.Test
@ -61,6 +60,19 @@ namespace Microsoft.AspNet.Identity.Test
Assert.Null(await manager.FindByNameAsync("UpdateAsync"));
}
[Fact]
public async Task CanUpdatePasswordUsingHasher()
{
var manager = CreateManager();
var user = new TUser() { UserName = "UpdatePassword" };
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "password"));
Assert.True(await manager.CheckPasswordAsync(user, "password"));
user.PasswordHash = manager.PasswordHasher.HashPassword("New");
IdentityResultAssert.IsSuccess(await manager.UpdateAsync(user));
Assert.False(await manager.CheckPasswordAsync(user, "password"));
Assert.True(await manager.CheckPasswordAsync(user, "New"));
}
[Fact]
public async Task CanFindById()
{
@ -397,9 +409,8 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c));
}
var identity = await manager.CreateIdentityAsync(user, "test");
var claimsFactory = (ClaimsIdentityFactory<TUser>)manager.ClaimsIdentityFactory;
Assert.NotNull(claimsFactory);
var claimsFactory = new ClaimsIdentityFactory<TUser, TRole>(manager, role);
var identity = await claimsFactory.CreateAsync(user, "test");
var claims = identity.Claims.ToList();
Assert.NotNull(claims);
Assert.True(
@ -805,6 +816,30 @@ namespace Microsoft.AspNet.Identity.Test
Assert.False(await manager.RoleExistsAsync(role.Name));
}
[Fact]
public async Task CanAddRemoveRoleClaim()
{
var manager = CreateRoleManager();
var role = CreateRole("ClaimsAddRemove");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
Claim[] claims = { new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3") };
foreach (Claim c in claims)
{
IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(role, c));
}
var roleClaims = await manager.GetClaimsAsync(role);
Assert.Equal(3, roleClaims.Count);
IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[0]));
roleClaims = await manager.GetClaimsAsync(role);
Assert.Equal(2, roleClaims.Count);
IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[1]));
roleClaims = await manager.GetClaimsAsync(role);
Assert.Equal(1, roleClaims.Count);
IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[2]));
roleClaims = await manager.GetClaimsAsync(role);
Assert.Equal(0, roleClaims.Count);
}
[Fact]
public async Task CanRoleFindByIdTest()
{
@ -968,7 +1003,6 @@ namespace Microsoft.AspNet.Identity.Test
}
}
[Fact]
public async Task RemoveUserFromRoleWithMultipleRoles()
{