【问题标题】:ASP.NET core, change default redirect for unauthorizedASP.NET 核心,更改未经授权的默认重定向
【发布时间】:2017-02-08 05:32:52
【问题描述】:

我正在尝试重定向到 ASP.NET MVC6 中的不同登录 url

我的帐户控制器登录方法有一个Route 属性来更改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

我已经配置了cookie认证路径如下:

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

我添加了一个默认过滤器,以确保默认情况下所有 url 都需要身份验证。

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

我检查了 URL /login 确实加载了登录页面,而 /account/login 没有按预期加载。

编辑:我已将路线保持原样(除了更改默认控制器和操作)

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "default",
      template: "{controller=Site}/{action=Site}/{id?}");
});

【问题讨论】:

  • 你能在Configure()中显示你的路由配置吗?
  • @juunas:我已经为问题添加了路线
  • 你在使用 asp.net-core-identity 吗?
  • @tmg,是的,我是,但是有了这个插件github.com/mrahhal/MR.AspNet.Identity.EntityFramework6 来支持 EF6,我认为重定向不会受到 EF 版本的影响,但我可能是错的。我仍在使用来自Microsoft.AspNetCore.Builderapp.UseIdentity()

标签: c# asp.net asp.net-core asp.net-identity asp.net-core-mvc


【解决方案1】:

asp.net core 2.0 现已推出,这已更改为:

services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn");

更多关于migrating to 2.0 here。以及 even more information 从 2.0 迁移到 2.1。

【讨论】:

  • 完美运行!感谢您拯救了这一天:D
【解决方案2】:

如果你检查UseIdentity扩展方法here你会注意到它使用的是IdentityOptions而不是CookieAuthenticationOptions,所以你必须配置IdentityOptions

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

编辑

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

【讨论】:

【解决方案3】:

由于asp.net core 2.0 如果您使用没有身份的cookie:

app.UseAuthentication();

// If you don't want the cookie to be automatically authenticated and assigned HttpContext.User, 
// remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => 
    {
        options.LoginPath = "/Account/LogIn";
        options.LogoutPath = "/Account/LogOff";
    });

source

【讨论】:

  • 这对 Core 3.0 仍然有效
【解决方案4】:

您可能还想尝试使用StatusCodePages

app.UseStatusCodePages(async context => {
    var response = context.HttpContext.Response;

    if (response.StatusCode == (int)HttpStatusCode.Unauthorized || 
        response.StatusCode == (int)HttpStatusCode.Forbidden)
        response.Redirect("/Error/Unauthorized");
});

【讨论】:

    【解决方案5】:

    添加身份验证服务时,您需要在 startup.cs 中进行配置,尤其是在您使用 cookie 身份验证方案时。

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options => 
            {
                options.LoginPath = new PathString("/login");
            }); 
    

    这就是我解决问题的方法,你应该试试......它肯定对你有用

    【讨论】:

      【解决方案6】:

      更新: 从 dot net core 2.1.x 开始,Identity 是从 SDK 构建的。 要共同签署@mxmissile 答案,可以指定路径。要实现技巧路径,请结合高级路由或重定向。Scaffold Identity

      【讨论】:

        【解决方案7】:

        我不会在现实生活示例中推荐 Serj Sagan 解决方案。这在开发时可以完美地工作,但对于不同类型的用户使用的真实应用程序可能会产生误导。让我们看看下面的场景

        1. 我已通过身份验证
        2. 我知道特定页面的网址
        3. 我无权访问该页面

        这意味着我将被重定向到登录页面,就好像我没有经过身份验证一样,但事实并非如此。我会更多地使用 mxmissile 解决方案

        我个人使用的是 AddMvcCore,但如果您使用的是 razor 视图,则需要添加 AddRazorViewEngine;如果您使用的是 razor 页面,则需要添加 AddRazorPages

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

        【讨论】:

        • (这篇文章似乎没有为问题提供quality answer。请编辑您的答案,或者将其作为对其他参考答案的评论发布)。
        猜你喜欢
        • 1970-01-01
        • 2016-12-09
        • 2020-10-30
        • 2012-01-23
        • 1970-01-01
        • 2021-08-22
        • 2020-04-25
        • 1970-01-01
        • 2010-11-01
        相关资源
        最近更新 更多