我有一个MVC 5应用程序,它使用单个用户帐户作为身份验证。
我向我的控制器文件夹中添加了一个WebApi2空控制器和一个post操作。
[Authorize]
public class AttendancesController : ApiController
{
[HttpPost]
public IHttpActionResult Attend([FromBody]int Id)
{
我运行应用程序,登录,然后使用Postman或Fidler发送一个post请求。我总是用我的应用程序的登录页面得到响应。
授权属性不适用于我的api控制器,但将在mvc控制器上工作。为什么?
发布于 2016-07-22 12:45:45
WebApi和MVC过滤器是不可互换的。
请参阅这篇文章,其中解释了如何创建WebApi过滤器(尽管使用了您可以忽略的IoC容器):https://damienbod.com/2014/01/04/web-api-2-using-actionfilterattribute-overrideactionfiltersattribute-and-ioc-injection/
特别是,开头的这一段:
重要的!Web的过滤器与MVC的过滤器不一样。Web过滤器可以在System.Web.Http.Filters命名空间中找到。
发布于 2017-11-24 02:38:47
如果遇到此问题,请确保验证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路由配置类,确保它调用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
复制相似问题