AuthorizeAttribute not working on Web Api Controller in Mvc 5 application

吃可爱长大的小学妹 提交于 2020-01-03 11:28:09

问题


I have an MVC 5 application that uses Individual User Accounts as authentication.

I add an Web Api2 empty controller to my Controllers folder, and an post action.

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

I run the application, i log in and then i use Postman or Fidler to send a post request. I always get response with the Login page of my application.

The [Authorize] attribute does not work on my api controller but will work on a mvc controller. Why?


回答1:


WebApi and MVC filters aren't interchangeable.

See this post which explains how to create WebApi filters (albeit with IoC containers which you can ignore): https://damienbod.com/2014/01/04/web-api-2-using-actionfilterattribute-overrideactionfiltersattribute-and-ioc-injection/

In particular, this opening paragraph:

Important! Filters for Web API are not the same as filters for MVC. The Web API filters are found in the System.Web.Http.Filters namespace.




回答2:


If you have encountered this issue, be sure to verify that the Startup.Auth has the app.UseOAuthBearerTokens, sometimes you create the OAuthAuthorizationServerOptions but do not apply them:

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);

Then check your Web Api Routes configuration class, be sure that it calls the 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());
}


来源:https://stackoverflow.com/questions/38485446/authorizeattribute-not-working-on-web-api-controller-in-mvc-5-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!