在asp.net mvc 5中使用会话变量进行授权
本文关键字:变量 会话 授权 net asp mvc | 更新日期: 2023-09-27 17:50:18
所以我的项目需求改变了,现在我想我需要建立自己的动作过滤器。
这是我当前的登录控制器:
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,但当我登录它不加载默认。它只是循环操作过滤器。它的操作结果如下所示:
//它位于MainPage控制器
[AuthorizationFilter]
public ActionResult Default()
{
return View("~/Views/Home/Default.cshtml");
}
那么,我需要添加什么来授予授权,以便只有经过身份验证的用户才能查看应用程序的页面?我应该使用会话变量还是有其他/更好的方法来使用?我几乎被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]
属性装饰你的控制器,如果你想防止某些控制器或动作的授权被检查。
您可能需要在不同的场景中检查这一点,以确保它提供足够严格的安全性。ASP。. NET MVC提供了开箱即用的机制来保护应用程序,我建议在任何可能的情况下使用这些机制。我记得有人对我说,如果你想为自己做认证/安全,你可能做错了。
由于您的属性已添加到FilterConfig中,因此它将适用于所有操作。因此,当您导航到主页面/默认操作时,它将应用过滤器并将您重定向到主页面/默认操作(等等…)。
你需要:
- 将其从FilterConfig中删除,并将其应用于相应的动作/控制器
- 或者在过滤器中添加一个额外的检查,以便它不会在某些路由上重定向
您可以像这样简单地从OnAuthorization方法访问Session Object:
public void OnAuthorization(AuthorizationFilterContext context)
{
//Log("OnAuthorization", context.RouteData);
var user = context.HttpContext.Session.GetString("user");
if (user == null) {
// context.Result = new UnauthorizedResult(); //use this if you want send 401 Http Response or
context.Result = new RedirectResult("home/login");
}
}