ASP.NET Core 2.0 disable automatic challenge

前端 未结 8 883
萌比男神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<MyEventsWrapper>();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    

    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<CookieAuthenticationOptions> context)
        {
            context.Response.Headers.Remove("Location");
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await _otherDependency.Cleanup(_accessor.HttpContext);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 14:15

    After some research, I found we can deal with this problem though the bellow approach:

    We can add two Authentication scheme both Identity and JWT; and use Identity scheme for authentication and use JWT schema for challenge, JWT will not redirect to any login route while challenge.

    services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
    
    services.AddAuthentication((cfg =>
    {
        cfg.DefaultScheme = IdentityConstants.ApplicationScheme;
        cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })).AddJwtBearer();
    
    0 讨论(0)
提交回复
热议问题