ASP.NET core, change default redirect for unauthorized

前端 未结 7 824
抹茶落季
抹茶落季 2020-12-05 09:55

I am attempting to redirect to a different login url in ASP.NET MVC6

My account controller login method has a Route attribute to change the url.

7条回答
  •  -上瘾入骨i
    2020-12-05 10:08

    I wouldn't recommend Serj Sagan solution in a real life example. This would work perfectly when developing but for a real application used by different types of user that might be misleading. Lets look at the below scenario

    1. I am authenticated used
    2. I know the url for a specific page
    3. I am not authorize to access that pages

    It means that I would be redirected to the login page as if I were not authenticated which is not the case. I would go more with mxmissile solution

    Personnally I am using the AddMvcCore but you need to add AddRazorViewEngine if you are using razor views and AddRazorPages if you are using razor pages

            services.AddMvcCore(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddRazorViewEngine()
            .AddAuthorization()
            .AddJsonFormatters();
    

提交回复
热议问题