dav*_*ooh 20 .net c# asp.net-mvc asp.net-mvc-5
我是ASP.NET MVC 5的新手,我发现身份认证+授权框架非常不舒服.我知道这是ASP.NET MVC框架的一个新功能,所以我想在我的应用程序中应用另一种方法来实现身份验证.
可能吗?我读过我可以用的FormsAuthenticationModule
.这是一个很好的选择吗?如何在基于MVC 5的应用程序中使用它?
cuo*_*gle 34
看一下Identity时我也有同感.它增加了许多不必要的抽象,并不适合我的情况,我有遗留系统,实现了自定义的身份验证工作流程.
大量关于使用Identity和EF默认的OWIN身份验证的例子让开发人员感到困惑,OWIN必须与身份和实体框架一起使用.
但从技术上讲,您可以剥离Identity以仅使用OWIN cookie身份验证(Microsoft.Owin.Security.Cookies
).代码变得非常简单,下面是我从我的代码中获得的示例,它消除了琐碎的事情:
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
var user = _userService.GetByEmail(model.Email);
//check username and password from database, naive checking:
//password should be in SHA
if (user != null && (user.Password == model.Password))
{
var claims = new[] {
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Email, user.Email),
// can add more claims
};
var identity = new ClaimsIdentity(claims, "ApplicationCookie");
// Add roles into claims
var roles = _roleService.GetByUserId(user.Id);
if (roles.Any())
{
var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r.Name));
identity.AddClaims(roleClaims);
}
var context = Request.GetOwinContext();
var authManager = context.Authentication;
authManager.SignIn(new AuthenticationProperties
{ IsPersistent = model.RememberMe }, identity);
return RedirectToAction("Index", "Home");
}
// login failed.
}
public ActionResult LogOut()
{
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignOut("ApplicationCookie");
return RedirectToAction("Login");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10461 次 |
最近记录: |