ASP.NET核心,更改未经授权的默认重定向 [英] ASP.NET core, change default redirect for unauthorized

查看:96
本文介绍了ASP.NET核心,更改未经授权的默认重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重定向到ASP.NET MVC6中的另一个登录URL

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

我的帐户控制器登录方法具有Route属性来更改网址.

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

当尝试访问未授权的页面时,我被重定向到无效的URL,它应该只是/login,但是我却得到了 http://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex

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

我已经配置了cookie身份验证路径,如下所示:

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

我检查了URL /login是否确实加载了登录页面,而/account/login并未按预期加载.

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

推荐答案

如果您检查UseIdentity扩展方法

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

修改

对于asp.net core 2.0: 身份cookie选项不再是IdentityOptions的一部分.检查mxmissile的 answer .

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

这篇关于ASP.NET核心,更改未经授权的默认重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆