2

WebAPIバックエンドでAzureロールベースの認証を行う方法Asp.net MVCの例はたくさんありますが、フロントエンドがAngularのWebAPIはありません。私はwebappiとしてバックエンドと角度をつけて開発したWebサイトをホストし、Azureでホストし、AzureウェブサイトのAzure Activeディレクトリとして認証/許可を有効にしました。また、私はマニフェストファイルのロールのためのADアプリケーションのセットアップを行っています。私はウェブサイトをヒットした後、私は認証する必要があり、認証後、それは私のウェブサイトにリダイレクトされます。私のウェブサイトのロード中に私のwebapiを呼び出すと、クレームのある認証トークンが私のwebapiに渡されます。 webapiではInRoleか[Authorize(Roles = "admin")]をチェックしており、それに基づいてアクセスを許可しています。ただし、トークン・ロールでは、デフォルトではフローは流れません。だから私は、トークンから情報を抽出してロールを得るためにグラフapiに問い合わせ、それをグラフapiに渡して役割を果たす。私はOwin Startupクラスでクエリを実行して役割を取得していますが、成功することはできません。コードに何か問題がありますか、助けてください。コードは下にコピーされます。また、AngalでADAL JSライブラリを使用してADで認証することもできましたが、オプション "Authentication/Authorization"を使用してAzureウェブサイトで認証を有効にしたので、そうする必要はありません。ウェブサイトの認証の層はすべてのトークンの検証を行い、それをwebapiに転送します。Asp.net webapiバックエンドとフロントエンドをAngularとしてAzureでロールベースの認証を行う方法

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.IdentityModel.Tokens; 
using System.Linq; 
using Microsoft.Owin.Security; 
using Microsoft.Owin.Security.ActiveDirectory; 
using Owin; 
using System.Security.Claims; 
using System.Net; 
using System.Web; 
using System.IO; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using Microsoft.IdentityModel.Clients.ActiveDirectory; 
using Microsoft.Owin.Security.OAuth; 
using Microsoft.Azure.ActiveDirectory.GraphClient; 
using System.Threading.Tasks; 

namespace OneMap.Web 
{ 
    public partial class Startup 
    { 
     // Apply bearer token authentication middleware to Owin IAppBuilder interface. 
     private void ConfigureAuth(IAppBuilder app) 
     { 
      var tenantId = Common.Configuration.GetConfigurationSetting("ida:Tenant"); 
      // ADAL authentication context for our Azure AD tenant. 
      var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(
       $"https://login.windows.net/{tenantId}", true, TokenCache.DefaultShared); 

      // Secret key that can be generated in the Azure portal to enable authentication of a 
      // specific application (in this case our Web API) against an Azure AD tenant. 
      var applicationKey = Common.Configuration.GetConfigurationSetting("ida:Password"); 



      // Root URL for Azure AD Graph API. 
      var azureGraphApiUrl = "https://graph.windows.net"; 
      var graphApiServiceRootUrl = new Uri(new Uri(azureGraphApiUrl), tenantId); 
      var clientId = Common.Configuration.GetConfigurationSetting("ida:ClientId"); 
      // Add bearer token authentication middleware. 
      app.UseWindowsAzureActiveDirectoryBearerAuthentication(
       new WindowsAzureActiveDirectoryBearerAuthenticationOptions 
       { 
        // The id of the client application that must be registered in Azure AD. 
        TokenValidationParameters = new TokenValidationParameters { ValidAudience = clientId }, 
        // Our Azure AD tenant (e.g.: contoso.onmicrosoft.com). 
        Tenant = tenantId, 
        Provider = new OAuthBearerAuthenticationProvider 
        { 
         // This is where the magic happens. In this handler we can perform additional 
         // validations against the authenticated principal or modify the principal. 
         OnValidateIdentity = async context => 
           { 
            try 
            { 
           // Retrieve user JWT token from request. 
           var authorizationHeader = context.Request.Headers["Authorization"]; 
             var userJwtToken = authorizationHeader.Substring("Bearer ".Length).Trim(); 

           // Get current user identity from authentication ticket. 
           var authenticationTicket = context.Ticket; 
             var identity = authenticationTicket.Identity; 

           // Credential representing the current user. We need this to request a token 
           // that allows our application access to the Azure Graph API. 
           var userUpnClaim = identity.FindFirst(ClaimTypes.Upn); 
             var userName = userUpnClaim == null 
           ? identity.FindFirst(ClaimTypes.Email).Value 
           : userUpnClaim.Value; 
             var userAssertion = new UserAssertion(
           userJwtToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName); 

           // Credential representing our client application in Azure AD. 
           var clientCredential = new ClientCredential(clientId, applicationKey); 

           // Get a token on behalf of the current user that lets Azure AD Graph API access 
           // our Azure AD tenant. 
           var authenticationResult = await authenticationContext.AcquireTokenAsync(
           azureGraphApiUrl, clientCredential, userAssertion).ConfigureAwait(false); 

           // Create Graph API client and give it the acquired token. 
           var activeDirectoryClient = new ActiveDirectoryClient(
           graphApiServiceRootUrl,() => Task.FromResult(authenticationResult.AccessToken)); 

           // Get current user groups. 
           var pagedUserGroups = 
           await activeDirectoryClient.Me.MemberOf.ExecuteAsync().ConfigureAwait(false); 
             do 
             { 
            // Collect groups and add them as role claims to our current principal. 
            var directoryObjects = pagedUserGroups.CurrentPage.ToList(); 
              foreach (var directoryObject in directoryObjects) 
              { 
               var group = directoryObject as Group; 
               if (group != null) 
               { 
              // Add ObjectId of group to current identity as role claim. 
              identity.AddClaim(new Claim(identity.RoleClaimType, group.ObjectId)); 
               } 
              } 
              pagedUserGroups = await pagedUserGroups.GetNextPageAsync().ConfigureAwait(false); 
             } while (pagedUserGroups != null); 
            } 
            catch (Exception e) 
            { 
             throw; 
            } 
           } 
        } 
       }); 
     } 
    } 
} 

答えて

0

AFAIK、rolesクレームはid_tokenでのみ発行されました。アプリのマニフェスト(hereを参照)を変更したら、SPAを使用してid_tokenを取得し、id_token経由でロールに従ってWeb APIにアクセスできます。

OWINミドルウェアMicrosoft.Owin.Security.ActiveDirectoryを使用してWeb APIを保護しているため、認証/認可を使用する必要はありません。 SPAを認証するには、code sampleを参照してください。

+0

ありがとうございました。私はAngal ADALライブラリを使用する代わりにAuthentication/Authorizationを使用しようとしていましたが、ここですべてが提供されれば余分なコードを書かなければならないと思っていましたが、あなたが言ったように、それはid_tokenにのみ来るでしょう、私は角度のためのADALを実装するつもりです。したがって、トークンには2種類のトークン(Access tokenとid_token)があります。私は角度の付いた図書館を使ってID_Tokenを得ることを望みますか? –

+0

認証/承認機能を有効にしてWebアプリケーションを保護する場合、** easy auth **によって発行されたCookieとトークンを使用してWeb APIを呼び出すことができます。 Azure ADによって発行されたid_tokenを使用してWeb APIを呼び出すことはできません。このシナリオでは、役割の主張をサポートしていません。適切な解決策は、OWINコンポーネントを使用してWeb APIを保護し、id_tokenにangle adalライブラリを使用してロール情報を取得し、このトークンを使用してWeb APIを呼び出すことです。 –

関連する問題