c# – OAuth令牌授权(请求已被拒绝)

我在不同IIS端口上运行的同一解决方案中有一个WebApi 2和一个MVC Web项目.在使用jQuery
AJAX收到我的Oauth令牌后,我在尝试调用授权的Controller方法时仍然收到401 Unauthorized错误消息.

《c# – OAuth令牌授权(请求已被拒绝)》

启动:

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);
}

认为我从I get “Authorization has been denied for this request.” error message when using OWIN oAuth middleware (with separate Auth and Resource Server)开始尝试:

>将所有Owin软件包更新到最新版本(Web项目不使用任何Owin功能,因此不在此处安装).
> Api和Web是不同的项目,但在同一台机器上,所以同样的机器密钥.
> OAuth令牌配置在Startup.cs中的WebApi配置之前.
>声明:oAuthIdentity由角色和管理员声明组成(http://schemas.microsoft.com/ws/2008/06/identity/claims/role:用户)

其他一切都按预期工作(web api,cors,token generation,……),我做错了什么? (涉及到很多代码,所以如果我需要从我的项目中添加其他代码,请告诉我.

编辑:

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) {
    //
});

最佳答案 您必须在ajax调用中包含带有承载令牌的Authorization标头.请以此
reponse为例.

我希望它有所帮助.

点赞