【发布时间】:2016-08-29 16:23:33
【问题描述】:
我在同一个解决方案中有一个 WebApi 2 和一个 MVC Web 项目,在不同的 IIS 端口上运行。使用 jQuery AJAX 接收我的 Oauth 令牌后,在尝试调用授权的 Controller 方法时,我仍然收到 401 Unauthorized 错误消息。
启动:
public void Configuration(IAppBuilder app)
{
HttpConfiguration httpConfig = new HttpConfiguration();
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
ConfigureWebApi(httpConfig);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(httpConfig);
}
CustomOAuthProvider:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<UserManager>();
User user = await userManager.FindAsync(context.UserName, context.Password);
// checks with context.SetError() results.
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
}
- 将所有 Owin 包更新到最新版本(Web 项目不使用任何 Owin 功能,因此未在此处安装)。
- Api 和 Web 是不同的项目,但在同一台机器上,所以机器密钥相同。
- OAuth Token 配置位于 Startup.cs 中的 WebApi 配置之前。
- 声明:oAuthIdentity 由角色和管理员声明组成(http://schemas.microsoft.com/ws/2008/06/identity/claims/role:用户)
其他一切都按预期工作(web api、cors、令牌生成......),我做错了什么? (涉及的代码很多,所以如果我需要从我的项目中放置另一段代码,请告诉我。
编辑:
Ajax 调用(jumuro 的解决方案):
var token = sessionStorage.getItem(tokenKey); // Same as the generated login token
$.ajax({
type: 'POST',
// Don't forget the 'Bearer '!
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + token) },
url: 'http://localhost:81/api/auth/test', // Authorized method
contentType: 'application/json; charset=utf-8'
}).done(function (data) {
//
});
【问题讨论】:
标签: c# asp.net-web-api asp.net-mvc-5 oauth-2.0 claims-based-identity