سفارشی کردن ASP.NET Identity در MVC 5
نویسنده: آرمین ضیاء
تاریخ: ۱۳۹۲/۱۰/۱۹ ۱۹:۵۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class IdentityUser : IUser
{
public IdentityUser();
public IdentityUser(string userName);
public virtual ICollection<identityuserclaim> Claims { get; }
public virtual string Id { get; set; }
public virtual ICollection<identityuserlogin> Logins { get; }
public virtual string PasswordHash { get; set; }
public virtual ICollection<identityuserrole> Roles { get; }
public virtual string SecurityStamp { get; set; }
public virtual string UserName { get; set; }
} public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
} public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Email address")]
public string Email { get; set; }
} <div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div> public ActionResult About()
{
ViewBag.Message = "Your application description page.";
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
ViewBag.Email = user.Email;
else
ViewBag.Email = "User not found.";
return View();
} سلام؛ از زحماتتون بسیار تشکر میکنم. من وب سایت را به روش چند لایهی مرسوم میسازم:
data layer - domain models - website - service layer
با توجه به آن چگونه میتوان از asp.net identity استفاده کرد؟ زیرا مثلا نیاز است از کلید جدول users در مدلهای دیگه استفاده شود. آیا این کلید را باید در لایه دومین استفاده کرد؟
سلام...ممنون از پاسختون.
با توجه به راهنمایی شما در قسمت context در لایه data layer بدین صورت درج کردم
public class Context : DbContext
{
public DbSet<IdentityUserClaim> AspNetUserClaims { set; get; }
public DbSet<IdentityRole> AspNetRoles { set; get; }
public DbSet<IdentityUserLogin> AspNetUserLogins { set; get; }
public DbSet<IdentityUserRole> AspNetUserRoles { set; get; }
public DbSet<IdentityUser> AspNetUsers { set; get; }
//--------------------------------------
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id).ToTable("AspNetRoles");
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
modelBuilder.Entity<IdentityUserLogin>().HasKey(l => new { l.UserId, l.LoginProvider, l.ProviderKey }).ToTable("AspNetUserLogins");
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId }).ToTable("AspNetUserRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
}
}
عذر خواهی میکنم فراموش کردم. ایراد بدین صورت است:
System.InvalidOperationException: The model backing the 'Context' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
مشخص است که میگوید context تغییر میکند.ولی من از migration استفاده میکنم و codefirst ولی باز هم این ایراد رو در اتصال به دیتابیس نشان میدهد. من از add-migration هم استفاده میکنم تا تغییرات موجودیتها رو کامل به من نشان دهد که چیزی را عنوان نمیکند.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection") { }
} public class AppUserManager : UserManager<AppUser>{
public AppUserManager() : base(new UserStore<AppUser>(new ShirazBilitDbContext())) { }
} public class AppUser : IdentityUser
{
public string Email { get; set; }
public string ConfirmationToken { get; set; }
public bool IsConfirmed { get; set; }
} public class IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim> : DbContext where TUser : IdentityUser<TKey, TUserLogin, TUserRole, TUserClaim> where TRole : IdentityRole<TKey, TUserRole> where TUserLogin : IdentityUserLogin<TKey> where TUserRole : IdentityUserRole<TKey> where TUserClaim : IdentityUserClaim<TKey>
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = UserManager.FindById(User.Identity.GetUserId()); public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doen't count login failures towards lockout only two factor authentication
// To enable password failures to trigger lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
{
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = UserManager.FindById(User.Identity.GetUserId());
return RedirectToLocal(returnUrl);
}
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
} مثال مطلب اعمال تزریق وابستگیها به مثال رسمی ASP.NET Identity، جهت تکمیل کلاس ApplicationRoleManager آن بهبود داده شد (^). برای نمونه:
public IList<ApplicationUser> GetApplicationUsersInRole(string roleName)
{
var selectedUserIds = from role in this.Roles
where role.Name == roleName
from user in role.Users
select user.UserId;
return _users.Where(applicationUser => selectedUserIds.Contains(applicationUser.Id)).ToList();
} public override void OnAuthorization(AuthorizationContext filterContext)
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName filterContext.ActionDescriptor.ActionName
filterContext.Result = new HttpStatusCodeResult(403);
ALTER TABLE yourtable DROP CONSTRAINT DF_AspNetUser_UserN__34C8D9D1
ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;