1

Web API、AzureユーザーとのMVCアプリケーションの統合OWINを使用して認証が行われます。認証Cookieを削除し、api呼び出しのヘッダーにトークンを渡します。どうやってするの? Azure AD認証にMSAL.csファイルを使用します。 apiコールヘッダーにトークンを渡したい最初にMVCアプリケーションページをロードし、認証呼び出し後Web APIメソッドを呼び出します。 私はあなたがウェブAPIを呼び出したい場合はASP.NetのOpenID接続OWINミドルウェアを使用して紺碧の広告からユーザーが初めてサインした後、あなたはトークンを追加することができますMVCとWeb APIでの認証のためのヘッダーにトークンを渡す

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) 
      { 
       // Extract the code from the response notification 
       var code = notification.Code; 

       string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; 
       TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); 
       ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null); 
       try 
       { 
        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes); 
       } 
       catch (Exception ex) 
       { 
        //TODO: Handle 
        throw; 
       } 
      } 
+3

ようこそStackOverflow。 [最小限で完全で検証可能な例](https://stackoverflow.com/help/mcve)を入力してください。そうしないと、この質問は終了する可能性があります。質問に関連する詳細(たとえば、クッキーとヘッダー名)と、これまでに試したことを含めてください。 – NightOwl888

答えて

0

、紺碧のAD autherizationのための次のコードを使用ヘッダをリクエストする:

string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value; 
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; 
string authority = String.Format(CultureInfo.InvariantCulture, Startup.aadInstance, tenantID, string.Empty); 
ClientCredential credential = new ClientCredential(Startup.clientSecret); 

// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId. 
app = new ConfidentialClientApplication(Startup.clientId, redirectUri, credential, new NaiveSessionCache(userObjectID, this.HttpContext)){}; 
result = await app.AcquireTokenSilentAsync(new string[] { Startup.clientId }); 

HttpClient client = new HttpClient(); 
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serviceUrl + "/api/todolist"); 
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.Token); 

HttpResponseMessage response = await client.SendAsync(request); 

詳細については、code sampleを参照してください。

関連する問題