我在 Web MVC 中有带有 OWIN 身份验证的 Web API。
我正在使用 <authentication>
在我的 Web MVC 的 Web.Config 中,因此它重定向到登录页面。
<authentication mode="Forms">
<forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All"
timeout="43200" path="/" requireSSL="false" slidingExpiration="true" />
</authentication>
我正在使用 [System.Web.Http.Authorize]
属性来授权我的 Web API。但不知何故,由于上述配置,API 重定向到登录页面与我的 MVC 应用程序相同。
我想做的是继续为 Web MVC 重定向功能,但为 Web API 返回 401。我怎样才能做到这一点?我应该为 Web API 创建自定义授权属性吗?
--编辑--
我从这篇文章中找到了答案SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi
所以我只是在我的 Startup.cs
中添加了几行.我为所有 Controller 配置了“api”前缀路由。
HttpConfiguration config = new HttpConfiguration();
//..some OWIN configuration
app.Map("/api", inner =>
{
inner.UseWebApi(config);
});
确保你输入 app.Map()
在 Web Api 配置行之后。否则,它会给 MVC 应用程序带来错误。
最佳答案
在 .NET Core 中我是这样解决的,Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.Name = "AuthCookie";
options.Events.OnRedirectToAccessDenied = UnAuthorizedResponse;
options.Events.OnRedirectToLogin = UnAuthorizedResponse;
})
....
}
internal static Task UnAuthorizedResponse(RedirectContext<CookieAuthenticationOptions> context)
{
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
return Task.CompletedTask;
}
关于c# - 使 Web API 身份验证返回 401 而不是重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880817/