【问题标题】:OAuth token authorization (request has been denied)OAuth 令牌授权(请求已被拒绝)
【发布时间】: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);
}

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

  1. 将所有 Owin 包更新到最新版本(Web 项目不使用任何 Owin 功能,因此未在此处安装)。
  2. Api 和 Web 是不同的项目,但在同一台机器上,所以机器密钥相同。
  3. OAuth Token 配置位于 Startup.cs 中的 WebApi 配置之前。
  4. 声明: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


    【解决方案1】:

    您必须在 ajax 调用中包含带有不记名令牌的 Authorization 标头。请以reponse 为例。 希望对你有帮助。

    【讨论】:

    • 我试过但没有运气,你能确认我做得对吗? (编辑了我的问题)。
    • 成功了!我忘记在令牌之前放置“承载”。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2019-07-17
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多