简体   繁体   English

MVC4中的基本登录/授权

[英]Basic Login / Authorization in MVC4

I have two Controllers in my MVC4 application that I want to require users to be logged into to access; 我的MVC4应用程序中有两个控制器,我想要求用户登录才能访问。 an 'admin' area of sorts. 一个“管理”区域。

I have a database linked class that handles authentication for me in C#, meaning I can do something like this: 我有一个数据库链接类,可以使用C#为我处理身份验证,这意味着我可以执行以下操作:

LoginUtility lu = new LoginUtility();
if(lu.Login("username", "password") == true){
   // User is genuine
} else {
   // Login failed
}

I want to hook this up to MVC4 so I can apply the [Authorize] attribute to those two Controllers. 我想将其连接到MVC4,以便可以将[Authorize]属性应用于这两个控制器。

You should use a basic Web Application Template, it gives you controllers to edit users and use authentication. 您应该使用基本的Web应用程序模板,它为您提供控制器来编辑用户和使用身份验证。 Then, you will be able to allow certain controllers, or certain action of controllers. 然后,您将可以允许某些控制器或某些控制器动作。 For a controller, you just have to put [Authorize(Roles = "Admin")] tag just before the definition of the controller to just allow this action to Admin Roles. 对于控制器,您只需要在控制器的定义之前放置[Authorize(Roles =“ Admin”)]标记,即可将此操作授予“管理员角色”。

I have found doing custom login logic quite the pain. 我发现执行自定义登录逻辑非常麻烦。 What you need to do is extend AuthorizeAttribute so you can use it on your controllers/actions, and override AuthorizeCore . 您需要做的是扩展AuthorizeAttribute以便可以在控制器/动作上使用它,并覆盖AuthorizeCore If you need custom logic to extract the username and password from the request, you can do that through setting the User property on HttpContext in an OnAuthorization override. 如果您需要自定义逻辑来从请求中提取用户名和密码,则可以通过在OnAuthorization覆盖中的HttpContext上设置User属性来OnAuthorization

In your web.config add : 在您的web.config中添加:

<authentication mode="Forms">
  <forms loginUrl="login.aspx" />
</authentication>

And in your controller : 在您的控制器中:

LoginUtility lu = new LoginUtility();
if(lu.Login("username", "password") == true){
 FormsAuthentication.SetAuthCookie(...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM