programing

ASP.NET 코어, 권한 없는 경우 기본 리디렉션 변경

telecom 2023. 10. 27. 21:44
반응형

ASP.NET 코어, 권한 없는 경우 기본 리디렉션 변경

ASP의 다른 로그인 URL로 리디렉션을 시도하는 중입니다.NET MVC6

내 계정 컨트롤러 로그인 방법은Routeurl을 변경하기 위해 attribute를 지정합니다.

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

인증되지 않은 페이지에 액세스하려고 하면 잘못된 URL로 리디렉션됩니다./login하지만 대신에 나는

쿠키 인증 경로를 다음과 같이 구성했습니다.

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예상대로 그렇지 않습니다.

edit: 경로를 그대로 두었습니다. (기본 컨트롤러 및 작업 변경과 별도로)

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로 마이그레이션하는 방법에 대한 자세한 정보도 제공합니다.

최신 Asp에 대한 업데이트입니다.NET 7.0, 감사 @Checkkan:

services.AddAuthentication().AddCookie(options => options.LoginPath = "/Login"); 

확인하시면UseIdentity여기서 확장 방법을 사용하는 것을 알게 될 것입니다.IdentityOptions것은 아니다.CookieAuthenticationOptions, 대신에 당신은 구성해야 합니다.IdentityOptions:

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

편집

asp.net core 2.0의 경우: Identity cookie 옵션은 Identity 옵션에 더 이상 포함되지 않습니다.mxmissile의 을 확인합니다.

부터asp.net core 2.0ID가 없는 쿠키를 사용하는 경우:

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 에서 이를 구성해야 합니다.

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

이렇게 해서 문제를 풀었으니, 당신이 한번 해보세요.당신에게 분명히 도움이 될 겁니다.

업데이트: 닷넷 코어 2.1.x 기준으로 아이덴티티는 SDK에서 스캐폴드됩니다.@mxmissile 답변에 공동 서명하려면 경로를 지정할 수 있습니다.트릭 경로를 제거하려면 고급 라우팅 또는 리디렉션과 결합합니다.스캐폴드 아이덴티티

실제 사례에서 Serj Sagan 솔루션을 추천하지는 않습니다.개발할 때는 완벽하게 작동하지만 오해의 소지가 있는 여러 유형의 사용자가 사용하는 실제 응용프로그램의 경우에는 완벽하게 작동합니다.아래 시나리오를 살펴보겠습니다.

  1. 인증된 사용자임
  2. 특정 페이지의 URL을 알고 있습니다.
  3. 해당 페이지에 액세스할 권한이 없습니다.

인증되지 않은 것처럼 로그인 페이지로 리디렉션된다는 의미인데 그렇지 않습니다.mxmissile 솔루션을 더 많이 사용하고 싶습니다.

개인적으로 AddMvcCore를 사용하고 있지만 면도기 보기를 사용하는 경우 AddRazorViewEngine을 추가하고 면도기 페이지를 사용하는 경우 AddRazorPages를 추가해야 합니다.

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

언급URL : https://stackoverflow.com/questions/42105434/asp-net-core-change-default-redirect-for-unauthorized

반응형