public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, TokenCache tokenCache, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { var configuration = GetAdalConfiguration(environment, tenant, resourceId, tokenCache); TracingAdapter.Information(Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); IAccessToken token; if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) { var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint); token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type); } else { token = TokenProvider.GetAccessToken(configuration, promptBehavior, account.Id, password, account.Type); } account.Id = token.UserId; return token; }
protected void Page_Load(object sender, EventArgs e) { //Redirect uri must match the redirect_uri used when requesting Authorization code. string redirectUri = Properties.Settings.Default.RedirectUrl; string authorityUri = "https://login.windows.net/common/oauth2/authorize/"; // Get the auth code string code = Request.Params.GetValues(0)[0]; // Get auth token from auth code TokenCache TC = new TokenCache(); AuthenticationContext AC = new AuthenticationContext(authorityUri, TC); ClientCredential cc = new ClientCredential (Properties.Settings.Default.ClientID, Properties.Settings.Default.ClientSecretKey); AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc); //Set Session "authResult" index string to the AuthenticationResult Session["authResult"] = AR; //Redirect back to Default.aspx Response.Redirect("/Default.aspx"); }
private static ServiceClientCredentials GetCreds_User_Popup( string tenant, System.Uri tokenAudience, string clientId, MSAD.TokenCache tokenCache, MSAD.PromptBehavior promptBehavior = MSAD.PromptBehavior.Auto) { System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Threading.SynchronizationContext()); var clientSettings = new REST.Authentication.ActiveDirectoryClientSettings { ClientId = clientId, ClientRedirectUri = new System.Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = promptBehavior }; var serviceSettings = REST.Authentication.ActiveDirectoryServiceSettings.Azure; serviceSettings.TokenAudience = tokenAudience; var creds = REST.Authentication.UserTokenProvider.LoginWithPromptAsync( tenant, clientSettings, serviceSettings, tokenCache).GetAwaiter().GetResult(); return(creds); }
protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, TokenSubjectType subjectType, bool callSync) { this.Authenticator = authenticator; this.CallState = CreateCallState(this.Authenticator.CorrelationId, callSync); Logger.Information(this.CallState, string.Format("=== Token Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t", authenticator.Authority, resource, clientKey.ClientId, (tokenCache != null) ? tokenCache.GetType().FullName + string.Format(" ({0} items)", tokenCache.Count) : "null", subjectType)); this.tokenCache = tokenCache; if (string.IsNullOrWhiteSpace(resource)) { var ex = new ArgumentNullException("resource"); Logger.Error(this.CallState, ex); throw ex; } this.Resource = (resource != NullResource) ? resource : null; this.ClientKey = clientKey; this.TokenSubjectType = subjectType; this.LoadFromCache = (tokenCache != null); this.StoreToCache = (tokenCache != null); this.SupportADFS = false; }
async Task IAuthenticationProvider.AuthenticateRequestAsync(HttpRequestMessage request) { // look in the IBotDataBag for the token string objectIdentifier; string tenantID = null; byte[] tokenBlob = null; bool found = bag.TryGetValue(Keys.ObjectID, out objectIdentifier) && bag.TryGetValue(Keys.TenantID, out tenantID) && bag.TryGetValue(Keys.TokenCache, out tokenBlob); // if not found, then throw the exception that will restart the login flow if (! found) { throw new AdalSilentTokenAcquisitionException(); } // deserialize the TokenCache and try to refresh the token silently var tokenCache = new TokenCache(tokenBlob); var token = await AcquireTokenSilentAsync(this.keys.ClientID, this.keys.ClientSecret, objectIdentifier, tenantID, tokenCache); // update the IBotDataBag with the new token if it's changed tokenBlob = tokenCache.Serialize(); bag.SetValue(Keys.TokenCache, tokenBlob); // add the access token to the authentication header for the Microsoft Graph request var accessToken = token.AccessToken; request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken); }
protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string[] scope, ClientKey clientKey, TokenSubjectType subjectType) { this.Authenticator = authenticator; this.CallState = CreateCallState(this.Authenticator.CorrelationId); PlatformPlugin.Logger.Information(this.CallState, string.Format( "=== accessToken Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t", authenticator.Authority, scope, clientKey.ClientId, (tokenCache != null) ? tokenCache.GetType().FullName + string.Format(" ({0} items)", tokenCache.Count) : "null", subjectType)); this.tokenCache = tokenCache; this.ClientKey = clientKey; this.TokenSubjectType = subjectType; this.LoadFromCache = (tokenCache != null); this.StoreToCache = (tokenCache != null); this.SupportADFS = false; if (ADALScopeHelper.IsNullOrEmpty(scope)) { throw new ArgumentNullException("scope"); } this.Scope = scope; ValidateScopeInput(scope); }
private async Task AdalLogin(bool forcePrompt) { var spUri = new Uri($"{txtSiteFor2FA.Text}"); string resourceUri = spUri.Scheme + "://" + spUri.Authority; const string clientId = "9bc3ab49-b65d-410a-85ad-de819febfddc"; const string redirectUri = "https://oauth.spops.microsoft.com/"; ADAL.AuthenticationResult authenticationResult; if (authContext == null || forcePrompt) { ADAL.TokenCache cache = new ADAL.TokenCache(); authContext = new ADAL.AuthenticationContext(AuthorityUri, cache); } try { if (forcePrompt) { throw new ADAL.AdalSilentTokenAcquisitionException(); } authenticationResult = await authContext.AcquireTokenSilentAsync(resourceUri, clientId); } catch (ADAL.AdalSilentTokenAcquisitionException) { authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always, null), ADAL.UserIdentifier.AnyUser, null, null); } options.AccessToken = authenticationResult.AccessToken; accessTokenObtained = true; }
public async Task<bool> EnsureAuthenticationContext(string authority, bool show) { if (this.AuthenticationContext == null) { var cache = _cachePersist.Read(); if (cache != null) { var t = new TokenCache(cache); this.AuthenticationContext = new AuthenticationContext(authority, t); } else { this.AuthenticationContext = new AuthenticationContext(authority); } } var p = new PlatformParameters(show ? PromptBehavior.Always : PromptBehavior.Never, _deviceService.WindowHandle); this.AuthenticationResult = await this.AuthenticationContext.AcquireTokenAsync( Office365ServicesUris.AADGraphAPIResourceId, ClientId, new Uri(RedirectUri), p); var tokenCache = AuthenticationContext.TokenCache.Serialize(); _cachePersist.Write(tokenCache); return !string.IsNullOrWhiteSpace(this.AuthenticationResult.AccessToken); }
public async Task AcquireTokenSilentServiceErrorTestAsync() { Sts sts = new AadSts(); TokenCache cache = new TokenCache(); TokenCacheKey key = new TokenCacheKey(sts.Authority, sts.ValidResource, sts.ValidClientId, TokenSubjectType.User, "unique_id", "*****@*****.**"); cache.tokenCacheDictionary[key] = new AuthenticationResult("Bearer", "some-access-token", "invalid-refresh-token", DateTimeOffset.UtcNow); AuthenticationContext context = new AuthenticationContext(sts.Authority, sts.ValidateAuthority, cache); try { await context.AcquireTokenSilentAsync(sts.ValidResource, sts.ValidClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId)); Verify.Fail("AdalSilentTokenAcquisitionException was expected"); } catch (AdalSilentTokenAcquisitionException ex) { Verify.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode); Verify.AreEqual(AdalErrorMessage.FailedToRefreshToken, ex.Message); Verify.IsNotNull(ex.InnerException); Verify.IsTrue(ex.InnerException is AdalException); Verify.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant"); } catch { Verify.Fail("AdalSilentTokenAcquisitionException was expected"); } }
static TokenCache() { DefaultShared = new TokenCache { BeforeAccess = PlatformPlugin.TokenCachePlugin.BeforeAccess, AfterAccess = PlatformPlugin.TokenCachePlugin.AfterAccess }; }
public static void UpdateTokenExpiryOnTokenCache(TokenCache cache, DateTimeOffset newExpiry) { var cacheDictionary = cache.tokenCacheDictionary; var key = cacheDictionary.Keys.First(); cache.tokenCacheDictionary[key].ExpiresOn = newExpiry; var value = cacheDictionary.Values.First(); cache.Clear(); cacheDictionary.Add(key, value); }
public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string[] scope, string clientId, UserCredential userCredential) : base(authenticator, tokenCache, scope, new ClientKey(clientId), TokenSubjectType.User) { if (userCredential == null) { throw new ArgumentNullException("userCredential"); } this.userCredential = userCredential; }
public void AuthenticateAndAddToPowerBI() { var tokenCache = new TokenCache(); var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache); var result = authenticationContext.AcquireToken(ResourceUri, SelectedTenant.Client, new Uri(RedirectUri), PromptBehavior.RefreshSession); var workspace = Workspace.GetFor(result.AccessToken); var dataset = workspace.Datasets.GetByName(SelectedTenant.Dataset); workspace.Rows.Add(dataset, new Message { ResponseInMinutes = Random.Next(0, 45) }); }
public AuthenticationContextProxy(string authority, bool validateAuthority, TokenCacheType tokenCacheType) { TokenCache tokenCache = null; if (tokenCacheType == TokenCacheType.InMemory) { tokenCache = new TokenCache(); } this.context = new AuthenticationContext(authority, validateAuthority, tokenCache); this.context.CorrelationId = new Guid(FixedCorrelationId); }
static TokenCache() { DefaultShared = new TokenCache(); #if !ADAL_NET DefaultShared.BeforeAccess = DefaultTokenCache_BeforeAccess; DefaultShared.AfterAccess = DefaultTokenCache_AfterAccess; DefaultTokenCache_BeforeAccess(null); #endif }
public void ClearCache() { string cache_filename = GetTokenCachePath(); if (System.IO.File.Exists(cache_filename)) { var bytes = System.IO.File.ReadAllBytes(cache_filename); var token_cache = new MSAD.TokenCache(bytes); token_cache.Clear(); System.IO.File.WriteAllBytes(cache_filename, token_cache.Serialize()); } }
public void ClearCache() { string cache_filename = GetTokenCachePath(); if (System.IO.File.Exists(cache_filename)) { var bytes = System.IO.File.ReadAllBytes(cache_filename); var token_cache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache(bytes); token_cache.Clear(); System.IO.File.WriteAllBytes(cache_filename, token_cache.Serialize()); } }
public void Authenticate() { string domain = this.Tenant; // if you want it to automatically use a tenant use "common" - but this can pick the an unintended tenant so it is best to be explicit string client_id = "1950a258-227b-4e31-a9cf-717495945fc2"; // Re-use the Azure PowerShell client id, in production code you should create your own client id var client_redirect = new System.Uri("urn:ietf:wg:oauth:2.0:oob"); var AD_client_settings = REST.Authentication.ActiveDirectoryClientSettings.UseCacheCookiesOrPrompt(client_id, client_redirect); // Load the token cache, if one exists. string cache_filename = GetTokenCachePath(); Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache token_cache; if (System.IO.File.Exists(cache_filename)) { var bytes = System.IO.File.ReadAllBytes(cache_filename); token_cache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache(bytes); } else { token_cache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache(); } // Now figure out the token business Microsoft.Rest.ServiceClientCredentials creds = null; // Get the cached token, if it exists and is not expired. //if (token_cache.Count > 0) //{ // var token_cache_item = token_cache.ReadItems().First(); // creds = REST.Authentication.UserTokenProvider.CreateCredentialsFromCache(client_id, token_cache_item.TenantId, token_cache_item.DisplayableId, token_cache).Result; // SaveTokenCache(token_cache, cache_filename); //} //if (creds == null) { // Did not find the token in the cache, show popup and save the token var sync_context = new System.Threading.SynchronizationContext(); System.Threading.SynchronizationContext.SetSynchronizationContext(sync_context); creds = REST.Authentication.UserTokenProvider.LoginWithPromptAsync(domain, AD_client_settings, token_cache).Result; if (token_cache.Count > 0) { // If token cache has no items then trying serialize it will fail when deserializing System.IO.File.WriteAllBytes(cache_filename, token_cache.Serialize()); } } this.Credentials = creds; this.Token = token_cache.ReadItems().First(); }
public void EnsureAuthenticationContext(TokenCache tokenCache) { if (ClaimsPrincipal.Current != null) { var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; this.AuthenticationContext = new AuthenticationContext( String.Format("{0}/{1}", AuthenticationHelper.AuthorizationUri, tenantId), tokenCache); } }
public Tokens RefreshToken(Client client, Token refreshToken) { var tokenCache = new TokenCache(); var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache); var result = authenticationContext.AcquireTokenByRefreshToken(refreshToken, client, ResourceUri); var tokens = new Tokens { AccessToken = result.AccessToken, RefreshToken = result.RefreshToken, ExpiresOn = result.ExpiresOn }; return tokens; }
public AcquireTokenOnBehalfHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserAssertion userAssertion) : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.UserPlusClient) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; this.SupportADFS = true; }
public AcquireTokenSilentHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserIdentifier userId, bool callSync) : base(authenticator, tokenCache, resource, clientKey, clientKey.HasCredential ? TokenSubjectType.UserPlusClient : TokenSubjectType.User, callSync) { if (userId == null) { throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser); } this.UniqueId = userId.UniqueId; this.DisplayableId = userId.DisplayableId; this.UserIdentifierType = userId.Type; this.SupportADFS = true; }
public AcquireTokenOnBehalfHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserAssertion userAssertion, bool callSync) : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.UserPlusClient, callSync) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; this.assertionHash = PlatformSpecificHelper.CreateSha256Hash(userAssertion.Assertion); this.SupportADFS = true; }
static AzureSession() { ClientFactory = new ClientFactory(); AuthenticationFactory = new AuthenticationFactory(); DataStore = new MemoryDataStore(); TokenCache = new TokenCache(); OldProfileFile = "WindowsAzureProfile.xml"; OldProfileFileBackup = "WindowsAzureProfile.xml.bak"; ProfileDirectory = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Resources.AzureDirectoryName); ; ProfileFile = "AzureProfile.json"; TokenCacheFile = "TokenCache.dat"; }
#pragma warning disable 1591 // Xml Comments public Tokens GetTokens(Client client) { var tokenCache = new TokenCache(); var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache); var result = authenticationContext.AcquireToken(ResourceUri, client, new Uri(RedirectUri), PromptBehavior.RefreshSession); var tokens = new Tokens { AccessToken = result.AccessToken, RefreshToken = result.RefreshToken, ExpiresOn = result.ExpiresOn }; return tokens; }
public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, UserAssertion userAssertion) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } if (string.IsNullOrWhiteSpace(userAssertion.AssertionType)) { throw new ArgumentException(AdalErrorMessage.UserCredentialAssertionTypeEmpty, "userAssertion"); } this.userAssertion = userAssertion; }
public Tokens GetTokens(Client client, ClientSecret clientSecret, Token token, string redirectUri) { var tokenCache = new TokenCache(); var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache); var clientCredential = new ClientCredential(client, clientSecret); var result = authenticationContext.AcquireTokenByAuthorizationCode(token, new Uri(redirectUri), clientCredential); var tokens = new Tokens { AccessToken = result.AccessToken, RefreshToken = result.RefreshToken, ExpiresOn = result.ExpiresOn }; return tokens; }
public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, UserCredential userCredential) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User) { if (userCredential == null) { throw new ArgumentNullException("userCredential"); } // We enable ADFS support only when it makes sense to do so if (authenticator.AuthorityType == AuthorityType.ADFS) { this.SupportADFS = true; } this.userCredential = userCredential; }
public AuthenticationContextProxy(string authority, bool validateAuthority, TokenCacheType tokenCacheType) { TokenCache tokenCache = null; if (tokenCacheType == TokenCacheType.InMemory) { tokenCache = new TokenCache(); } try { this.context = CreateAsync(authority, validateAuthority, tokenCache, new Guid(FixedCorrelationId)).Result; } catch (AggregateException ae) { throw ae.InnerExceptions[0]; } }
// This constructor is called by ContinueAcquireTokenAsync after WAB call has returned. public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, IWebAuthenticationBrokerContinuationEventArgs args) : this( authenticator, tokenCache, (string)args.ContinuationData[WabArgName.Resource], (string)args.ContinuationData[WabArgName.ClientId], GetRedirectUri((string)args.ContinuationData[WabArgName.RedirectUri]), // Issue #129 - Windows Phone cannot handle ms-app URI's so use the placeholder URI for SSO PromptBehavior.Always, // This is simply to disable cache lookup. In fact, there is no authorize call at this point and promptBehavior is not applicable. new UserIdentifier((string)args.ContinuationData[WabArgName.UserId], (UserIdentifierType)((int)args.ContinuationData[WabArgName.UserIdType])), null, NetworkPlugin.WebUIFactory.Create(), false) { CallState callState = new CallState(new Guid((string)args.ContinuationData[WabArgName.CorrelationId]), false); this.authorizationResult = this.webUi.ProcessAuthorizationResult(args, callState); }
public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string[] scope, string[] additionalScope, string clientId, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters, IWebUI webUI) : base(authenticator, tokenCache, scope, new ClientKey(clientId), TokenSubjectType.User) { this.redirectUri = PlatformPlugin.PlatformInformation.ValidateRedirectUri(redirectUri, this.CallState); if (!string.IsNullOrWhiteSpace(this.redirectUri.Fragment)) { throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri"); } this.authorizationParameters = parameters; if (!ADALScopeHelper.IsNullOrEmpty(additionalScope)) { this.additionalScope = additionalScope; } else { this.additionalScope = new string[] {}; } ValidateScopeInput(scope.Union(this.additionalScope).ToArray()); this.redirectUriRequestParameter = PlatformPlugin.PlatformInformation.GetRedirectUriAsString(this.redirectUri, this.CallState); if (userId == null) { throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser); } this.userId = userId; if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&') { extraQueryParameters = extraQueryParameters.Substring(1); } this.extraQueryParameters = extraQueryParameters; this.webUi = webUI; this.UniqueId = userId.UniqueId; this.DisplayableId = userId.DisplayableId; this.UserIdentifierType = userId.Type; this.LoadFromCache = (tokenCache != null && parameters != null && PlatformPlugin.PlatformInformation.GetCacheLoadPolicy(parameters)); this.SupportADFS = false; }
public void EnsureAuthenticationContext(string authority) { if (this.AuthenticationContext == null) { var cache = _cachePersist.Read(); if (cache != null) { var t = new TokenCache(cache); this.AuthenticationContext = new AuthenticationContext(authority, t); } else { throw new Exception("Cache is empty, fire up main project and log in first. Check path in TestCachePersist"); } } }
public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters, IWebUI webUI, bool callSync) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User, callSync) { if (redirectUri == null) { throw new ArgumentNullException("redirectUri"); } if (!string.IsNullOrWhiteSpace(redirectUri.Fragment)) { throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri"); } this.redirectUri = redirectUri; this.SetRedirectUriRequestParameter(); if (userId == null) { throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser); } this.userId = userId; this.promptBehavior = promptBehavior; if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&') { extraQueryParameters = extraQueryParameters.Substring(1); } this.extraQueryParameters = extraQueryParameters; this.webUi = webUI; this.UniqueId = userId.UniqueId; this.DisplayableId = userId.DisplayableId; this.UserIdentifierType = userId.Type; this.LoadFromCache = (tokenCache != null && this.promptBehavior != PromptBehavior.Always && this.promptBehavior != PromptBehavior.RefreshSession); this.SupportADFS = true; }
public AcquireTokenByRefreshTokenHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, string refreshToken, bool callSync) : base(authenticator, tokenCache, resource ?? NullResource, clientKey, TokenSubjectType.UserPlusClient, callSync) { if (string.IsNullOrWhiteSpace(refreshToken)) { throw new ArgumentNullException("refreshToken"); } if (!string.IsNullOrWhiteSpace(resource) && this.Authenticator.AuthorityType != AuthorityType.AAD) { throw new ArgumentException(AdalErrorMessage.UnsupportedMultiRefreshToken, "resource"); } this.refreshToken = refreshToken; this.LoadFromCache = false; this.StoreToCache = false; this.SupportADFS = true; }
/// <summary> /// Use AuthenticationContext to get an access token /// </summary> /// <returns></returns> static string AccessToken() { if (token == String.Empty) { // Create an instance of TokenCache to cache the access token TokenCache TC = new TokenCache(); // Create an instance of AuthenticationContext to acquire an Azure access token authContext = new AuthenticationContext(authority, TC); // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken.ToString(); } else { // Get the token in the cache token = authContext.AcquireTokenSilent(resourceUri, clientID).AccessToken; } return token; }
private static MSAD.TokenCache GetTokenCache(string path) { var tokenCache = new MSAD.TokenCache(); tokenCache.BeforeAccess += notificationArgs => { if (System.IO.File.Exists(path)) { var bytes = System.IO.File.ReadAllBytes(path); notificationArgs.TokenCache.Deserialize(bytes); } }; tokenCache.AfterAccess += notificationArgs => { var bytes = notificationArgs.TokenCache.Serialize(); System.IO.File.WriteAllBytes(path, bytes); }; return(tokenCache); }
private ADAL.AuthenticationContext AuthContext = null; // new ADAL.AuthenticationContext(AuthorityUri); // use default static cache - not thread safe?; public AdalAuthentication() { Guid runspaceId = Guid.Empty; using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) { runspaceId = ps.Runspace.InstanceId; ADAL.TokenCache tc; bool found = Tokens.TryGetValue(runspaceId, out tc); if (!found) { tc = new ADAL.TokenCache(); Tokens.AddOrUpdate(runspaceId, tc, (k, v) => v); // Do I need to use a ConcurrentDictionary? } AuthContext = new ADAL.AuthenticationContext(AuthorityUri, tc); } }
private static void SaveTokenCache(MSAD.TokenCache token_cache, string filename) { var bytes = token_cache.Serialize(); System.IO.File.WriteAllBytes(filename, bytes); }