Asp.net web api oauth导致400个错误请求
本文关键字:400个 错误 请求 导致 oauth net web api Asp | 更新日期: 2023-09-27 18:10:54
代码如下:当我使用邮差"/token"发出单独的请求时,它可以工作。但是当我从客户端代码调用时,它失败了,有400个错误请求。当我调试时,我可以看到"GrantResourceOwnerCredentials"方法没有被击中。任何想法?
客户机代码return this.$http({
url: this.config.remoteUri.account.login,
method: "POST",
data: { UserName: user.name, Password: user.password, grant_type: "password" },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, status, headers, config) {
// $scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
// $scope.status = status;
});
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
Provider = new ActiveDirectoryAuthorizationProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
}
Webapi配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
授权过滤器
public class ActiveDirectoryAuthorizationProvider : OAuthAuthorizationServerProvider
{
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "authorization" });
context.RequestCompleted();
return Task.FromResult(0);
}
return base.MatchEndpoint(context);
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
首先要做的是:发送请求(OPTIONS+POST)时必须设置Origin header
我在其他线程中见过这个过滤器的实现,但这里是我的,它实际上为我工作-本地和生产服务器:
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
{
if (!context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Origin"))
context.OwinContext.Response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Origin", new[] { ConfigurationManager.AppSettings["allowedOrigin"] });
if (!context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Headers"))
context.OwinContext.Response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", new[] { "Accept", "Content-Type", "Authorization", "Cache-Control", "Pragma", "Origin" });
if (!context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Methods"))
context.OwinContext.Response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" });
context.MatchesTokenEndpoint();
context.RequestCompleted();
return Task.FromResult<object>(null);
}
return base.MatchEndpoint(context);
}
如果您仍有问题,请回复更多细节。请注意,需要AppendCommaSeparatedValues才能在IE和Edge