Azure的活动目录 - 存储访问令牌MVC应用程序的最佳实践 [英] Azure Active Directory - MVC application best practices to store the access token
问题描述
我使用Azure中的Active Directory(AAD)设置一个简单的MVC应用程序。
I've set up a simple MVC Application using Azure Active Directory(AAD).
我需要查询AAD图形API,以便从我的应用程序管理应用程序的角色和组。
I need to query the AAD Graph API in order to manage application roles and groups from my application.
在启动
类,我收到的accessToken这样的:
In the Startup
class, I received the AccessToken like that:
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:
To instantiate the ActiveDirectoryClient
class, I need to pass the AccessToken :
var servicePointUri = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(servicePointUri, tenantID);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await GetTokenForApplication());
我想知道如果存储的accessToken作为索赔是一个很好的解决方案(线在启动
添加类)?
context.AuthenticationTicket.Identity.AddClaim(new
Claim("OpenId_AccessToken", result.AccessToken));
修改令牌已经存储..
得到它!谢谢乔治。
所以,我的令牌已使用 TokenDbCache
类存储在数据库中。
Get it !!! Thank you George.
So my Token has been stored in the database using the TokenDbCache
class.
要根据样品再得到它(在我的控制器之一):
To get it again (in one of my controller) according to the sample:
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
。
推荐答案
当您检索通过阿达尔是其高速缓存NaiveCache对象令牌。
When you are retrieving tokens through Adal it is caching it in NaiveCache object.
code检索令牌withing启动类:
Code to retrieve token withing StartUp class:
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 )用于获取令牌这个对象在应用程序控制器。佑康实现自己的高速缓存以同样的方式进行检索。
In Azure Active Directory samples (https://github.com/AzureADSamples) this object utilized to retrieve token within app controllers. Youcan implement your own caching to retrieve it in a same manner.
在你的控制器code,你可以做以下内容:
In your controller code you can do following:
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)
You can store token in claims as well if your are obtaining tokens not though AuthenticationContext (3d party apis)
这篇关于Azure的活动目录 - 存储访问令牌MVC应用程序的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!