簡體   English   中英

OAuth令牌授權(請求已被拒絕)

[英]OAuth token authorization (request has been denied)

我在不同IIS端口上運行的同一解決方案中有一個WebApi 2和一個MVC Web項目。 在使用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 oAuth中間件(具有單獨的Auth和資源服務器)時出現錯誤消息

  1. 將所有Owin軟件包更新到最新版本(Web項目不使用任何Owin功能,因此不會在此處安裝)。
  2. Api和web是不同的項目,但在同一台機器上,所以同樣的機器密鑰。
  3. OAuth令牌配置位於Startup.cs中的WebApi配置之前。
  4. 聲明:oAuthIdentity由角色和管理員聲明組成( http://schemas.microsoft.com/ws/2008/06/identity/claims/role:User

其他一切都按預期工作(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標頭。 請以此響應為例。 我希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM