在Mvc 5应用程序中,AuthorizeAttribute在Web Api Controller上不起作用。

9

我有一个使用个人用户帐户进行身份验证的MVC 5应用程序。

我向我的控制器文件夹中添加了一个Web Api2空控制器和一个post操作。

[Authorize]
public class AttendancesController : ApiController
{
    [HttpPost]
    public IHttpActionResult Attend([FromBody]int Id)
    {

我运行应用程序,登录后使用Postman或Fidler发送POST请求。然而,我总是得到我的应用程序的登录页面作为响应。
为什么在我的API控制器上不起作用[Authorize]属性,但在MVC控制器上可以?
2个回答

4

1
System.Web.Http.Filters 命名空间包含 AuthorizationFilterAttribute 类。但我认为,OP 需要一个在 System.Web.Http 命名空间中定义的 AuthorizeAttribute 实例。 - Alexander

2
如果您遇到此问题,请确保验证Startup.Auth中是否包含app.UseOAuthBearerTokens。有时您会创建OAuthAuthorizationServerOptions,但未应用它们:
Startup.Auth.cs
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new OAuthServerProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);

请检查您的Web Api路由配置类,确保它调用了SuppressDefaultHostAuthentication方法: WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    // Configure Web API to use only bearer token authentication.
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultController",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { id = RouteParameter.Optional }
    );

    // Register Additional Filters
    config.Filters.Add(new WebApiPlatformFilters());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接