ASP.NET WEB API 2 OWIN认证unsuported grant_Type [英] ASP.NET WEB API 2 OWIN Authentication unsuported grant_Type
问题描述
我想建立的OAuth bearrer令牌认证在我的ASP.NET Web API 2项目。
我有两个项目之一将是在WEB API项目,另一个是SPA项目。
Hi I am trying to set up OAuth bearrer token authentication in my ASP.NET Web API 2 project. I have two project one will be the WEB API Project and the other a SPA project.
这是我迄今所做的:
我创建了OWIN启动类:
I have created the OWIN Startup class:
[assembly: OwinStartup(typeof(CodeArt.WebApi.App_Start.Startup))]
namespace CodeArt.WebApi.App_Start
{
public class Startup
{
static Startup()
{
PublicClientId = "self";
UserManagerFactory = () => new UserManager<UserModel>(new UserStore<UserModel>());
OAuthOptions = new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/Token"),
Provider = new OAuthAuthorizatonServer(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static Func<UserManager<UserModel>> UserManagerFactory { get; set; }
public static string PublicClientId { get; private set; }
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalBearer);
app.UseOAuthBearerTokens(OAuthOptions);
}
}
我配置的Web API只使用承载令牌认证:
I have configured Web API to use only bearer token authentication:
private static void ConfigureBearerTokenAuthentication(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));
}
我配置的Web API支持CORS:
I have configured WEB API to support CORS:
private static void ConfigureCrossOriginResourseSharing(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
我创建了OAuthAuthorizationServerProvider class.From这个类我只是设法让我的code调用此方法:
I have created the OAuthAuthorizationServerProvider class.From this class I only managed to make my code call this method:
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
if(context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
if条件里面,它总是被执行。
The if condition inside of it always gets executed.
在我的水疗项目,我有以下几点:
On my spa project I have the following:
这是我的视图模型:
var vm = {
grant_type: "password",
userName: ko.observable(),
password: ko.observable()
};
当登录按钮被点击我调用这个函数:
When the login button gets clicked I call this function:
var http = {
post:function(url, data) {
return $.ajax({
url: url,
data: data,
type: 'POST',
contentType: 'application/json',
dataType: 'jsonp'
});
}
}
function loginClick() {
var model = ko.mapping.toJS(vm.loginModel);
var rez = $.param(model);
http.post("http://localhost:3439/Token", rez)
.done(function (data) {
console.log(data);
})
.fail(function(eror, stuff, otherstuff) {
console.log(eror);
console.log(stuff);
console.log(otherstuff);
});
}
我的,我设置了后第一次尝试调用数据类型为JSON和我得到这个错误:
My first attempt I have set the post calls dataType to json and I got this errors:
选项...:3439/400令牌(错误请求)的jquery.js:7845
OPTIONS ...:3439/Token 400 (Bad Request) jquery.js:7845
选项...:3439 /令牌的访问控制允许原产地
头是在被请求的资源present。起源
'...:3304,因此没有允许访问。
的jquery.js:7845
OPTIONS ...:3439/Token No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...:3304' is therefore not allowed access. jquery.js:7845
XMLHtt prequest无法加载... 3439 /令牌。没有
访问控制允许来源标头present的要求
资源。因此出身...... 3304是不允许的
访问。
XMLHttpRequest cannot load ...3439/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...3304' is therefore not allowed access.
3点重新present 的http://本地主机
The 3 dots represent http://localhost
.
第二次角落找寻我将它设置为数据类型和JSONP我回来的规定不支持unsupported_grant_type错误。
The second time arround I set it datatype to jsonp and I got back an error that stated unsupported "unsupported_grant_type".
两种电话使其向ValidateClientAuthentication我上面提到的,但他们都送回作为一个失败的请求。
Both calls make it to ValidateClientAuthentication that I mentioned above but they are both sent back as a failed request.
现在我猜测,这个问题更关系到我是如何发送数据,而不是因为grand_type在Visual Studion设置SPA模板的批类型grant_type:密码像我一样
Now I am guessing that the problem is more related to how I am sending data instead of the grand_type because the SPA template in Visual Studion set's the grant type to grant_type: "password" like I did.
我也看过,我必须序列数据不是JSON发送为了这个来这里工作是,得到的发送确切的JSON序列数据:
\"grant_type=password&userName=aleczandru&password=happynewYear&moduleId=models%2FappPostModels%2FloginModel\"
Also I have read that I have to serialize the data not send it in json in order for this to work here is the exact json serialized data that get's sent: "grant_type=password&userName=aleczandru&password=happynewYear&moduleId=models%2FappPostModels%2FloginModel"
该模型id属性获取的设置为我所有的对象由迪朗达尔框架我SPA的模板。
The model id property get's set to all my object in my SPA template by Durandal Framework.
谁能告诉我什么,我做错了,我一直试图弄清楚这一点在最后两天?
Can anyone tell me what I am doing wrong I have been trying to figure this out for the last two days?
推荐答案
code的下面一行添加到 GrantResourceOwnerCredentials
,这将头添加到响应
Add the following line of code to GrantResourceOwnerCredentials
, which will add the header to the response.
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
有关更多信息,请参阅:
<一href=\"http://oscarmeszar.com/web-api-2-0-cors-and-individual-account-identity/\">web-api-2-0-cors-and-individual-account-identity
for more information refer to: web-api-2-0-cors-and-individual-account-identity
这篇关于ASP.NET WEB API 2 OWIN认证unsuported grant_Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!