4

WebApi 2とMVC Webプロジェクトは、同じソリューション内で異なるIISポートで実行されています。 jQuery AJAXを使用してOauthトークンを受け取った後、認可されたコントローラメソッドを呼び出そうとすると、401 Unauthorizedのエラーメッセージが表示されます。OAuthトークン認証(要求は拒否されました)

enter image description here

スタートアップ:

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トークンの設定は、Startup.csのWebApi設定の前に行われます。
  4. クレームが行われます(:ユーザーhttp://schemas.microsoft.com/ws/2008/06/identity/claims/role

すべて予想通り、他の作品(ウェブAPI、CORS、トークン生成、...)、私は何をしていますoAuthIdentityが役割と管理者の請求のうち、構成されて間違っている? (関連するコードがたくさんあるので、私は私のプロジェクトからコードの他の部分を配置する必要がある場合は私に知らせて

EDIT:

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

答えて

1

あなたはAJAX呼び出しにおけるベアラトークンでAuthorizationヘッダーを含める必要があります。一例として、このreponseを参照してください。 私は、私が試した

+0

。それは役立ちます願っていますが、運なしで、あなたがCONFすることができます私はそれを正しくやっていることを確認しますか? (私の質問を編集した)。 – Sam

+1

それは働いた!トークンの前に「ベアラー」を置くのを忘れてしまった。どうもありがとう! – Sam

+0

@Sam、あなたは大歓迎です! – jumuro

関連する問題