Authorization with Session variables in asp net mvc 5

后端 未结 2 865
暗喜
暗喜 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.

提交回复
热议问题