如何实现在ASP.NET MVC中5个自定义验证 [英] How to implement custom authentication in ASP.NET MVC 5
问题描述
我开发一个ASP.NET MVC 5应用程序。我有一个现有的数据库,从中我创建了ADO.NET实体数据模型。
我在其中包含用户名和密码列数据库的表,我想用它来实现我的webapp身份验证和授权;我无法创建任何其他数据库或表或列,我不能使用标准的身份认证,因为客户的需求。
我并不需要管理注册,密码更改或其他东西:只需用用户名和密码登录。
我该怎么办呢?
I'm developing an ASP.NET MVC 5 application. I have an existing DB, from which I created my ADO.NET Entity Data Model. I have a table in that DB which contains "username" and "password" column, and I want to use them to implement authentication and authorization in my Webapp; I cannot create any other database or table or column and I cannot use the standard Identity authentication, because of customer's requirements. I don't need to manage signup, password changing or other stuffs: just login with password and username. How can I do that?
推荐答案
当然可以。微软的身份框架的认证和授权的部分独立工作。如果你有自己的认证服务,您可以只使用标识的授权部分。想想你已经有一个的UserManager
这也验证了用户名
和密码
。因此,你可以按照你的背部后登录操作code写的:
Yes you can. Microsoft's Identity framework's authentication and authorization parts works independently. If you have own authentication service you can just use Identity's authorization part. Consider you already have a UserManager
which validates username
and password
. Therefore you can write following code in your post back login action:
[HttpPost]
public ActionResult Login(string username, string password)
{
if (new UserManager.IsValid(username, password))
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, username),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,username),
// optionally you could add roles if any
new Claim(ClaimTypes.Role, "RoleName"),
new Claim(ClaimTypes.Role, "AnotherRole"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View();
}
和您的用户管理器可以是这样的:
And your user manager can be something like this:
class UserManager
{
public bool IsValid(string username, string password)
{
using(var db=new MyDbContext()) // use your DbConext
{
// if your users set name is Users
return db.Users.Any(u=>u.Username==username
&& u.Password==password);
}
}
}
目前您可以通过添加授权
属性保护您的行为或控制器结束。
At the end you can protect your actions or controllers by adding Authorize
attribute.
[Authorize]
public ActionResult MySecretAction()
{
// all authorized users can use this method
// we have access current user principal by calling also
// HttpContext.User
}
[Authorize(Roles="Admin")]
public ActionResult MySecretAction()
{
// just Admin users have access to this method
}
这篇关于如何实现在ASP.NET MVC中5个自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!