简体   繁体   English

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

[英]Authorization with Session variables in asp net mvc 5

So my project requirements changed and now I think I need to build my own action filter. 所以我的项目要求发生了变化,现在我认为我需要构建自己的动作过滤器。

So, this is my current login 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");
    }
}

And this is my action filter attempt: 这是我的动作过滤器尝试:

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

I have already added it to FilterConfig, but when I login it does not load Default.cshtml it just keeps looping the action filter. 我已经将它添加到FilterConfig,但是当我登录时它没有加载Default.cshtml它只是继续循环动作过滤器。 The action result for it looks like this: 它的动作结果如下所示:

//this is located in the MainPage controller //它位于MainPage控制器中

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

So, what would I need to add in order to give authorization so only authenticated users can view the application´s pages? 那么,我需要添加什么才能授权,以便只有经过身份验证的用户才能查看应用程序的页面? Should I use Session variables or is there another/better way of doing this using? 我应该使用Session变量还是有另一种/更好的方法来使用它? I am pretty much stuck with AuthenticateUser(), since what happens there now is just a simple comparison like the one we have there now. 我几乎坚持使用AuthenticateUser(),因为现在发生的只是一个简单的比较,就像我们现在所拥有的那样。

Thank you for your time. 感谢您的时间。

Create an AuthorizeAttribute with your logic in there: 使用您的逻辑创建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();
        }
    }
}

As long as you have the Login URL Configured in your Startup.Auth.cs file, it will handle the redirection to the login page for you. 只要您在Startup.Auth.cs文件中配置了登录URL,它就会为您处理重定向到登录页面。 If you create a new MVC project it configures this for you: 如果您创建一个新的MVC项目,它会为您配置:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(
            new CookieAuthenticationOptions {

                    // YOUR LOGIN PATH
                    LoginPath = new PathString("/Account/Login")
            }
        );
    }
}

Using this you can decorate your controllers with [AuthorizationFilter] and also [AllowAnonymous] attributes if you want to prevent the authorization from being checked for certain Controllers or Actions. 使用此选项可以使用[AuthorizationFilter][AllowAnonymous]属性修饰控制器,以防止对某些控制器或操作检查授权。

You might want to check this in different scenarios to ensure it provides tight enough security. 您可能希望在不同的方案中检查这一点,以确保它提供足够的安全性。 ASP.NET MVC provides mechanisms that you can use out of the box for protecting your applications, I'd recommend using those if possible in any situation. ASP.NET MVC提供了可以立即使用的机制来保护您的应用程序,我建议在任何情况下尽可能使用这些机制。 I remember someone saying to me, if you're trying to do authentication/security for yourself, you're probably doing it wrong. 我记得有人对我说,如果你想为自己做身份验证/安全,你可能做错了。

Since your attribute is added to the FilterConfig, it will apply to ALL actions. 由于您的属性已添加到FilterConfig,因此它将应用于所有操作。 So when you navigate to your MainPage/Default action it will be applying the filter and redirecting you to your MainPage/Default action (and so on...). 因此,当您导航到MainPage / Default操作时,它将应用过滤器并将您重定向到MainPage / Default操作(依此类推......)。

You will either need to: 您将需要:

  • remove it from the FilterConfig and apply it to the appropriate actions / controllers 将其从FilterConfig中删除并将其应用于适当的操作/控制器
  • or add an extra check in the filter so that it doesn't redirect on certain routes 或者在过滤器中添加额外的检查,以便它不会在某些路由上重定向

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM