使Web API身份验证返回401而不是重定向到登录页面

van*_*ian 14 c# asp.net authentication asp.net-mvc asp.net-web-api

我在Web MVC中使用带有OWIN身份验证的Web API.我<authentication>在Web.Config中使用我的Web MVC,所以它重定向到登录页面.

<authentication mode="Forms">
    <forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All" 
    timeout="43200" path="/" requireSSL="false" slidingExpiration="true" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

我正在使用[System.Web.Http.Authorize]属性来授权我的Web API.但不知何故,由于上述配置,API重定向到登录页面,就像我的MVC应用程序一样.

我想要做的是保持重定向Web MVC的功能,但返回401 for Web API.我怎样才能做到这一点?我应该为Web API创建自定义授权属性吗?

- 编辑 -

我发现WebApi.Owin中的这篇文章SuppressDefaultHostAuthentication的答案也抑制了webapi之外的身份验证

所以我只想在我的脑中加几行Startup.cs.我的所有控制器都配置了"api"前缀路由.

HttpConfiguration config = new HttpConfiguration();
//..some OWIN configuration
app.Map("/api", inner =>
{
  inner.UseWebApi(config);
});
Run Code Online (Sandbox Code Playgroud)

确保你放在app.Map()Web Api配置行之后.否则,它将给MVC应用程序带来错误.

Oyv*_*tad 8

在.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;
    }
Run Code Online (Sandbox Code Playgroud)


pec*_*eco 4

创建自定义AuthorizeAttribute

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您将来跳过 web.config 内容并使用 owin 设置身份验证,您可以这样做Startup.cs

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
});
Run Code Online (Sandbox Code Playgroud)