ASP.NET MVC 表单身份验证 + 授权属性 + 简单角色

编程代码

1个回答

写回答

QIAN HUI

2025-06-25 13:20

+ 关注

服务器
服务器

使用 ASP.NET MVC 框架进行表单身份验证和授权属性设置,是一种常见的安全机制。本文将介绍如何在 ASP.NET MVC 中实现表单身份验证以及使用简单角色进行授权控制的方法,并提供相应的案例代码。

ASP.NET MVC 表单身份验证

ASP.NET MVC 提供了一种基于表单的身份验证机制,可以方便地对用户进行身份验证和授权控制。表单身份验证是一种基于 cookie 的机制,通过在用户登录成功后生成一个身份验证票据,并将该票据存储在用户的浏览器中,以后每次用户访问受限资源时,服务器将检查该票据是否有效来进行身份验证。

要使用表单身份验证,首先需要在 ASP.NET MVC 项目中启用身份验证。可以在项目的 Web.config 文件中的 节点中添加如下配置:

<authentication mode="Forms">

<forms loginUrl="~/Account/Login" timeout="2880" />

</authentication>

其中,loginUrl 属性指定了登录页面的 URL,timeout 属性指定了身份验证票据的过期时间。

接下来,在登录控制器中实现登录和注销的方法。例如,可以创建一个 AccountController,并在其中添加以下代码:

csharp

public class AccountController : Controller

{

public ActionResult Login()

{

return View();

}

[HttpPost]

public ActionResult Login(LoginViewModel model)

{

if (ModelState.IsValid)

{

// 验证用户信息,判断用户名和密码是否匹配

if (model.Username == "admin" && model.Password == "admin123")

{

// 登录成功,生成身份验证票据并保存到浏览器中

FormsAuthentication.SetAuthCookie(model.Username, false);

return RedirectToAction("Index", "Home");

}

else

{

ModelState.AddModelError("", "用户名或密码不正确");

}

}

return View(model);

}

public ActionResult Logout()

{

// 注销,清除浏览器中的身份验证票据

FormsAuthentication.SignOut();

return RedirectToAction("Login");

}

}

上述代码中,Login 方法用于显示登录页面,LoginViewModel 是一个用于接收登录表单数据的模型。在登录 POST 方法中,首先验证用户输入的用户名和密码是否正确,如果正确,则使用 FormsAuthentication.SetAuthCookie 方法生成身份验证票据并保存到浏览器中,然后重定向到首页;如果输入的用户名和密码不正确,则通过 ModelState.AddModelError 方法添加错误信息,并返回登录页面。

ASP.NET MVC 授权属性

在 ASP.NET MVC 中,可以使用授权属性来限制某些操作只能由特定角色的用户执行。授权属性是一种声明在控制器或操作方法上的特性,用于指定该控制器或操作方法只有满足特定条件的用户才能访问。

可以通过在控制器或操作方法上添加 [Authorize] 属性来启用授权。例如,可以在 HomeController 中的某个操作方法上添加 [Authorize(Roles = "Admin")],表示只有拥有 "Admin" 角色的用户才能访问该操作方法。

现在,我们来实现一个简单的角色授权的例子。首先,在 AccountController 的 Login POST 方法中,将登录成功的用户角色信息写入身份验证票据的 UserData 属性中:

csharp

if (model.Username == "admin" && model.Password == "admin123")

{

FormsAuthentication.SetAuthCookie(model.Username, false);

// 将用户角色写入身份验证票据的 UserData 属性

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.Username, DateTime.Now, DateTime.Now.AddMinutes(30), false, "Admin");

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

Response.Cookies.Add(cookie);

return RedirectToAction("Index", "Home");

}

上述代码中,我们使用 FormsAuthenticationTicket 类创建一个身份验证票据,并将用户角色信息写入其中。然后,使用 FormsAuthentication.Encrypt 方法将票据加密,并将加密后的票据存储在浏览器的 cookie 中。

接下来,在 HomeController 中的某个操作方法上添加 [Authorize(Roles = "Admin")] 属性,例如:

csharp

[Authorize(Roles = "Admin")]

public ActionResult AdminOnly()

{

return View();

}

上述代码中,我们使用 [Authorize(Roles = "Admin")] 属性来限制 AdminOnly 操作方法只能由拥有 "Admin" 角色的用户访问。

案例代码

AccountController.cs:

csharp

public class AccountController : Controller

{

public ActionResult Login()

{

return View();

}

[HttpPost]

public ActionResult Login(LoginViewModel model)

{

if (ModelState.IsValid)

{

if (model.Username == "admin" && model.Password == "admin123")

{

FormsAuthentication.SetAuthCookie(model.Username, false);

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.Username, DateTime.Now, DateTime.Now.AddMinutes(30), false, "Admin");

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

Response.Cookies.Add(cookie);

return RedirectToAction("Index", "Home");

}

else

{

ModelState.AddModelError("", "用户名或密码不正确");

}

}

return View(model);

}

public ActionResult Logout()

{

FormsAuthentication.SignOut();

return RedirectToAction("Login");

}

}

HomeController.cs:

csharp

public class HomeController : Controller

{

public ActionResult Index()

{

return View();

}

[Authorize(Roles = "Admin")]

public ActionResult AdminOnly()

{

return View();

}

}

LoginViewModel.cs:

csharp

public class LoginViewModel

{

[Required]

public string Username { get; set; }

[Required]

public string Password { get; set; }

}

Index.cshtml:

html

<h2>首页</h2>

AdminOnly.cshtml:

html

<h2>仅限管理员访问的页面</h2>

本文介绍了如何在 ASP.NET MVC 中使用表单身份验证和授权属性进行身份验证和授权控制的方法。通过使用表单身份验证,可以方便地对用户进行身份验证,并通过授权属性来限制特定角色的用户访问某些操作。这种安全机制可以有效保护网站的敏感资源,提高用户的安全性和隐私保护。

以上就是关于 ASP.NET MVC 表单身份验证 + 授权属性 + 简单角色 的介绍和案例代码,希望对你有所帮助。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号