ASP.NET Core 2.0 disable automatic challenge

前端 未结 8 881
萌比男神i
萌比男神i 2020-11-28 13:40

After upgrading my ASP.NET Core project to 2.0, attempts to access protected endpoints no longer returns 401, but redirects to an (non-existing) endpoint in an attempt to le

8条回答
  •  北海茫月
    2020-11-28 14:07

    Another way to do this which is more DI/testing-friendly is to use AuthenticationSchemeOptions.EventsType (another answer points at it here). This will allow you to pull other components into the resolution process.

    Here's an example including registration and resolution which stops the default redirect to login on an unauthenticated request, and instead just returns with a hard 401. It also has a slot for any other dependencies which may need to know about unauthenticated requests.

    In Startup.cs:

    services
        .AddAuthentication("MyAuthScheme")
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            options.EventsType = typeof(MyEventsWrapper);
        };
    
    ...
    
    services.AddTransient();
    services.AddSingleton();
    

    Then, in MyEventsWrapper.cs:

    public class MyEventsWrapper : CookieAuthenticationEvents
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly IDependency _otherDependency;
    
        public MyEventsWrapper(IHttpContextAccessor accessor,
                               IDependency otherDependency)
        {
            _accessor = accessor;
            _otherDependency = otherDependency;
        }
    
        public override async Task RedirectToLogin(RedirectContext context)
        {
            context.Response.Headers.Remove("Location");
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await _otherDependency.Cleanup(_accessor.HttpContext);
        }
    }
    

提交回复
热议问题