public static async Task <AuthenticationResult> AcquireTokenWithClientCredentialAsync() { AuthenticationResult result = null; ClientCredential cred = null; string ClientId = null; string ClientSecret = null; if (ctx.TokenCache.Count > 0) { ClientId = CustomTokenCache.ReadData("Clientid.dat"); ClientSecret = CustomTokenCache.ReadData("Sec.dat"); } else { string keyvaultUri = ConfigurationManager.AppSettings["ServicePrincipalContextUri"]; KeyVaultSecret spContext = await KeyVaultHelper.KeyVaultHelper.GetSecretFromMsiAsync(keyvaultUri); CustomTokenCache.WriteData("clientid.dat", spContext.ServicePrincipal.ClientId); CustomTokenCache.WriteData("Sec.dat", spContext.ServicePrincipal.ClientSecret); ClientId = spContext.ServicePrincipal.ClientId; ClientSecret = spContext.ServicePrincipal.ClientSecret; } cred = new ClientCredential(ClientId, ClientSecret); result = await ctx.AcquireTokenAsync(Resource, cred); return(result); }
protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null) { var tcs = new TaskCompletionSource <TokenCacheInfo>(); resource = resource ?? Constants.CSMResources[(int)AzureEnvironments]; TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { tcs.SetResult(found); return(tcs.Task); } var thread = new Thread(() => { try { var azureEnvironment = this.AzureEnvironments; var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); AuthenticationResult result = null; if (!string.IsNullOrEmpty(user)) { result = context.AcquireToken( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), promptBehavior: PromptBehavior.Never, userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); } else { result = context.AcquireToken( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), promptBehavior: PromptBehavior.Always); } var cacheInfo = new TokenCacheInfo(resource, result); tokenCache.Add(cacheInfo); tcs.TrySetResult(cacheInfo); } catch (Exception ex) { tcs.TrySetException(ex); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); return(tcs.Task); }
protected async Task <TokenCacheInfo> RefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo) { if (!String.IsNullOrEmpty(cacheInfo.RefreshToken)) { return(await GetAuthorizationResultByRefreshToken(tokenCache, cacheInfo)); } else if (!String.IsNullOrEmpty(cacheInfo.AppId) && !String.IsNullOrEmpty(cacheInfo.AppKey)) { return(GetAuthorizationResultBySpn(tokenCache, cacheInfo.TenantId, cacheInfo.AppId, cacheInfo.AppKey, cacheInfo.Resource)); } throw new NotImplementedException(); }
public async Task AcquireTokens() { this.TokenStorage.ClearCache(); this.TenantStorage.ClearCache(); var tokenCache = new CustomTokenCache(); var cacheInfo = await GetAuthorizationResult(tokenCache, Utils.GetLoginTenant()); Utils.Trace.WriteLine(string.Format("Welcome {0} (Tenant: {1})", cacheInfo.DisplayableId, cacheInfo.TenantId)); var tenantCache = await GetTokenForTenants(tokenCache, cacheInfo); this.TokenStorage.SaveCache(tokenCache); this.TenantStorage.SaveCache(tenantCache); }
public async Task <TokenCacheInfo> GetTokenBySpn(string tenantId, string appId, string appKey, string resource) { this.TokenStorage.ClearCache(); this.TenantStorage.ClearCache(); var tokenCache = new CustomTokenCache(); var cacheInfo = GetAuthorizationResultBySpn(tokenCache, tenantId, appId, appKey, resource ?? ARMConfiguration.ARMResource); var tenantCache = await GetTokenForTenants(tokenCache, cacheInfo, appId : appId, appKey : appKey); this.TokenStorage.SaveCache(tokenCache); this.TenantStorage.SaveCache(tenantCache); return(cacheInfo); }
public async Task <TokenCacheInfo> GetTokenByUpn(string username, string password) { this.TokenStorage.ClearCache(); this.TenantStorage.ClearCache(); var tokenCache = new CustomTokenCache(); var cacheInfo = GetAuthorizationResultByUpn(tokenCache, "common", username, password, Constants.CSMResources[(int)AzureEnvironments]); var tenantCache = await GetTokenForTenants(tokenCache, cacheInfo, username : username, password : password); this.TokenStorage.SaveCache(tokenCache); this.TenantStorage.SaveCache(tenantCache); return(cacheInfo); }
public async Task <TokenCacheInfo> GetTokenBySpn(string tenantId, string appId, X509Certificate2 certificate) { this.TokenStorage.ClearCache(); this.TenantStorage.ClearCache(); var tokenCache = new CustomTokenCache(); var cacheInfo = await GetAuthorizationResultBySpn(tokenCache, tenantId, appId, certificate, Constants.CSMResources[(int)AzureEnvironments]); var tenantCache = await GetTokenForTenants(tokenCache, cacheInfo, appId : appId, appKey : "_certificate_"); this.TokenStorage.SaveCache(tokenCache); this.TenantStorage.SaveCache(tenantCache); return(cacheInfo); }
protected async Task <TokenCacheInfo> RefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo) { if (!String.IsNullOrEmpty(cacheInfo.RefreshToken)) { return(await GetAuthorizationResultByRefreshToken(tokenCache, cacheInfo)); } else if (!String.IsNullOrEmpty(cacheInfo.AppId) && cacheInfo.AppKey == "_certificate_") { throw new InvalidOperationException("Unable to refresh expired token! Try login with certificate again."); } else if (!String.IsNullOrEmpty(cacheInfo.AppId) && !String.IsNullOrEmpty(cacheInfo.AppKey)) { return(GetAuthorizationResultBySpn(tokenCache, cacheInfo.TenantId, cacheInfo.AppId, cacheInfo.AppKey, cacheInfo.Resource)); } throw new NotImplementedException(); }
protected async Task <TokenCacheInfo> GetAuthorizationResultBySpn(CustomTokenCache tokenCache, string tenantId, string appId, X509Certificate2 certificate, string resource) { TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { return(found); } var helper = new JwtHelper(); var tokenEndpoint = string.Format("{0}/{1}/oauth2/token", Constants.AADLoginUrls[(int)this.AzureEnvironments], tenantId); var token = await helper.AcquireTokenByX509(tenantId, appId, certificate, resource, tokenEndpoint); var cacheInfo = new TokenCacheInfo(tenantId, appId, "_certificate_", resource, token); tokenCache.Add(cacheInfo); return(cacheInfo); }
public async Task <TokenCacheInfo> GetTokenBySpn(string tenantId, string appId, X509Certificate2 certificate, string resource) { this.TokenStorage.ClearCache(); this.TenantStorage.ClearCache(); var tokenCache = new CustomTokenCache(); var cacheInfo = await GetAuthorizationResultBySpn(tokenCache, tenantId, appId, certificate, resource ?? ARMConfiguration.ARMResource); if (cacheInfo.Resource != ARMConfiguration.ARMResource) { cacheInfo = await GetAuthorizationResultBySpn(tokenCache, tenantId, appId, certificate, ARMConfiguration.ARMResource); } var tenantCache = await GetTokenForTenants(tokenCache, cacheInfo, appId : appId, appKey : "_certificate_"); this.TokenStorage.SaveCache(tokenCache); this.TenantStorage.SaveCache(tenantCache); return(cacheInfo); }
protected async Task <TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo) { var azureEnvironment = this.AzureEnvironments; var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], cacheInfo.TenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); AuthenticationResult result = await context.AcquireTokenByRefreshTokenAsync( refreshToken : cacheInfo.RefreshToken, clientId : Constants.AADClientId, resource : cacheInfo.Resource); var ret = new TokenCacheInfo(cacheInfo.Resource, result); ret.TenantId = cacheInfo.TenantId; ret.DisplayableId = cacheInfo.DisplayableId; tokenCache.Add(ret); return(ret); }
protected async Task <TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo) { var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, cacheInfo.TenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); AuthenticationResult result = await context.AcquireTokenByRefreshTokenAsync( refreshToken : cacheInfo.RefreshToken, clientId : !string.IsNullOrEmpty(cacheInfo.ClientId)?cacheInfo.ClientId : Constants.AADClientId, resource : cacheInfo.Resource); var ret = new TokenCacheInfo(cacheInfo.Resource, result); ret.TenantId = cacheInfo.TenantId; ret.DisplayableId = cacheInfo.DisplayableId; ret.ClientId = cacheInfo.ClientId; tokenCache.Add(ret); return(ret); }
public static async Task <AuthenticationResult> AcquireTokenWithSSOAsync(string clientId = null, string resourceId = null) { AuthenticationResult result = null; //Get the local upn from connected user //cache upn string upn = CustomTokenCache.ReadData("upn.dat"); if (string.IsNullOrEmpty(upn)) { upn = UserPrincipal.Current.UserPrincipalName; CustomTokenCache.WriteData("upn.dat", upn); } if (string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(resourceId)) { try { result = await ctx.AcquireTokenSilentAsync(Resource, ClientId).ConfigureAwait(false); } catch (AdalException) { result = await ctx.AcquireTokenAsync(Resource, ClientId, new UserCredential(upn)).ConfigureAwait(false); } } else { try { result = await ctx.AcquireTokenSilentAsync(resourceId, clientId).ConfigureAwait(false); } catch (AdalException) { result = await ctx.AcquireTokenAsync(resourceId, clientId, new UserCredential(upn)).ConfigureAwait(false); } } return(result); }
protected TokenCacheInfo GetAuthorizationResultByUpn(CustomTokenCache tokenCache, string tenantId, string username, string password, string resource) { TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { return(found); } var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, tenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); var credential = new UserCredential(username, password); var result = context.AcquireToken(resource, Constants.AADClientId, credential); var cacheInfo = new TokenCacheInfo(resource, result); tokenCache.Add(cacheInfo); return(cacheInfo); }
protected TokenCacheInfo GetAuthorizationResultBySpn(CustomTokenCache tokenCache, string tenantId, string appId, string appKey, string resource) { TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { return(found); } var azureEnvironment = this.AzureEnvironments; var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); var credential = new ClientCredential(appId, appKey); var result = context.AcquireToken(resource, credential); var cacheInfo = new TokenCacheInfo(tenantId, appId, appKey, resource, result); tokenCache.Add(cacheInfo); return(cacheInfo); }
protected async Task <Dictionary <string, TenantCacheInfo> > GetTokenForTenants(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo, string appId = null, string appKey = null, string username = null, string password = null) { var recentInfo = cacheInfo; var tenantIds = await GetTenantIds(cacheInfo); if (!tenantIds.Contains(cacheInfo.TenantId)) { var list = tenantIds.ToList(); list.Insert(0, cacheInfo.TenantId); tenantIds = list.ToArray(); } var tenantCache = this.TenantStorage.GetCache(); foreach (var tenantId in tenantIds) { var info = new TenantCacheInfo { tenantId = tenantId, displayName = "unknown", domain = tenantId }; TokenCacheInfo result = null; try { if (!String.IsNullOrEmpty(appId) && !String.IsNullOrEmpty(appKey)) { result = GetAuthorizationResultBySpn(tokenCache, tenantId: tenantId, appId: appId, appKey: appKey, resource: Constants.CSMResources[(int)AzureEnvironments]); } else if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { result = GetAuthorizationResultByUpn(tokenCache, tenantId: tenantId, username: username, password: password, resource: Constants.CSMResources[(int)AzureEnvironments]); } else { result = await GetAuthorizationResult(tokenCache, tenantId : tenantId, user : cacheInfo.DisplayableId); } } catch (Exception ex) { Utils.Trace.WriteLine(string.Format("User: {0}, Tenant: {1} {2}", cacheInfo.DisplayableId, tenantId, ex.Message)); Utils.Trace.WriteLine(string.Empty); continue; } try { TokenCacheInfo aadToken = null; if (!String.IsNullOrEmpty(appId) && appKey == "_certificate_") { Utils.Trace.WriteLine(string.Format("AppId: {0}, Tenant: {1}", appId, tenantId)); } else if (!String.IsNullOrEmpty(appId) && !String.IsNullOrEmpty(appKey)) { aadToken = GetAuthorizationResultBySpn(tokenCache, tenantId: tenantId, appId: appId, appKey: appKey, resource: Constants.AADGraphUrls[(int)AzureEnvironments]); } else if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { aadToken = GetAuthorizationResultByUpn(tokenCache, tenantId: tenantId, username: username, password: password, resource: Constants.AADGraphUrls[(int)AzureEnvironments]); } else { aadToken = await GetAuthorizationResult(tokenCache, tenantId : tenantId, user : cacheInfo.DisplayableId, resource : Constants.AADGraphUrls[(int)AzureEnvironments]); } if (aadToken != null) { var details = await GetTenantDetail(aadToken, tenantId); info.displayName = details.displayName; info.domain = details.verifiedDomains.First(d => d.@default).name; if (!String.IsNullOrEmpty(appId) && !String.IsNullOrEmpty(appKey)) { Utils.Trace.WriteLine(string.Format("AppId: {0}, Tenant: {1} ({2})", appId, tenantId, info.domain)); } else { Utils.Trace.WriteLine(string.Format("User: {0}, Tenant: {1} ({2})", result.DisplayableId, tenantId, info.domain)); } } } catch (Exception) { if (!String.IsNullOrEmpty(appId) && !String.IsNullOrEmpty(appKey)) { Utils.Trace.WriteLine(string.Format("AppId: {0}, Tenant: {1}", appId, tenantId)); } else { Utils.Trace.WriteLine(string.Format("User: {0}, Tenant: {1}", result.DisplayableId, tenantId)); } } try { var subscriptions = await GetSubscriptions(result); Utils.Trace.WriteLine(string.Format("\tThere are {0} subscriptions", subscriptions.Length)); info.subscriptions = subscriptions.Select(subscription => new SubscriptionCacheInfo { subscriptionId = subscription.subscriptionId, displayName = subscription.displayName }).ToArray(); if (recentInfo != null && info.subscriptions.Length > 0) { recentInfo = result; } foreach (var subscription in subscriptions) { Utils.Trace.WriteLine(string.Format("\tSubscription {0} ({1})", subscription.subscriptionId, subscription.displayName)); } } catch (Exception ex) { Utils.Trace.WriteLine(string.Format("\t{0}!", ex.Message)); } tenantCache[tenantId] = info; if (!String.IsNullOrEmpty(info.domain) && info.domain != "unknown") { tenantCache[info.domain] = info; } Utils.Trace.WriteLine(string.Empty); } this.TokenStorage.SaveRecentToken(recentInfo, Constants.CSMResources[(int)AzureEnvironments]); return(tenantCache); }
public void SaveCache(CustomTokenCache cache) { this._cache = cache; }
public async Task AzLogin() { this.TokenStorage.ClearCache(); this.TenantStorage.ClearCache(); var tokens = GetAzLoginTokens(); var tokenCache = new CustomTokenCache(); var tenantCache = this.TenantStorage.GetCache(); TokenCacheInfo recentInfo = null; foreach (var token in tokens) { var result = token.ToTokenCacheInfo(); Guid unused; if (!Guid.TryParse(result.TenantId, out unused)) { continue; } tokenCache.Add(result); var tenantId = result.TenantId; var info = new TenantCacheInfo { tenantId = tenantId, displayName = "unknown", domain = tenantId }; Utils.Trace.WriteLine(string.Format("User: {0}, Tenant: {1}", result.DisplayableId, tenantId)); try { var subscriptions = await GetSubscriptions(result); Utils.Trace.WriteLine(string.Format("\tThere are {0} subscriptions", subscriptions.Length)); info.subscriptions = subscriptions.Select(subscription => new SubscriptionCacheInfo { subscriptionId = subscription.subscriptionId, displayName = subscription.displayName }).ToArray(); if (recentInfo == null || info.subscriptions.Length > 0) { recentInfo = result; } foreach (var subscription in subscriptions) { Utils.Trace.WriteLine(string.Format("\tSubscription {0} ({1})", subscription.subscriptionId, subscription.displayName)); } } catch (Exception ex) { Utils.Trace.WriteLine(string.Format("\t{0}!", ex.Message)); } tenantCache[tenantId] = info; if (!String.IsNullOrEmpty(info.domain) && info.domain != "unknown") { tenantCache[info.domain] = info; } Utils.Trace.WriteLine(string.Empty); } if (recentInfo != null) { this.TokenStorage.SaveRecentToken(recentInfo, Constants.CSMResources[(int)AzureEnvironments]); } this.TokenStorage.SaveCache(tokenCache); this.TenantStorage.SaveCache(tenantCache); }
public void SaveCache(CustomTokenCache cache) { var state = cache.GetState(); ProtectedFile.WriteAllText(ProtectedFile.GetCacheFile(_cacheFileName), state); }
protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null) { var tcs = new TaskCompletionSource <TokenCacheInfo>(); resource = resource ?? Constants.CSMResources[(int)AzureEnvironments]; TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { tcs.SetResult(found); return(tcs.Task); } var thread = new Thread(async() => { try { var azureEnvironment = this.AzureEnvironments; var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); AuthenticationResult result = null; if (!string.IsNullOrEmpty(user)) { try { #if NET471 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(PromptBehavior.Never), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif #if NETCOREAPP2_0 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif } catch (AdalException adalEx) { if (adalEx.Message.IndexOf("user_interaction_required") < 0) { throw; } #if NET471 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(PromptBehavior.Auto), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif #if NETCOREAPP2_0 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif } } else { #if NET471 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(PromptBehavior.Always)); #endif #if NETCOREAPP2_0 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters()); #endif } var cacheInfo = new TokenCacheInfo(resource, result); tokenCache.Add(cacheInfo); tcs.TrySetResult(cacheInfo); } catch (Exception ex) { tcs.TrySetException(ex); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); return(tcs.Task); }
protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null) { var tcs = new TaskCompletionSource <TokenCacheInfo>(); resource = resource ?? ARMConfiguration.ARMResource; TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { tcs.SetResult(found); return(tcs.Task); } var thread = new Thread(() => { try { var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, tenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); AuthenticationResult result = null; if (!string.IsNullOrEmpty(user)) { try { result = context.AcquireToken( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), promptBehavior: PromptBehavior.Never, userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); } catch (AdalException adalEx) { if (!string.Equals(adalEx.ErrorCode, "interaction_required", StringComparison.OrdinalIgnoreCase) && adalEx.Message.IndexOf("user_interaction_required") < 0) { throw; } result = context.AcquireToken( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), promptBehavior: PromptBehavior.Auto, userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); } } else { result = context.AcquireToken( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), promptBehavior: PromptBehavior.Always); } var cacheInfo = new TokenCacheInfo(resource, result); tokenCache.Add(cacheInfo); tcs.TrySetResult(cacheInfo); } catch (Exception ex) { tcs.TrySetException(ex); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); return(tcs.Task); }