Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

c# - ASP.NET core, change default redirect for unauthorized

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.

[HttpGet]
[AllowAnonymous]
[Route("login")]
public IActionResult Login(string returnUrl = null)
{
    this.ViewData["ReturnUrl"] = returnUrl;
    return this.View();
}

When attempting to access an unathorized page, I am redirected to the invalid url, it should just be /login but instead I get http://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex

I have configured the cookie authentication path as follows:

services.Configure<CookieAuthenticationOptions>(opt =>
{
    opt.LoginPath = new PathString("/login");
});

I have added a default filter, to ensure that all urls require authentication by default.

services.AddMvc(
    options =>
    {
        options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
    });

I have checked that the url /login does in fact load the login page, whilst /account/login does not, as expected.

edit: I have left the routes as is, (apart from changing the default controller and action)

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "default",
      template: "{controller=Site}/{action=Site}/{id?}");
});
question from:https://stackoverflow.com/questions/42105434/asp-net-core-change-default-redirect-for-unauthorized

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you check UseIdentity extension method here you will notice that it is using IdentityOptions not CookieAuthenticationOptions, so instead you must configure IdentityOptions:

services.Configure<IdentityOptions>(opt =>
{
    opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
});

Edit

For asp.net core 2.0: Identity cookie options are no longer part of IdentityOptions. Check mxmissile's answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...