Authorization with Session variables in asp net mvc 5

后端 未结 2 866
暗喜
暗喜 2021-01-06 08:50

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 Login         


        
相关标签:
2条回答
  • 2021-01-06 09:45

    Create an AuthorizeAttribute with your logic in there:

    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. If you create a new MVC project it configures this for you:

    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.

    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. I remember someone saying to me, if you're trying to do authentication/security for yourself, you're probably doing it wrong.

    0 讨论(0)
  • 2021-01-06 09:45

    Since your attribute is added to the FilterConfig, it will apply to ALL actions. 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...).

    You will either need to:

    • remove it from the FilterConfig and apply it to the appropriate actions / controllers
    • or add an extra check in the filter so that it doesn't redirect on certain routes
    0 讨论(0)
提交回复
热议问题