在asp net mvc 5中使用Session变量进行授权

所以我的项目要求发生了变化,现在我认为我需要构建自己的动作filter。

所以,这是我当前的登录控制器:

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"); } } 

这是我的动作filter尝试:

 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它只是保持循环动作filter。 它的动作结果如下所示:

//它位于MainPage控制器中

  [AuthorizationFilter] public ActionResult Default() { return View("~/Views/Home/Default.cshtml"); } 

那么,我需要添加什么才能授权,以便只有经过身份validation的用户才能查看应用程序的页面? 我应该使用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]属性修饰控制器,以防止对某些控制器或操作检查授权。

您可能希望在不同的方案中检查这一点,以确保它提供足够的安全性。 ASP.NET MVC提供了可以立即使用的机制来保护您的应用程序,我建议在任何情况下尽可能使用这些机制。 我记得有人对我说,如果你想为自己做身份validation/安全,你可能做错了。

由于您的属性已添加到FilterConfig,因此它将应用于所有操作。 因此,当您导航到MainPage / Default操作时,它将应用filter并将您重定向到MainPage / Default操作(依此类推……)。

您将需要:

  • 将其从FilterConfig中删除并将其应用于相应的操作/控制器
  • 或者在filter中添加额外的检查,以便它不会在某些路由上重定向