簡體   English   中英

ASP.NET 核心,更改未經授權的默認重定向

[英]ASP.NET core, change default redirect for unauthorized

我正在嘗試重定向到 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?}");
});

現在,隨着asp.net core 2.0的發布,這已更改為:

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

更多關於遷移到 2.0 的信息 還有更多關於從 2.0 遷移到 2.1 的信息。

如果您在此處檢查UseIdentity擴展方法,您會注意到它使用的是IdentityOptions而不是CookieAuthenticationOptions ,因此您必須配置IdentityOptions

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

編輯

對於 asp.net core 2.0:身份 cookie 選項不再是 IdentityOptions 的一部分。 檢查 mxmissile 的答案

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

資源

您可能還想嘗試使用StatusCodePages

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

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

添加身份驗證服務時,您需要在 startup.cs 中進行配置,尤其是在您使用 cookie 身份驗證方案時。

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

這就是我解決問題的方法,你應該試試......它肯定對你有用

更新:從 dot net core 2.1.x 開始,Identity 是從 SDK 構建的。 要共同簽署@mxmissile 答案,可以指定路徑。 要實現技巧路徑,請結合高級路由或重定向。 腳手架標識

我不會在現實生活中推薦 Serj Sagan 解決方案。 這在開發時可以完美地工作,但對於不同類型的用戶使用的真實應用程序可能會產生誤導。 讓我們看看下面的場景

  1. 我已通過身份驗證
  2. 我知道特定頁面的網址
  3. 我無權訪問該頁面

這意味着我將被重定向到登錄頁面,就好像我沒有經過身份驗證一樣,但事實並非如此。 我會更多地使用 mxmissile 解決方案

我個人使用的是 AddMvcCore,但如果您使用的是剃刀視圖,則需要添加 AddRazorViewEngine,如果您使用的是剃刀頁面,則需要添加 AddRazorPages

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM