我正在开发asp.net web API 2.0中的CORS,我必须使用Jquery向WebAPI发出POST请求。我已经从包括Stackoverflow本身在内的众多资源中学到了很多教程,但无论尝试了什么,结果都是相同的" unsupported_grant类型"错误。
我用来执行实际POST请求的Jquery代码使用以下命令执行:
$('#myForm').submit(function(event) {
$.ajax({
type:'POST',
url:'https://sandbox.datamotion.com:4334/idvs/token?' + $('#myForm').serialize(),
//data:vm,
contentType:'application/x-www-form-urlencoded',
crossDomain: true,
dataType: 'json'
})
.done(function(data) {
alert(data.access_token);
})
.error(function(objAJAXRequest, strError) {
alert(objAJAXRequest.responseText);
}),
event.preventDefault();
});
});
使用以下代码设置Access-Control-Allow-Origin,Access-Control-Allow-Headers和Access-Control-Allow-Methods:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
if (context.Request.Headers.Get("Origin") != null)
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { context.Request.Headers.Get("Origin") });
else
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "x-requested-with" });
context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET", "PUT", "POST", "DELETE", "OPTIONS" });
}
使用Owin上下文完成配置授权并使用令牌。以下代码适用于此。
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(12),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
设置Origin是为了强制请求使用适当的网络服务器,因为&#34; *&#34;并没有为&#34; Access-Control-Allow-Origin&#34;方法
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
if (context.Request.Headers.Get("Origin") != "null")
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { context.Request.Headers.Get("Origin") });
else
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
}
在Firefox中调试时显示的请求中发送以下内容:
**Accept**: application/json, text/javascript, */*; q=0.01
**Accept-Encoding**: gzip, deflate
**Accept-Language**: en-US,en;q=0.8
**Connection**: keep-alive
**Content-Length**: 0
**Content-Type**: application/x-www-form-urlencoded
**Host**: sandbox.datamotion.com:4334
**Origin**: http://localhost:83
**Referer**: http://localhost:83/
**User-Agent**: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
URL编码并放入请求的参数如下:
**grant_type**: password
**username**: kylec
**password**: pass
在回复中,我收到以下内容:
**Access-Control-Allow-Credentials**: true
**Access-Control-Allow-Headers**: x-requested-with
**Access-Control-Allow-Headers**: Content-Type,Accept,Authorization
**Access-Control-Allow-Methods**: GET
**Access-Control-Allow-Methods**: PUT
**Access-Control-Allow-Methods**: POST
**Access-Control-Allow-Methods**: DELETE
**Access-Control-Allow-Methods**: OPTIONS
**Access-Control-Allow-Origin**: http://localhost:83
**Access-Control-Expose-Headers**: Access-Control-Allow-Origin
**Cache-Control**: no-cache
**Content-Length**: 34
**Content-Type**: application/json;charset=UTF-8
**Date**: Tue, 17 Nov 2015 21:53:09 GMT
**Expires**: -1
**Pragma**: no-cache
**Server**: Microsoft-IIS/8.5
**X-Powered-By**: ASP.NET