2017-05-09 12 views
0

私はADAP4を実装しようとしています - 認証のためのOAuth(OpenID接続)とwebapi通信のwebapp。MSIS9649:無効なOAuth要求を受信しました。 'assertion'パラメータの値が有効なアクセストークンではありません

私はそれに応じてADFSアプリケーショングループを構成し、認証のためにwebappでOpenIdconnectauthパイプラインを使用しました。 webapiを呼び出すために、私がクライアントクレデンシャル付与だけを使用してaccesstokenを要求すると、有効なアクセストークンを受け取り、apiにアクセスできるようになります。しかし、アクセストークンにはwebapiの終わりから必要なユーザーの詳細はありません。

私は、bootstrapcontext.tokenからUserAssertionオブジェクトを作成してみました。しかし今度は、私がアクセストークンを要求すると、私はタイトルで述べたようにこのエラーを受け取ります。ここで

は、コードスニペットです:ここで

AuthenticationContext authContext = null; 
AuthenticationResult result = null; 
authContext = new AuthenticationContext(Startup.authority, false); 
ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey); 
string usercheck = User.Identity.Name; //For checking, returns username 

var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; 
string username = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value; 
string userAccessToken = bootstrapContext.Token; 
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", username); 

string accessToken = null; 
HttpClient httpClient = new HttpClient(); 

try { 
//result = authContext.AcquireTokenAsync(Startup.apiResourceId, credential).Result; // This works fine but no user details in the token 
result = authContext.AcquireTokenAsync(Startup.apiResourceId, credential, userAssertion).Result; 
} 

はStartup.ConfigureAuth(IAppBuilderアプリ)がWebアプリケーションとWEBAPIの両方でどのように見えるかです:

Webアプリケーションでは:

public void ConfigureAuth(IAppBuilder app) 
{ 
      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 

      app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

      app.UseOpenIdConnectAuthentication(
       new OpenIdConnectAuthenticationOptions 
       { 
        ClientId = clientId, 
        AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType, 

        MetadataAddress = metadataAddress, 
        PostLogoutRedirectUri = postLogoutRedirectUri, 
        RedirectUri = postLogoutRedirectUri, 
        TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() 
        { 
         SaveSigninToken = true 
        }, 

        ResponseType = "code id_token", 
        Notifications = new OpenIdConnectAuthenticationNotifications 
        { 
         AuthenticationFailed = context => 
         { 
          context.HandleResponse(); 
          context.Response.Redirect("/Error?message=" + context.Exception.Message); 
          return Task.FromResult(0); 
         } 
        } 
       }); 
} 

そしてwebapiでは:

public void ConfigureAuth(IAppBuilder app) 
     { 
      JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); 
      app.UseActiveDirectoryFederationServicesBearerAuthentication(
       new ActiveDirectoryFederationServicesBearerAuthenticationOptions 
       { 
        MetadataEndpoint = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"], 
        TokenValidationParameters = new TokenValidationParameters() { 
         SaveSigninToken = true, 
         ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] 
        } 
       }); 
     } 

私はuserassertionに渡しているトークンが間違っていると思います。しかし、どうすればこの問題を解決できますか?アクセストークンにユーザーの詳細を取得できる他の方法はありますか。誰でも私たちがこの問題を解決するのを助けることができたら本当に感謝していますか?

ありがとうございました。

答えて

1

MVCアプリケーションでAPIと通信するには、認証コードフローを使用する必要があります。あなたが電話をかける準備ができているときあなたはStartup.ConfigureAuth(IAppBuilderアプリ)からOpenIdConnectAuthenticationOptionsに通知を経由してAuthorizationCodeReceivedイベントを処理する必要があることを行うためにVittorio has a nice post on it here, although it talks about azure.

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions { 
     ... 
     Notifications = new OpenIdConnectAuthenticationNotifications { 
      AuthorizationCodeReceived = async code => { 
       ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey); 
       AuthenticationContext authContext = new AuthenticationContext(Startup.authority, false); 
       AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
        code.Code, 
        new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), 
        credential, 
        Startup.apiResourceId); 
      } 
     } 

あなたは黙って自分のトークンを取得します。

var authContext = new AuthenticationContext(Startup.authority, false); 
var credential = new ClientCredential(Startup.clientId, Startup.appKey); 
var claim = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 
var userId = new UserIdentifier(claim, UserIdentifierType.UniqueId); 

result = await authContext.AcquireTokenSilentAsync(
    Startup.apiResourceId, 
    credential, 
    userId); 

HttpClient httpClient = new HttpClient(); 
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer", 
    result.AccessToken); 
関連する問題