使Web API身份验证返回401,而不是重定向到登录页面 [英] Make Web API authentication return 401 instead of redirect to login page
问题描述
我在Web MVC中具有带有OWIN身份验证的Web API.
我在Web.Config中将<authentication>
用于我的Web MVC,因此它将重定向到登录页面.
I have Web API with OWIN Authentication in Web MVC.
I'm using <authentication>
in Web.Config for my Web MVC so it's redirecting to login page.
<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应用程序相同,
I'm using [System.Web.Http.Authorize]
attribute to authorize my Web API. But somehow, the API redirecting to login page same like my MVC app because of above configuration.
我要做的是为Web MVC保留重定向功能,但为Web API返回401.我怎样才能做到这一点?我应该为Web API创建自定义授权属性吗?
what I want to do is keep redirecting function for the Web MVC but returning 401 for Web API. How can I achieve this? should I create a custom authorization attribute for Web API?
-编辑-
我从此帖子中找到了答案 WebApi.Owin中的SuppressDefaultHostAuthentication也抑制了身份验证外部webapi
I found the answer from this post SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi
所以我只需在Startup.cs
中添加几行.我为所有控制器配置了"api"前缀路由.
So I just add a few lines into my Startup.cs
. I had all my controllers configured with a "api" prefix route.
HttpConfiguration config = new HttpConfiguration();
//..some OWIN configuration
app.Map("/api", inner =>
{
inner.UseWebApi(config);
});
确保将app.Map()
放在Web Api配置行之后.否则,它将使MVC应用程序出错.
make sure you put app.Map()
after Web Api Configuration lines. Otherwise, it will give error to MVC application.
推荐答案
创建自定义AuthorizeAttribute
:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");
}
}
如果将来您跳过web.config内容并使用owin设置身份验证,则可以在Startup.cs
中执行以下操作:
If you in the future skip the web.config stuff and use owin to setup your authentication, you could in your Startup.cs
do:
var provider = new CookieAuthenticationProvider();
var originalHandler = provider.OnApplyRedirect;
provider.OnApplyRedirect = context =>
{
if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api")))
{
context.RedirectUri = new Uri(context.RedirectUri).PathAndQuery;
originalHandler.Invoke(context);
}
};
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieName = FormsAuthentication.FormsCookieName,
LoginPath = new PathString("/Account/LogOn"),
ExpireTimeSpan = TimeSpan.FromMinutes(240),
Provider = provider
});
这篇关于使Web API身份验证返回401,而不是重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!