所以我的项目需求发生了变化,现在我认为我需要构建自己的操作过滤器。
所以,这是我当前的登录 Controller :
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
string userName = AuthenticateUser(model.UserName, model.Password);
if (!(String.IsNullOrEmpty(userName)))
{
Session["UserName"] = userName;
return View("~/Views/Home/Default.cshtml");
}
else
{
ModelState.AddModelError("", "Invalid Login");
return View("~/Views/Home/Login.cshtml");
}
}
public string AuthenticateUser(string username, string password)
{
if(password.Equals("123")
return "Super"
else
return null;
}
public ActionResult LogOff()
{
Session["UserName"] = null;
//AuthenticationManager.SignOut();
return View("~/Views/Home/Login.cshtml");
}
}
这是我的操作过滤器尝试:
public class AuthorizationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["UserName"] != null)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "MainPage" },
{ "action", "Default" }
});
}
base.OnActionExecuting(filterContext);
}
}
我已经将它添加到 FilterConfig,但是当我登录时它不会加载 Default.cshtml,它只是不断循环操作过滤器。它的操作结果如下所示:
//这位于MainPage Controller 中
[AuthorizationFilter]
public ActionResult Default()
{
return View("~/Views/Home/Default.cshtml");
}
那么,我需要添加什么才能授予授权,以便只有经过身份验证的用户才能查看应用程序的页面?我应该使用 session 变量还是有另一种/更好的方法来使用?我几乎被 AuthenticateUser() 困住了,因为现在发生的只是一个简单的比较,就像我们现在的比较一样。
感谢您的宝贵时间。
最佳答案
用你的逻辑创建一个AuthorizeAttribute
:
public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
// Don't check for authorization as AllowAnonymous filter is applied to the action or controller
return;
}
// Check for authorization
if (HttpContext.Current.Session["UserName"] == null)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
只要您在 Startup.Auth.cs
文件中配置了登录 URL,它就会为您处理到登录页面的重定向。如果您创建一个新的 MVC 项目,它会为您配置:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(
new CookieAuthenticationOptions {
// YOUR LOGIN PATH
LoginPath = new PathString("/Account/Login")
}
);
}
}
使用它,您可以使用 [AuthorizationFilter]
和 [AllowAnonymous]
属性来装饰您的 Controller ,如果您想要防止检查某些 Controller 或操作的授权。
您可能想在不同的场景中检查它以确保它提供足够严格的安全性。 ASP.NET MVC 提供了开箱即用的机制来保护您的应用程序,我建议您尽可能在任何情况下使用这些机制。我记得有人对我说,如果你想为自己做身份验证/安全,你可能做错了。
关于c# - 在 asp net mvc 5 中使用 session 变量进行授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30372022/