ASP.NET Core 2.0 disable automatic challenge

前端 未结 8 884
萌比男神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 13:50

    I found that in most cases the solution is to override

    OnRedirectToLogin

    But in my app I was using multiple authentication policies and overriding of the OnRedirectToLogin did not work for me. The solution in my case it was to add a simple middleware to redirect the incoming request.

    app.Use(async (HttpContext context, Func next) => {
        await next.Invoke(); //execute the request pipeline
    
        if (context.Response.StatusCode == StatusCodes.Status302Found && context.Response.Headers.TryGetValue("Location", out var redirect)) {
            var v = redirect.ToString();
            if (v.StartsWith($"{context.Request.Scheme}://{context.Request.Host}/Account/Login")) {
                context.Response.Headers["Location"] = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}";
                context.Response.StatusCode = 401;
            }
        }
    });
    
    

提交回复
热议问题