我有一个使用个人用户帐户作为身份验证的MVC 5应用程序。
我将一个Web Api2空控制器添加到我的Controllers文件夹和一个帖子操作。
[Authorize]
public class AttendancesController : ApiController
{
[HttpPost]
public IHttpActionResult Attend([FromBody]int Id)
{
我运行应用程序,我登录然后我使用Postman或Fidler发送帖子请求。我总是通过我的应用程序的登录页面得到回复。
[Authorize]属性在我的api控制器上不起作用,但可以在mvc控制器上运行。为什么呢?
答案 0 :(得分:3)
WebApi和MVC过滤器不可互换。
请参阅此文章,其中介绍了如何创建WebApi过滤器(尽管您可以忽略IoC容器): https://damienbod.com/2014/01/04/web-api-2-using-actionfilterattribute-overrideactionfiltersattribute-and-ioc-injection/
特别是这个开头段落:
重要提示! Web API的过滤器与MVC的过滤器不同。 Web API过滤器位于System.Web.Http.Filters命名空间中。
答案 1 :(得分:1)
如果您遇到此问题,请务必验证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 Routes配置类,确保它调用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());
}