用于身份验证的中间件
本文关键字:中间件 身份验证 用于 | 更新日期: 2023-09-27 17:58:04
我创建了一个ASP.NET MVC核心应用程序。我刚刚创建并登录了一个用户。现在我正试图弄清楚
1.如何保存用户登录信息
2.如何要求用户登录才能访问网站的其余部分
用于保存用户日志信息。我本来打算使用Identity或Asp.Net.Session,但由于我找不到任何显示如何要求用户登录才能访问路线的内容,我不确定哪个选项最有效
有人能向我解释一下在访问路由之前如何要求身份验证,以及哪种保存登录信息的方法最适合这种方法吗?
当前登录示例
public ActionResult Login(LoginModel model){
if (ModelState.IsValid){
SqlConnect test = new SqlConnect("Data Source=/home/andrew/database.db","Accounts");
var check = test.count(model.UserName,model.Password);
if(check){
// Found in database
return RedirectToAction("Index","Home");
}
}
// If we got this far, something failed, redisplay form
return RedirectToAction("Error","Home");
}
您不应该保护路由。当使用占位符(例如在默认路由中)时,可能有多个路由可以到达一个操作方法。随着应用程序的变化,这些备用路径肯定很难(几乎不可能)保持安全。
因此,最好的选择是通过阻止资源得到服务来保护它们。请注意,这也是ASP.NET中安全性的工作方式,因此ASP.NET和MVC都挂接到相同的机制(IPrincipal
和IIdentity
)中,以控制身份验证和授权。ASP.NET Identity和Microsoft的旧安全框架都使用此扩展点来插入MVC和ASP.NET。
在MVC中,AuthorizeAttribute
使用这些接口来保护操作方法。AuthorizeAttribute
可用于多种方式:
论行动方法
public class MyController
{
[Authorize(Roles = "Admin,SuperUser")]
public ActionResult Index()
{
return View();
{
}
在控制器上
[Authorize(Roles = "Admin,SuperUser")]
public class MyController
{
[AllowAnonymous] // All users have access
public ActionResult Index()
{
return View();
{
// Only authenticated users in Admin or SuperUser
// role have access
public ActionResult Contact()
{
return View();
{
// Only authenticated users in Admin or SuperUser
// role have access
public ActionResult About()
{
return View();
{
}
全球
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
filters.Add(new HandleErrorAttribute());
}
}
这意味着只有经过身份验证的用户才能访问应用程序中的任何操作方法。您也可以在此处使用类似filters.Add(new AuthorizeAttribute() { Roles = "Foo,Bar" });
的角色。您可以使用AllowAnonymousAttribute
允许未经身份验证的用户访问特定的控制器/操作。
如果您有比"用户"answers"角色"更复杂的业务逻辑,您也可以将AuthorizeAttribute
子类化。