2016-07-20 10 views
3

Ich habe eine MVC 5-Anwendung, die einzelne Benutzerkonten als Authentifizierung verwendet.AuthorizeAttribute funktioniert nicht auf Web-API-Controller in Mvc 5-Anwendung

Ich füge meinem Controller-Ordner einen leeren Web Api2-Controller und eine Post-Aktion hinzu.

Ich führe die Anwendung aus, ich logge mich ein und dann benutze ich Postman oder Fidler, um eine Postanfrage zu senden. Ich bekomme immer eine Antwort mit der Anmeldeseite meiner Anwendung.

Das [Autorisieren] -Attribut funktioniert nicht auf meinem api-Controller, aber funktioniert auf einem mvc-Controller. Warum?

Antwort

1

WebApi und MVC Filter sind nicht austauschbar.

Sehen Sie diesen Beitrag, der erklärt, wie WebAPI Filter (wenn auch mit IoC Container, die Sie ignorieren können) erstellen: https://damienbod.com/2014/01/04/web-api-2-using-actionfilterattribute-overrideactionfiltersattribute-and-ioc-injection/

Insbesondere diese Öffnung Absatz:

Wichtige! Filter für Web-API sind nicht identisch mit Filtern für MVC. Die Web-API-Filter befinden sich im System.Web.Http.Filters-Namespace.

0

Wenn Sie dieses Problem gestoßen sind, sollten Sie überprüfen, ob die Startup.Auth die app.UseOAuthBearerTokens hat, manchmal Sie die OAuthAuthorizationServerOptions erstellen, aber nicht gelten sie:

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

Dann schauen sie sich Ihre Web-Api Routen Konfigurationsklasse, stellen sie sicher, dass es die SuppressDefaultHostAuthentication ruft:

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()); 
} 
Verwandte Themen