Azure Active Directory(AAD)を使用して単純なMVCアプリケーションをセットアップしました。
アプリケーションからアプリケーションのロールとグループを管理するには、AAD GraphAPIにクエリを実行する必要があります。
では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
。
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(サードパーティAPI)を介さずにトークンを取得している場合は、クレームにトークンを保存することもできます
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加