ASP.NET WEB API 2 OWIN 身份验证不支持 grant_Type [英] ASP.NET WEB API 2 OWIN Authentication unsuported grant_Type
问题描述
您好,我正在尝试在我的 ASP.NET Web API 2 项目中设置 OAuth 不记名令牌身份验证.我有两个项目,一个是 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 类.从这个类我只能设法让我的代码调用这个方法:
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);
});
}
我第一次尝试将 post 调用 dataType 设置为 json,但出现此错误:
My first attempt I have set the post calls dataType to json and I got this errors:
OPTIONS ...:3439/Token 400 (Bad Request) jquery.js:7845
OPTIONS ...:3439/Token 400 (Bad Request) jquery.js:7845
OPTIONS ...:3439/Token No 'Access-Control-Allow-Origin'请求的资源上存在标头.起源'...: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
XMLHttpRequest 无法加载 ...3439/令牌.不请求中存在Access-Control-Allow-Origin"标头资源.因此不允许使用原点 '...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.
三个点代表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:password",就像我一样.
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 属性 get 由 Durandal Framework 设置为我的 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?
推荐答案
将以下代码行添加到 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[] { "*" });
有关更多信息,请参阅:web-api-2-0-cors-and-个人账户身份
for more information refer to: web-api-2-0-cors-and-individual-account-identity
这篇关于ASP.NET WEB API 2 OWIN 身份验证不支持 grant_Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!