4

Azure Active Directory (AAD) を使用して単純な MVC アプリケーションをセットアップしました。

アプリケーションからアプリケーション ロールとグループを管理するには、AAD Graph API にクエリを実行する必要があります。

クラスではStartup、次のように AccessToken を受け取りました。

public void ConfigureAuth(IAppBuilder app)
{
    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = Constants.ClientId,
            Authority = Constants.Authority,
            PostLogoutRedirectUri = Constants.PostLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                AuthorizationCodeReceived = (context) =>
                {
                    var code = context.Code;
                    var credential = new ClientCredential(Constants.ClientId, Constants.ClientSecret);
                    var signedInUserId =
                        context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    var authContext = new AuthenticationContext(Constants.Authority,
                        new TokenDbCache(signedInUserId));
                    var result = authContext.AcquireTokenByAuthorizationCode(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential,
                        Constants.GraphUrl);

                    var accessToken = result.AccessToken;                        
                    return Task.FromResult(0);
                }
            }
        });
}

クラスをインスタンス化するActiveDirectoryClientには、 AccessToken を渡す必要があります。

var servicePointUri = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(servicePointUri, tenantID);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
        async () => await GetTokenForApplication());

AccessToken をクレームとして保存することが適切な解決策であるかどうか疑問に思っています (Startupクラスに追加する行)。

context.AuthenticationTicket.Identity.AddClaim(new 
    Claim("OpenId_AccessToken", result.AccessToken));

EDITトークンはすでに保存されています..

それを得る !!!ありがとう、ジョージ。TokenDbCacheしたがって、私のトークンはクラスを使用してデータベースに保存されています。

サンプルに従って(コントローラーの1つで)再度取得するには:

public async Task<string> GetTokenForApplication()
{
    string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
    string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

    // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
    ClientCredential clientcred = new ClientCredential(clientId, appKey);
    // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
    AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new TokenDbCache<ApplicationDbContext>(signedInUserID));
    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    return authenticationResult.AccessToken;
}

からわからないことAuthenticationContext: トークンが既に要求されている場合、トークンは から取得されますTokenDbCache

4

1 に答える 1

2

Adal を介してトークンを取得すると、NaiveCache オブジェクトにキャッシュされます。

StartUp クラスでトークンを取得するコード:

  AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, "Your API Resource ID");
                            string kdAccessToken = kdAPiresult.AccessToken;

Azure Active Directory のサンプル ( https://github.com/AzureADSamples ) では、このオブジェクトはアプリ コントローラー内でトークンを取得するために使用されました。独自のキャッシングを実装して、同じ方法で取得できます。

コントローラーコードでは、次のことができます。

IOwinContext owinContext = HttpContext.GetOwinContext();
                string userObjectID = owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsObjectidentifier).Value;
                NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
                AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, cache);
                TokenCacheItem kdAPITokenCache = authContext.TokenCache.ReadItems().Where(c => c.Resource == "You API Resource ID").FirstOrDefault();

AuthenticationContext (3d パーティ API) を介さずにトークンを取得する場合は、トークンをクレームに保存することもできます。

于 2016-01-20T02:07:02.093 に答える