اعمال تزریق وابستگیها به مثال رسمی ASP.NET Identity
نویسنده: وحید نصیری
تاریخ: ۱۳۹۳/۰۹/۲۹ ۱۳:۳۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNet.Identity.EntityFramework;
namespace AspNetIdentityDependencyInjectionSample.DomainClasses
{
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
// سایر خواص اضافی در اینجا
[ForeignKey("AddressId")]
public virtual Address Address { get; set; }
public int? AddressId { get; set; }
}
}
using System.Collections.Generic;
namespace AspNetIdentityDependencyInjectionSample.DomainClasses
{
public class Address
{
public int Id { get; set; }
public string City { get; set; }
public string State { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { set; get; }
}
}
using Microsoft.AspNet.Identity.EntityFramework;
namespace AspNetIdentityDependencyInjectionSample.DomainClasses
{
public class CustomRole : IdentityRole<int, CustomUserRole>
{
public CustomRole() { }
public CustomRole(string name) { Name = name; }
}
}
using Microsoft.AspNet.Identity.EntityFramework;
namespace AspNetIdentityDependencyInjectionSample.DomainClasses
{
public class CustomUserClaim : IdentityUserClaim<int>
{
}
}
using Microsoft.AspNet.Identity.EntityFramework;
namespace AspNetIdentityDependencyInjectionSample.DomainClasses
{
public class CustomUserLogin : IdentityUserLogin<int>
{
}
}
using Microsoft.AspNet.Identity.EntityFramework;
namespace AspNetIdentityDependencyInjectionSample.DomainClasses
{
public class CustomUserRole : IdentityUserRole<int>
{
}
} public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
using System.Collections.Generic;
using System.Data.Entity;
namespace AspNetIdentityDependencyInjectionSample.DataLayer.Context
{
public interface IUnitOfWork
{
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveAllChanges();
void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class;
IList<T> GetRows<T>(string sql, params object[] parameters) where T : class;
IEnumerable<TEntity> AddThisRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;
void ForceDatabaseInitialize();
}
} public class ApplicationDbContext :
IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>,
IUnitOfWork
{
public DbSet<Category> Categories { set; get; }
public DbSet<Product> Products { set; get; }
public DbSet<Address> Addresses { set; get; } public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
using System.Data.Entity.Migrations;
namespace AspNetIdentityDependencyInjectionSample.DataLayer.Context
{
public class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
} using System;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNetIdentityDependencyInjectionSample.DomainClasses;
using AspNetIdentityDependencyInjectionSample.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
namespace AspNetIdentityDependencyInjectionSample.ServiceLayer
{
public class ApplicationUserManager
: UserManager<ApplicationUser, int>, IApplicationUserManager
{
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly IIdentityMessageService _emailService;
private readonly IApplicationRoleManager _roleManager;
private readonly IIdentityMessageService _smsService;
private readonly IUserStore<ApplicationUser, int> _store;
public ApplicationUserManager(IUserStore<ApplicationUser, int> store,
IApplicationRoleManager roleManager,
IDataProtectionProvider dataProtectionProvider,
IIdentityMessageService smsService,
IIdentityMessageService emailService)
: base(store)
{
_store = store;
_roleManager = roleManager;
_dataProtectionProvider = dataProtectionProvider;
_smsService = smsService;
_emailService = emailService;
createApplicationUserManager();
}
public void SeedDatabase()
{
}
private void createApplicationUserManager()
{
// Configure validation logic for usernames
this.UserValidator = new UserValidator<ApplicationUser, int>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
this.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
this.UserLockoutEnabledByDefault = true;
this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
this.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
this.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser, int>
{
MessageFormat = "Your security code is: {0}"
});
this.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser, int>
{
Subject = "SecurityCode",
BodyFormat = "Your security code is {0}"
});
this.EmailService = _emailService;
this.SmsService = _smsService;
if (_dataProtectionProvider != null)
{
var dataProtector = _dataProtectionProvider.Create("ASP.NET Identity");
this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtector);
}
}
}
} using AspNetIdentityDependencyInjectionSample.DomainClasses;
using AspNetIdentityDependencyInjectionSample.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
namespace AspNetIdentityDependencyInjectionSample.ServiceLayer
{
public class ApplicationSignInManager :
SignInManager<ApplicationUser, int>, IApplicationSignInManager
{
private readonly ApplicationUserManager _userManager;
private readonly IAuthenticationManager _authenticationManager;
public ApplicationSignInManager(ApplicationUserManager userManager,
IAuthenticationManager authenticationManager) :
base(userManager, authenticationManager)
{
_userManager = userManager;
_authenticationManager = authenticationManager;
}
}
} using AspNetIdentityDependencyInjectionSample.DomainClasses;
using AspNetIdentityDependencyInjectionSample.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity;
namespace AspNetIdentityDependencyInjectionSample.ServiceLayer
{
public class ApplicationRoleManager : RoleManager<CustomRole, int>, IApplicationRoleManager
{
private readonly IRoleStore<CustomRole, int> _roleStore;
public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
: base(roleStore)
{
_roleStore = roleStore;
}
public CustomRole FindRoleByName(string roleName)
{
return this.FindByName(roleName); // RoleManagerExtensions
}
public IdentityResult CreateRole(CustomRole role)
{
return this.Create(role); // RoleManagerExtensions
}
}
} using System;
using System.Data.Entity;
using System.Threading;
using System.Web;
using AspNetIdentityDependencyInjectionSample.DataLayer.Context;
using AspNetIdentityDependencyInjectionSample.DomainClasses;
using AspNetIdentityDependencyInjectionSample.ServiceLayer;
using AspNetIdentityDependencyInjectionSample.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using StructureMap;
using StructureMap.Web;
namespace AspNetIdentityDependencyInjectionSample.IocConfig
{
public static class SmObjectFactory
{
private static readonly Lazy<Container> _containerBuilder =
new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
private static Container defaultContainer()
{
return new Container(ioc =>
{
ioc.For<IUnitOfWork>()
.HybridHttpOrThreadLocalScoped()
.Use<ApplicationDbContext>();
ioc.For<ApplicationDbContext>().HybridHttpOrThreadLocalScoped().Use<ApplicationDbContext>();
ioc.For<DbContext>().HybridHttpOrThreadLocalScoped().Use<ApplicationDbContext>();
ioc.For<IUserStore<ApplicationUser, int>>()
.HybridHttpOrThreadLocalScoped()
.Use<UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>>();
ioc.For<IRoleStore<CustomRole, int>>()
.HybridHttpOrThreadLocalScoped()
.Use<RoleStore<CustomRole, int, CustomUserRole>>();
ioc.For<IAuthenticationManager>()
.Use(() => HttpContext.Current.GetOwinContext().Authentication);
ioc.For<IApplicationSignInManager>()
.HybridHttpOrThreadLocalScoped()
.Use<ApplicationSignInManager>();
ioc.For<IApplicationUserManager>()
.HybridHttpOrThreadLocalScoped()
.Use<ApplicationUserManager>();
ioc.For<IApplicationRoleManager>()
.HybridHttpOrThreadLocalScoped()
.Use<ApplicationRoleManager>();
ioc.For<IIdentityMessageService>().Use<SmsService>();
ioc.For<IIdentityMessageService>().Use<EmailService>();
ioc.For<ICustomRoleStore>()
.HybridHttpOrThreadLocalScoped()
.Use<CustomRoleStore>();
ioc.For<ICustomUserStore>()
.HybridHttpOrThreadLocalScoped()
.Use<CustomUserStore>();
//config.For<IDataProtectionProvider>().Use(()=> app.GetDataProtectionProvider()); // In Startup class
ioc.For<ICategoryService>().Use<EfCategoryService>();
ioc.For<IProductService>().Use<EfProductService>();
});
}
}
} using System;
using AspNetIdentityDependencyInjectionSample.IocConfig;
using AspNetIdentityDependencyInjectionSample.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Owin;
using StructureMap.Web;
namespace AspNetIdentityDependencyInjectionSample
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
configureAuth(app);
}
private static void configureAuth(IAppBuilder app)
{
SmObjectFactory.Container.Configure(config =>
{
config.For<IDataProtectionProvider>()
.HybridHttpOrThreadLocalScoped()
.Use(()=> app.GetDataProtectionProvider());
});
SmObjectFactory.Container.GetInstance<IApplicationUserManager>().SeedDatabase();
// Configure the db context, user manager and role manager to use a single instance per request
app.CreatePerOwinContext(() => SmObjectFactory.Container.GetInstance<IApplicationUserManager>());
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SmObjectFactory.Container.GetInstance<IApplicationUserManager>().OnValidateIdentity()
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
}
} using System;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using AspNetIdentityDependencyInjectionSample.DataLayer.Context;
using AspNetIdentityDependencyInjectionSample.IocConfig;
using StructureMap.Web.Pipeline;
namespace AspNetIdentityDependencyInjectionSample
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
setDbInitializer();
//Set current Controller factory as StructureMapControllerFactory
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpContextLifecycle.DisposeAndClearAll();
}
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
throw new InvalidOperationException(string.Format("Page not found: {0}", requestContext.HttpContext.Request.RawUrl));
return SmObjectFactory.Container.GetInstance(controllerType) as Controller;
}
}
private static void setDbInitializer()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
SmObjectFactory.Container.GetInstance<IUnitOfWork>().ForceDatabaseInitialize();
}
}
} [Authorize]
public class AccountController : Controller
{
private readonly IAuthenticationManager _authenticationManager;
private readonly IApplicationSignInManager _signInManager;
private readonly IApplicationUserManager _userManager;
public AccountController(IApplicationUserManager userManager,
IApplicationSignInManager signInManager,
IAuthenticationManager authenticationManager)
{
_userManager = userManager;
_signInManager = signInManager;
_authenticationManager = authenticationManager;
}
[Authorize]
public class ManageController : Controller
{
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private readonly IAuthenticationManager _authenticationManager;
private readonly IApplicationUserManager _userManager;
public ManageController(IApplicationUserManager userManager, IAuthenticationManager authenticationManager)
{
_userManager = userManager;
_authenticationManager = authenticationManager;
}
[Authorize(Roles = "Admin")]
public class RolesAdminController : Controller
{
private readonly IApplicationRoleManager _roleManager;
private readonly IApplicationUserManager _userManager;
public RolesAdminController(IApplicationUserManager userManager,
IApplicationRoleManager roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
[Authorize(Roles = "Admin")]
public class UsersAdminController : Controller
{
private readonly IApplicationRoleManager _roleManager;
private readonly IApplicationUserManager _userManager;
public UsersAdminController(IApplicationUserManager userManager,
IApplicationRoleManager roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
} modelBuilder.Entity<ApplicationUser>().ToTable("User").Property(p => p.Id).HasColumnName("Id");
modelBuilder.Entity<CustomUserRole>().ToTable("UserRole").HasKey(p => new { p.RoleId, p.UserId });
modelBuilder.Entity<CustomUserLogin>().ToTable("UserLogin").HasKey(p => new { p.LoginProvider, p.ProviderKey, p.UserId });
modelBuilder.Entity<CustomUserClaim>().ToTable("UserClaim").HasKey(p => p.Id).Property(p => p.Id).HasColumnName("UserClaimId");
modelBuilder.Entity<CustomRole>().ToTable("Role").Property(p => p.Id).HasColumnName("RoleId"); protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>().ToTable("Users");
builder.Entity<CustomRole>().ToTable("Roles");
builder.Entity<CustomUserClaim>().ToTable("UserClaims");
builder.Entity<CustomUserRole>().ToTable("UserRoles");
builder.Entity<CustomUserLogin>().ToTable("UserLogins");
} public ApplicationDbContext()
: base("connectionString1")
{
//this.Database.Log = data => System.Diagnostics.Debug.WriteLine(data);
//فقط تعریف شده تا یک برک پوینت در اینجا قرار داده شود برای آزمایش تعداد بار فراخوانی آن
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
//فقط تعریف شده تا یک برک پوینت در اینجا قرار داده شود برای آزمایش فراخوانی آن
} User.Identity.GetUserName() User.Identity.GetUserId()
result = this.SetLockoutEnabled(user.Id, false);
ioc.For<IIdentityMessageService>().Use<SmsService>(); ioc.For<IIdentityMessageService>().Use<EmailService>();
// map same interface to different concrete classes
ioc.For<IIdentityMessageService>().Use<SmsService>().Named("smsService");
ioc.For<IIdentityMessageService>().Use<EmailService>().Named("emailService");
ioc.For<IApplicationUserManager>().HybridHttpOrThreadLocalScoped()
.Use<ApplicationUserManager>()
.Ctor<IIdentityMessageService>("smsService").Is<SmsService>()
.Ctor<IIdentityMessageService>("emailService").Is<EmailService>()
.Setter<IIdentityMessageService>(userManager => userManager.SmsService).Is<SmsService>()
.Setter<IIdentityMessageService>(userManager => userManager.EmailService).Is<EmailService>(); public ApplicationUserManager(
IApplicationUserStore store,
IApplicationRoleManager roleManager,
IDataProtectionProvider dataProtectionProvider,
IIdentityMessageService smsService,
IIdentityMessageService emailService)
: base(store as IUserStore<User,int>)
{
this.roleManager = roleManager;
this.dataProtectionProvider = dataProtectionProvider;
EmailService = emailService;
SmsService = smsService;
Debug.WriteLine("Ticks = {0}",DateTime.Now.Ticks);
Debug.WriteLine(emailService.ToString());
Debug.WriteLine(smsService.ToString());
CreateApplicationUserManager();
} Ticks = 635560859158196052 PWS.ServiceLayer.EF.Identity.EmailService PWS.ServiceLayer.EF.Identity.SmsService Ticks = 635560859158246098 PWS.ServiceLayer.EF.Identity.EmailService PWS.ServiceLayer.EF.Identity.EmailService
<add name="connectionString1" connectionString="Data Source=(local);Initial Catalog=TestDbIdentity;Integrated Security = true" providerName="System.Data.SqlClient" />
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public IApplicationRoleManager _roleManager { get; set; }
public IApplicationUserManager _userManager { get; set; }
public CustomAuthorizeAttribute(IApplicationUserManager userManager,
IApplicationRoleManager roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Put your custom logic here, returning true for success and false for failure,
// or return base.AuthorizeCore(httpContext) to defer to the base implementation
IPrincipal user = httpContext.User;
IIdentity identity = user.Identity;
if (!identity.IsAuthenticated)
{
return false;
}
bool isAuthorized = true;
// TODO: perform custom authorization against the App
var qry = _userManager.Users.Where(u => u.UserName == identity.Name).ToList();
return isAuthorized;
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*browserlink}", new { browserlink = @".*/arterySignalR/ping" });
//...
} <appSettings>
<add key="vs:EnableBrowserLink" value="false" />
</appSettings> ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationUser()
{
Id = Guid.NewGuid().ToString();
}
// ...
} PM> install-package name_here
var currentUserRoles =System.Web.Security.Roles.GetRolesForUser().Select(u => u.ToLower()).ToList();
IApplicationRoleManager را به attribute پاس داد که فکر نمیکنم ممکن باشد. ممکن است قدری راهنمایی بفرمایید؟ Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
SmObjectFactory.Container.GetInstance<IUnitOfWork>().ForceDatabaseInitialize(); public override Task<ApplicationUser> FindByIdAsync(int userId)
{
return base.FindByIdAsync(userId);
}
public override Task<ApplicationUser> FindByNameAsync(string userName)
{
return base.FindByNameAsync(userName);
} public virtual Task<TUser> FindByIdAsync(TKey userId)
{
ThrowIfDisposed();
return GetUserAggregateAsync(u => u.Id.Equals(userId));
}
protected virtual async Task<TUser> GetUserAggregateAsync(Expression<Func<TUser, bool>> filter)
{
TKey id;
TUser user;
if (FindByIdFilterParser.TryMatchAndGetId(filter, out id))
{
user = await _userStore.GetByIdAsync(id).WithCurrentCulture();
}
else
{
user = await Users.FirstOrDefaultAsync(filter).WithCurrentCulture();
}
if (user != null)
{
await EnsureClaimsLoaded(user).WithCurrentCulture();
await EnsureLoginsLoaded(user).WithCurrentCulture();
await EnsureRolesLoaded(user).WithCurrentCulture();
}
return user;
} public class MyUserStore
:UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
private DbSet<ApplicationUser> _myUserStore;
public MyUserStore(ApplicationDbContext context)
: base(context)
{
_myUserStore = (DbSet<ApplicationUser>) context.Set<ApplicationUser>();
}
public override Task<ApplicationUser> FindByIdAsync(int userId)
{
return _myUserStore.FindAsync(userId);
}
}
} ioc.For<IUserStore<ApplicationUser, int>>()
.HybridHttpOrThreadLocalScoped()
.Use<UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>>(); ioc.For<IUserStore<ApplicationUser, int>>()
.HybridHttpOrThreadLocalScoped()
.Use<MyUserStore>(); using System.Data.Entity;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.EntityFramework;
using SmartMarket.Core.Domain.Members;
using SmartMarket.Data;
namespace SmartMarket.Services.Members
{
/// <summary>
/// The ApplicationUserStore Class
/// </summary>
public class ApplicationUserStore : UserStore<User, Role, int, UserLogin, UserRole, UserClaim>, IApplicationUserStore
{
#region Fields (1)
private readonly IDbSet<User> _userStore;
#endregion Fields
#region Constructors (2)
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationUserStore" /> class.
/// </summary>
/// <param name="dbContext">The database context.</param>
public ApplicationUserStore(DbContext dbContext) : base(dbContext) { }
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationUserStore"/> class.
/// </summary>
/// <param name="context">The context.</param>
public ApplicationUserStore(IdentityDbContext context)
: base(context)
{
_userStore = context.Set<User>();
}
#endregion Constructors
#region Methods (2)
// Public Methods (2)
/// <summary>
/// Adds to previous passwords asynchronous.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
public Task AddToPreviousPasswordsAsync(User user, string password)
{
user.PreviousUserPasswords.Add(new PreviousPassword { UserId = user.Id, PasswordHash = password });
return UpdateAsync(user);
}
/// <summary>
/// Finds the by identifier asynchronous.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns></returns>
public override Task<User> FindByIdAsync(int userId)
{
return Task.FromResult(_userStore.Find(userId));
}
#endregion Methods
/// <summary>
/// Creates the asynchronous.
/// </summary>
/// <param name="user">The user.</param>
/// <returns></returns>
public override async Task CreateAsync(User user)
{
await base.CreateAsync(user);
await AddToPreviousPasswordsAsync(user, user.PasswordHash);
}
}
} appBuilder.CreatePerOwinContext(
() =>ProjectObjectFactory.Container.GetInstance<ApplicationUserManager>()); ioc.For<IIdentity>().Use(() => (HttpContext.Current != null && HttpContext.Current.User != null) ? HttpContext.Current.User.Identity : null);
ioc.For<DbContext>().HybridHttpOrThreadLocalScoped().Use<ApplicationDbContext>();
app.CreatePerOwinContext(
() => SmObjectFactory.Container.GetInstance<IApplicationUserManager>()); public class User : IdentityUser<Guid, UserLogin, UserRole, UserClaim>
public Guid GetCurrentUserId()
{
return _identity.GetUserId<Guid>();
} The type 'System.Guid' cannot be used as type parameter 'T' in the generic type or method 'Microsoft.AspNet.Identity.IdentityExtensions.GetUserId<T>(System.Security.Principal.IIdentity)'. There is no boxing conversion from 'System.Guid' to 'System.IConvertible'
Guid.Parse(User.Identity.GetUserId())
public static class IdentityExtensions
{
public static Guid GetGuidUserId(this IIdentity identity)
{
Guid result = Guid.Empty;
Guid.TryParse(identity.GetUserId(), out result);
return result;
}
} public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUser applicationUser)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("Avatar",applicationUser.Avatar));
return userIdentity;
} app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromDays(30),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = StoreObjectFactory.Container.GetInstance<IApplicationUserManagerService>().OnValidateIdentity()
},
SlidingExpiration = true,
CookieName = "iasaccount"
}); public Func<CookieValidateIdentityContext, Task> OnValidateIdentity()
{
return SecurityStampValidator.OnValidateIdentity<ApplicationUserManagerService, User, Guid>(
validateInterval: TimeSpan.FromDays(3),
regenerateIdentityCallback: (manager, user) => GenerateUserIdentityAsync(manager, user),
getUserIdCallback: id => id.GetGuidUserId());
} var result = await _signInManagerService.PasswordSignInAsync(loginViewModel.Email, loginViewModel.Password, loginViewModel.RememberMe, shouldLockout: false);
C:\Windows\System32\inetsrv\config\schema\IIS_schema.xml
<attribute name="idleTimeout"
type="timeSpan"
defaultValue="00:20:00"
validationType="timeSpanRange"
validationParameter="0,2592000,60"/> Line 118: {
Line 119: user = new ApplicationUser { UserName = name, Email = name };
Line 120: var result = this.Create(user, password);
Line 121: result = this.SetLockoutEnabled(user.Id, false);
Line 122: } Line 119: user = new ApplicationUser { UserName = name, Email = name };
Line 120: var result = this.Create(user, password);
Line 121: result = this.SetLockoutEnabled(user.Id, false);
Line 122: }
Line 123: //...
Debug.WriteLine(err.PropertyName + " " + err.ErrorMessage); exceptionMessage": "An error occurred when trying to create a controller of type 'AccountApiController'. Make sure that the controller has a parameterless public constructor.",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "Type 'MyProject.Web.Controllers.AccountApiController' does not have a default constructor",
"exceptionType": "System.ArgumentException", _identity.GetEmailAdress()
// Add custom user claims here
userIdentity.AddClaim(new Claim("key1", "value1")); public static string GetClaimValue(this IPrincipal currentPrincipal, string key)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claim = identity.Claims.FirstOrDefault(c => c.Type == key);
return claim?.Value;
} public async Task<ClaimsIdentity> GenerateUserIdentityAsync(User applicationUser)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("emailaddress", applicationUser.Email));
return userIdentity;
} public virtual async Task<ActionResult> Login(LoginViewModel viewModel, string returnUrl)
{
// ... more code
var user = await this._userManager.FindByNameAsync(viewModel.UserName);
await this._userManager.GenerateUserIdentityAsync(user);
return this.View(viewModel);
} _.For<IPrincipal>().Use(() => HttpContext.Current.User);
var useremail = this._principal.GetClaimValue("emailaddress"); var manager = context.OwinContext.GetUserManager<TManager>();
app.CreatePerOwinContext(() => (ApplicationUserManager)container.GetInstance<IApplicationUserManager>());
var dbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
CookieManager = new SystemWebCookieManager()
regenerateIdentityCallback: (manager, user) => manager.GenerateUserIdentityAsync(user)
public static string GetClaimValue(this IPrincipal currentPrincipal, string key)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claim = identity.Claims.FirstOrDefault(c => c.Type == key);
return claim?.Value;
} public override Task<ClaimsIdentity> CreateUserIdentityAsync(User user)
{
return _userManager.GenerateUserIdentityAsync(user);
} case SignInStatus.Success:
var user = await _userManager.FindByNameAsync(model.UserName);
await _signInManager.CreateUserIdentityAsync(user);
return RedirectToLocal(returnUrl); One or more validation errors were detected during model generation: DataLayer.Context.CustomUserRole: : EntityType 'CustomUserRole' has no key defined. Define the key for this EntityType. DataLayer.Context.CustomUserLogin: : EntityType 'CustomUserLogin' has no key defined. Define the key for this EntityType. CustomUserRoles: EntityType: EntitySet 'CustomUserRoles' is based on type 'CustomUserRole' that has no keys defined. CustomUserLogins: EntityType: EntitySet 'CustomUserLogins' is based on type 'CustomUserLogin' that has no keys defined.
protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder); var createResult = this.Create(user, password); var result = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(false);