且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.Net Core - API 身份验证错误没有重定向

更新时间:2023-02-15 13:04:21

更新 ASP.NET Core 2.x

授权在 ASP.NET Core 2.0 中有所改变.下面的答案仅对 ASP.NET Core 1.x 有效.对于 ASP.NET Core 2.0,请参阅此 answer 和此 GitHub 公告.

您似乎忘记了 app.UseIdentity() 也是 注册cookie中间件.

What you seems to have forgotten is that app.UseIdentity() also registers the cookie middleware.

var options = app.ApplicationServices.GetRequiredService<IOptions<IdentityOptions>>().Value;
app.UseCookieAuthentication(options.Cookies.ExternalCookie);
app.UseCookieAuthentication(options.Cookies.TwoFactorRememberMeCookie);
app.UseCookieAuthentication(options.Cookies.TwoFactorUserIdCookie);
app.UseCookieAuthentication(options.Cookies.ApplicationCookie);

并且 ASP.NET Core Identity 将 AutomaticChallange 设置为 true 用于 cookie (ApplicationCookie) 中间件 (查看源代码).因此重定向到 /Account/Login?ReturnUrl.您需要在 Identity 中禁用此选项.

and the ASP.NET Core Identity sets the AutomaticChallange to true for cookie (ApplicationCookie) middleware (see source). Hence the redirect to /Account/Login?ReturnUrl. You will need do disable this option in Identity.

services.AddIdentity(options =>
{
    options.Cookies.ApplicationCookie.AutomaticChallenge = false;
});

如果您真的想要拥有 Identity 的 Auth(登录网页)和 JWT,则需要根据 url 注册中间件.因此,即 app.UseIdentity() 只为非 api url 注册,而 Jwt 中间件只为以 /api 开头的 url 注册.

If you really want have Identity's Auth (login to web page) and JWT, you'd need to register the middlewares based on the url. So i.e. app.UseIdentity() is only registered for non-api urls and Jwt middleware is only registered for urls starting with /api.

您可以使用 .MapWhen (docs).

app.MapWhen(context => !context.Request.Path.StartsWith("/api"), branch => 
{
    branch.UseIdentity();
});

现在 branch.UseIdentity() 将只用于不以 /api 开头的 URL,通常是重定向到 /api 的 MVC 视图code>/Account/Login 是需要的.

Now branch.UseIdentity() will only be used, for URLs which don't start with /api, which usually are your MVC views where the redirect to /Account/Login is desired.