//see: https://azure.microsoft.com/en-us/resources/samples/data-lake-analytics-dotnet-auth-options/ private static ServiceClientCredentials GetCreds_User_Popup( string tenant, System.Uri tokenAudience, string clientId, PromptBehavior promptBehavior = PromptBehavior.Auto) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var clientSettings = new ActiveDirectoryClientSettings { ClientId = clientId, ClientRedirectUri = new System.Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = promptBehavior }; var serviceSettings = ActiveDirectoryServiceSettings.Azure; serviceSettings.TokenAudience = tokenAudience; var creds = UserTokenProvider.LoginWithPromptAsync( tenant, clientSettings, serviceSettings).GetAwaiter().GetResult(); return(creds); }
static async Task Main(string[] args) { var clientId = "1950a258-227b-4e31-a9cf-717495945fc2"; // "well-known" value: https://blogs.technet.microsoft.com/keithmayer/2014/12/30/leveraging-the-azure-service-management-rest-api-with-azure-active-directory-and-powershell-list-azure-administrators/ var config = LoadConfiguration(args); //var authorizationRule = "DefaultFullSharedAccessSignature"; var creds = await UserTokenProvider.LoginByDeviceCodeAsync(clientId, (deviceCodeResult) => { Console.WriteLine(deviceCodeResult.Message); return(true); }); // Create resource group var resourceClient = new ResourceManagementClient(creds); resourceClient.SubscriptionId = config.SubscriptionId; await resourceClient.ResourceGroups.CreateOrUpdateAsync(config.ResourceGroupName, new ResourceGroup(config.Location)); var nhManagemntClient = new NotificationHubsManagementClient(creds); nhManagemntClient.SubscriptionId = config.SubscriptionId; // Create namespace await nhManagemntClient.Namespaces.CreateOrUpdateAsync(config.ResourceGroupName, config.NamespaceName, new NamespaceCreateOrUpdateParameters(config.Location) { Sku = new Microsoft.Azure.Management.NotificationHubs.Models.Sku("standard") }); // Create hub Microsoft.Azure.Management.NotificationHubs.Models.GcmCredential gcmCreds = null; Microsoft.Azure.Management.NotificationHubs.Models.ApnsCredential apnsCreds = null; if (config.GcmCreds != null) { gcmCreds = new Microsoft.Azure.Management.NotificationHubs.Models.GcmCredential { GoogleApiKey = config.GcmCreds }; } if (config.ApnsCreds != null) { var apnsCredsSplit = config.ApnsCreds.Replace("\\n", "\n").Split(";"); apnsCreds = new Microsoft.Azure.Management.NotificationHubs.Models.ApnsCredential { KeyId = apnsCredsSplit[0], // Id AppName = apnsCredsSplit[1], // Prefix AppId = apnsCredsSplit[2], Token = apnsCredsSplit[3], Endpoint = "https://api.development.push.apple.com:443/3/device" }; } await nhManagemntClient.NotificationHubs.CreateOrUpdateAsync(config.ResourceGroupName, config.NamespaceName, config.HubName, new NotificationHubCreateOrUpdateParameters(config.Location) { GcmCredential = gcmCreds, ApnsCredential = apnsCreds }); Console.WriteLine($"Create NotificationHub {config.HubName}."); }
public void CredentialsConstructorThrowsForInvalidValues() { TokenCache cache = new TestTokenCache(); var settings = ActiveDirectoryServiceSettings.Azure; Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginSilentAsync(null, "microsoft.onmicrosoft.com", this._username, this._password, cache)); Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync( "microsoft.onmicrosoft.com", ActiveDirectoryClientSettings.UsePromptOnly(string.Empty, new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, cache)); Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(null, ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, cache)); Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(string.Empty, ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, cache)); Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", null, this._password, cache)); Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", string.Empty, this._password, cache).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", this._username, null, cache)); Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", this._username, string.Empty, cache)); }
private static async Task <ServiceClientCredentials> GetAzureCredentials() { var activeDirectoryClientSettings = ActiveDirectoryClientSettings.UsePromptOnly(ConfigurationManager.AppSettings["ClientId"], new Uri("urn:ietf:wg:oauth:2.0:oob")); ServiceClientCredentials credentials = await UserTokenProvider.LoginWithPromptAsync(ConfigurationManager.AppSettings["ActiveDirectoryTenantId"], activeDirectoryClientSettings); return(credentials); }
public ResponseResult <TokenDecodeResponseDTO> Decode(TokenDecodeRequestDTO request) { TokenDecodeResponseDTO response = new TokenDecodeResponseDTO(); var app = OAuthAppCache.Get(request.Appid); if (app == null) { return(Fail <TokenDecodeResponseDTO>("无效的应用id", "0400")); } var ut = UserTokenProvider.DecryptAccessToken(request.Token); if (ut == null || !ut.Success) { return(Fail <TokenDecodeResponseDTO>("无效的token", "0400")); } if (ut.Content.AppId != app.Id) { return(Fail <TokenDecodeResponseDTO>("操作不允许", "0402")); } response = new TokenDecodeResponseDTO { Appid = ut.Content.AppId, ExpireTime = ut.Content.Expire_Time, Usercode = ut.Content.UserCode, Userid = ut.Content.UserId }; return(Success(response)); }
private void ConnectMenuItem_Click(object sender, RoutedEventArgs e) { try { // User login via interactive popup // Authenticate using an an Azure AD domain and client ID that is available by default for all Azure subscriptions SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); tenant = this.txtTenantID.Text; var nativeClientApp_clientId = "1950a258-227b-4e31-a9cf-717495945fc2"; var activeDirectoryClientSettings = ActiveDirectoryClientSettings.UsePromptOnly(nativeClientApp_clientId, new Uri("urn:ietf:wg:oauth:2.0:oob")); var creds = UserTokenProvider.LoginWithPromptAsync(tenant, activeDirectoryClientSettings).Result; this.uploadMenuItem.IsEnabled = true; this.downloadMenuItem.IsEnabled = true; this.listFilesMenuItem.IsEnabled = true; this.getFileInfoMenuItem.IsEnabled = true; // Create client objects and set the subscription ID adlsClient = new DataLakeStoreAccountManagementClient(creds); adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds); } catch (Exception ex) { MessageBox.Show($"Exception {ex.Message}", "Connect Failure", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Acquire Graph token /// </summary> /// <param name="graphAADServiceSettings"></param> /// <param name="spnClientId"></param> /// <param name="spnSecret"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="psClientId"></param> private void UpdateTokenInfoWithGraphToken(ActiveDirectoryServiceSettings graphAADServiceSettings, string spnClientId = "", string spnSecret = "", string userName = "", string password = "", string psClientId = "") { Task <TokenCredentials> graphAuthResult = null; try { if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { //#if FullNetFx #if net452 graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginSilentAsync(psClientId, this.Tenant, userName, password, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); #endif } else if (!string.IsNullOrWhiteSpace(spnClientId) && !string.IsNullOrWhiteSpace(spnSecret)) { graphAuthResult = Task.Run(async() => (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(this.Tenant, spnClientId, spnSecret, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); } this.TokenInfo[TokenAudience.Graph] = graphAuthResult?.Result; } catch (Exception ex) { Debug.WriteLine(string.Format("Error while acquiring Graph Token: '{0}'", ex.ToString())); // Not all accounts are registered to have access to Graph endpoints. } }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (servicePrincipalLoginInformation != null) { if (servicePrincipalLoginInformation.ClientSecret != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } #if NET45 else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #endif else { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, adSettings, TokenCache.DefaultShared); } } #if !PORTABLE else if (userLoginInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( userLoginInformation.ClientId, TenantId, userLoginInformation.UserName, userLoginInformation.Password, adSettings, TokenCache.DefaultShared); } #endif #if PORTABLE else if (deviceCredentialInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, deviceCredentialInformation.DeviceCodeFlowHandler); } #endif else if (msiTokenProviderFactory != null) { credentialsCache[adSettings.TokenAudience] = new TokenCredentials(this.msiTokenProviderFactory.Create(adSettings.TokenAudience.OriginalString)); } } await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
public void SilentUserLogin(string cnnStr) { LiteralCnnString = cnnStr; ServiceClientCredentials svcClientCred = null; svcClientCred = UserTokenProvider.LoginSilentAsync(this.ClientId, this.TenantId, this.UserName, this.Password, ActiveDirectoryServiceSettings.AzureGermany).GetAwaiter().GetResult(); Assert.NotNull(svcClientCred); }
public static ServiceClientCredentials GetCredentialFromPrompt(TokenCache tokenCache) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); // might need to specify the username as the 4th param if you need to switch user instead of the cached one //return UserTokenProvider.LoginWithPromptAsync(DomainOrTenantId, GetCredentialFromPromptClientSettings, ServiceSettings).GetAwaiter().GetResult(); return(UserTokenProvider.LoginWithPromptAsync(DomainOrTenantId, GetCredentialFromPromptClientSettings, ServiceSettings, tokenCache).GetAwaiter().GetResult()); }
public void InteractiveUserLogin(string cnnStr) { LiteralCnnString = cnnStr; ServiceClientCredentials svcClientCred = null; svcClientCred = UserTokenProvider.LoginWithPromptAsync(this.TenantId, GetADClientSettings(), ActiveDirectoryServiceSettings.AzureGermany, () => { return(TaskScheduler.FromCurrentSynchronizationContext()); }).GetAwaiter().GetResult(); Assert.NotNull(svcClientCred); }
public virtual async Task <string> GenerateUserTokenAsync(string purpose, TUser user) { if (UserTokenProvider == null) { throw new NotSupportedException("No Token Provider"); } if (user == null) { throw new ArgumentNullException("user"); } return(await UserTokenProvider.GenerateAsync(purpose, this, user)); }
public async void loginAsync() { try { ActiveDirectoryClientSettings activeDirectoryClientSettings = new ActiveDirectoryClientSettings(clientID, new Uri(redirectUri)); activeDirectoryClientSettings.PromptBehavior = Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior.Always; activeDirectoryClientSettings.OwnerWindow = this; ServiceClientCredentials credentials = await UserTokenProvider.LoginWithPromptAsync(activeDirectoryClientSettings); //MessageBox.Show(credentials.TenantId); //ResourceManagementClient resourceManagementClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credentials); SubscriptionClient subClient = new SubscriptionClient(credentials); var subs = await subClient.Subscriptions.ListAsync(); //TenantsOperationsExtensions //{ // SubscriptionId = SubscriptionId, // GenerateClientRequestId = true, // LongRunningOperationRetryTimeout = 60 * 6 //}; //AzureCredentials azureCredentials = new AzureCredentials(credentials, credentials, "common", AzureEnvironment.AzureGlobalCloud); //string tenant = Azure // .Authenticate(azureCredentials) // .TenantId; //MessageBox.Show(tenant); //var serviceClient = await credentials.InitializeServiceClient(); MessageBox.Show(credentials.ToString()); } catch (Exception e) { MessageBox.Show(e.Message); } //azureCredentials = new AzureCredentials(credentials, credentials, tenantID, AzureEnvironment.AzureGlobalCloud); }
public virtual async Task <bool> VerifyUserTokenAsync(TUser user, string purpose, string token) { if (UserTokenProvider == null) { throw new NotSupportedException("No Token Provider"); } if (user == null) { throw new ArgumentNullException("user"); } // Make sure the token is valid return(await UserTokenProvider.ValidateAsync(purpose, token, this, user)); }
public void OrgIdCredentialWorksWithoutDialog() { var credentials = UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, this._username, this._password).GetAwaiter().GetResult(); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); var response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; var url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } if (!_credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (_servicePrincipalLoginInformation != null) { if (_servicePrincipalLoginInformation.ClientSecret != null) { _credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, _servicePrincipalLoginInformation.ClientId, _servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } else { _credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, _servicePrincipalLoginInformation.ClientId, _servicePrincipalLoginInformation.Certificate, _servicePrincipalLoginInformation.CertificatePassword, TokenCache.DefaultShared); } } //else if (_userLoginInformation != null) //Not supported in .Net Core. UserTokenProvider.LoginSilentAsync does not exist //{ // _credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( // _userLoginInformation.ClientId, TenantId, _userLoginInformation.UserName, // _userLoginInformation.Password, adSettings, TokenCache.DefaultShared); //} else if (_deviceCredentialInformation != null) { _credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( _deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, _deviceCredentialInformation.DeviceCodeFlowHandler); } } await _credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
public void OrgIdCredentialsThrowsForInvalidCredentials() { var exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, "*****@*****.**", "This is not a valid password").GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalException), exception.InnerException.GetType()); exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, "bad_user@bad_domain.com", this._password).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalException), exception.InnerException.GetType()); exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "not-a-valid-domain", this._username, this._password).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalServiceException), exception.InnerException.GetType()); exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("not-a-valid-client-id", this._domain, this._username, this._password) .ConfigureAwait(false).GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalServiceException), exception.InnerException.GetType()); }
public static ServiceClientCredentials LoginAzureRM(this ICakeContext ctx, string tenantId, string loginName, string password) { if (string.IsNullOrWhiteSpace(tenantId)) { throw new ArgumentNullException(nameof(tenantId)); } if (string.IsNullOrWhiteSpace(loginName)) { throw new ArgumentNullException(nameof(loginName)); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException(nameof(password)); } return(UserTokenProvider.LoginSilentAsync(WELLKNOWN_CLIENTID, tenantId, loginName, password).GetAwaiter().GetResult()); }
/* * Interactive: User popup * (using a token cache to reuse/save session state) */ private static ServiceClientCredentials GetCredsInteractivePopup(string domain, Uri tokenAudience, TokenCache tokenCache, PromptBehavior promptBehavior = PromptBehavior.Auto) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var clientSettings = new ActiveDirectoryClientSettings { ClientId = azure_powershell_clientid, ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = promptBehavior }; var serviceSettings = ActiveDirectoryServiceSettings.Azure; serviceSettings.TokenAudience = tokenAudience; var creds = UserTokenProvider.LoginWithPromptAsync(domain, clientSettings, serviceSettings, tokenCache).GetAwaiter().GetResult(); return(creds); }
private static void LoginWithPromptAsync( Dictionary <TokenAudience, TokenCredentials> tokens, string domain, TestEndpoints endpoints) { var mgmSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.AADTokenAudienceUri }; var grpSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.GraphTokenAudienceUri }; var clientSettings = new ActiveDirectoryClientSettings() { ClientId = TestEnvironment.ClientIdDefault, ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = PromptBehavior.Auto }; var mgmAuthResult = (TokenCredentials)UserTokenProvider .LoginWithPromptAsync(domain, clientSettings, mgmSettings) .ConfigureAwait(false) .GetAwaiter().GetResult(); try { var graphAuthResult = (TokenCredentials)UserTokenProvider .LoginWithPromptAsync(domain, clientSettings, grpSettings) .GetAwaiter().GetResult(); tokens[TokenAudience.Graph] = graphAuthResult; } catch { // Not all accounts are registered to have access to Graph endpoints. } tokens[TokenAudience.Management] = mgmAuthResult; }
private static async Task LoginUserAsync( Dictionary <TokenAudience, TokenCredentials> tokens, string domain, string username, string password, TestEndpoints endpoints) { var mgmSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.AADTokenAudienceUri }; var grpSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.GraphTokenAudienceUri }; var mgmAuthResult = (TokenCredentials)await UserTokenProvider .LoginSilentAsync(TestEnvironment.ClientIdDefault, domain, username, password, mgmSettings) .ConfigureAwait(false); try { var graphAuthResult = (TokenCredentials)await UserTokenProvider .LoginSilentAsync(TestEnvironment.ClientIdDefault, domain, username, password, grpSettings) .ConfigureAwait(false); tokens[TokenAudience.Graph] = graphAuthResult; } catch { // Not all accounts are registered to have access to Graph endpoints. } tokens[TokenAudience.Management] = mgmAuthResult; }
public override Task <TokenDecodeResponseDTO> Decode(TokenDecodeRequestDTO request, ServerCallContext context) { return(Task.Run(() => { TokenDecodeResponseDTO response = new TokenDecodeResponseDTO(); var app = OAuthAppCache.Get(request.Appid); if (app == null) { response.RetCode = "0400"; response.RetMsg = "无效的应用id"; return response; } var ut = UserTokenProvider.DecryptAccessToken(request.Token); if (ut == null || !ut.Success) { response.RetCode = "0400"; response.RetMsg = "无效的token"; return response; } if (ut.Content.AppId != app.Id) { response.RetCode = "0402"; response.RetMsg = "操作不允许"; return response; } response.RetCode = "0000"; response.RetMsg = "ok"; response.Data = new TokenDecodeResponseDTO.Types.Result { Appid = ut.Content.AppId, ExpireTime = ut.Content.Expire_Time.ToString(), Usercode = ut.Content.UserCode, Userid = ut.Content.UserId }; return response; })); }
private static string localFilePropertyDumpPath = @"C:\Data"; // Used for Acl/DiskUsage Dump public static void Main(string[] args) { try { // Acquire token and create client using user id and password - Shown for illustration purposes, Comment following two lines if you are not authenticating with userid and password ServiceClientCredentials clientCreds1 = UserTokenProvider.LoginSilentAsync(clientId, domain, UserId, Psswd).GetAwaiter().GetResult(); AdlsClient client1 = AdlsClient.CreateClient(clientAccountPath, clientCreds1); // Acquire token and create client using client secret and client id var creds = new ClientCredential(clientId, clientSecret); ServiceClientCredentials clientCreds2 = ApplicationTokenProvider.LoginSilentAsync(domain, creds).GetAwaiter().GetResult(); AdlsClient client2 = AdlsClient.CreateClient(clientAccountPath, clientCreds2); // Perform write with flush and read with seek PerformWriteFlushReadSeek(client2); // Concatenate two files PerformConcat(client2); // Get Content summary using async operations GetContentSummaryAsync(client2).GetAwaiter().GetResult(); // Bulk upload and download RunFileTransfer(client2); // Change Acl and get acl and disk usage properties SetAclAndGetFileProperties(client2); // Illustrate token refresh TestTokenRefresh(client2); } catch (AdlsException e) { PrintAdlsException(e); } Console.WriteLine("Done. Press ENTER to continue ..."); Console.ReadLine(); }
public void UserCredentialsPopsDialog() { var cache = new TestTokenCache(); var settings = ActiveDirectoryServiceSettings.Azure; var credentials = UserTokenProvider.LoginWithPromptAsync(this._domain, ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, this._username, cache).GetAwaiter().GetResult(); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); var response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Repeat with PromptBehavior.Never credentials = UserTokenProvider.LoginWithPromptAsync(this._domain, ActiveDirectoryClientSettings.UseCacheOrCookiesOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, this._username, cache).GetAwaiter().GetResult(); request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Repeat with getting tokens strictly from cache credentials = UserTokenProvider.CreateCredentialsFromCache("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, this._username, cache).GetAwaiter().GetResult(); request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
/// <summary> /// Run interactive login /// </summary> /// <param name="tenant"></param> /// <param name="aadServiceSettings"></param> /// <param name="graphAADServiceSettings"></param> private void InteractiveLogin(string tenant, string PsClientId, ActiveDirectoryServiceSettings aadServiceSettings, ActiveDirectoryServiceSettings graphAADServiceSettings) { //#if FullNetFx #if net452 ActiveDirectoryClientSettings clientSettings = new ActiveDirectoryClientSettings() { ClientId = PsClientId, ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = PromptBehavior.Always }; TaskScheduler scheduler; if (SynchronizationContext.Current != null) { scheduler = TaskScheduler.FromCurrentSynchronizationContext(); } else { scheduler = TaskScheduler.Current; } Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginWithPromptAsync(this.Tenant, clientSettings, aadServiceSettings, () => { return(scheduler); }).ConfigureAwait(continueOnCapturedContext: false)); this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result; this.ConnectionString.KeyValuePairs[ConnectionStringKeys.UserIdKey] = this.TokenInfo[TokenAudience.Management].CallerId; try { Task <TokenCredentials> graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginWithPromptAsync(this.Tenant, clientSettings, graphAADServiceSettings, () => { return(scheduler); }).ConfigureAwait(continueOnCapturedContext: true)); this.TokenInfo[TokenAudience.Graph] = graphAuthResult.Result; } catch { // Not all accounts are registered to have access to Graph endpoints. } #endif }
/// <summary> /// Login /// </summary> private void Login() { string userPassword = this.ConnectionString.GetValue(ConnectionStringKeys.PasswordKey); string spnClientId = this.ConnectionString.GetValue(ConnectionStringKeys.ServicePrincipalKey); string spnSecret = this.ConnectionString.GetValue(ConnectionStringKeys.ServicePrincipalSecretKey); //We use this because when login silently using userTokenProvider, we need to provide a well known ClientId for an app that has delegating permissions. //All first party app have that permissions, so we use PowerShell app ClientId string PowerShellClientId = "1950a258-227b-4e31-a9cf-717495945fc2"; /* * Currently we prioritize login as below: * 1) ServicePrincipal/ServicePrincipal Secret Key * 2) UserName / Password combination * 3) Interactive Login (where user will be presented with prompt to login) */ #region Login #region aadSettings ActiveDirectoryServiceSettings aadServiceSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(this.Endpoints.AADAuthUri.ToString() + this.ConnectionString.GetValue(ConnectionStringKeys.AADTenantKey)), TokenAudience = this.Endpoints.AADTokenAudienceUri }; ActiveDirectoryServiceSettings graphAADServiceSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(this.Endpoints.AADAuthUri.ToString() + this.ConnectionString.GetValue(ConnectionStringKeys.AADTenantKey)), TokenAudience = this.Endpoints.GraphTokenAudienceUri }; #endregion if ((!string.IsNullOrEmpty(spnClientId)) && (!string.IsNullOrEmpty(spnSecret))) { Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(this.Tenant, spnClientId, spnSecret, aadServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result; UpdateTokenInfoWithGraphToken(graphAADServiceSettings, spnClientId: spnClientId, spnSecret: spnSecret); } else if ((!string.IsNullOrEmpty(this.UserName)) && (!string.IsNullOrEmpty(userPassword))) { //#if FullNetFx #if net452 Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginSilentAsync(PowerShellClientId, this.Tenant, this.UserName, userPassword, aadServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result; UpdateTokenInfoWithGraphToken(graphAADServiceSettings, userName: this.UserName, password: userPassword, psClientId: PowerShellClientId); #else throw new NotSupportedException("Username/Password login is supported only in NET452 and above projects"); #endif } else { //#if FullNetFx #if net452 InteractiveLogin(this.Tenant, PowerShellClientId, aadServiceSettings, graphAADServiceSettings); #else throw new NotSupportedException("Interactive Login is supported only in NET452 and above projects"); #endif } #endregion }
public UserTokenProviderTest() { _userTokenRepository = A.Fake<IUserTokenRepository>(); _userTokenProvider = new UserTokenProvider(_userTokenRepository); }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } string host = request.RequestUri.Host; if (host.EndsWith(Environment.KeyVaultSuffix, StringComparison.OrdinalIgnoreCase)) { var resource = new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")); if (credentialsCache.ContainsKey(new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")))) { adSettings.TokenAudience = resource; } else { using (var r = new HttpRequestMessage(request.Method, url)) { var response = await new HttpClient().SendAsync(r).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && response.Headers.WwwAuthenticate != null) { var header = response.Headers.WwwAuthenticate.ElementAt(0).ToString(); var regex = new Regex("authorization=\"([^\"]+)\""); var match = regex.Match(header); adSettings.AuthenticationEndpoint = new Uri(match.Groups[1].Value); regex = new Regex("resource=\"([^\"]+)\""); match = regex.Match(header); adSettings.TokenAudience = new Uri(match.Groups[1].Value); } } } } if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (servicePrincipalLoginInformation != null) { if (servicePrincipalLoginInformation.ClientId == null) { throw new RestException($"Cannot communicate with server. ServicePrincipalLoginInformation should contain a valid ClientId information."); } if (servicePrincipalLoginInformation.ClientSecret != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } #if NET45 else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #else else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new Microsoft.Rest.Azure.Authentication.ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #endif else if (servicePrincipalLoginInformation.Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, adSettings, TokenCache.DefaultShared); } else { throw new RestException($"Cannot communicate with server. ServicePrincipalLoginInformation should contain either a valid ClientSecret or Certificate information."); } } #if NET45 else if (userLoginInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( userLoginInformation.ClientId, TenantId, userLoginInformation.UserName, userLoginInformation.Password, adSettings, TokenCache.DefaultShared); } #else else if (deviceCredentialInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, deviceCredentialInformation.DeviceCodeFlowHandler); } #endif else if (msiTokenProviderFactory != null) { credentialsCache[adSettings.TokenAudience] = new TokenCredentials(this.msiTokenProviderFactory.Create(adSettings.TokenAudience.OriginalString)); } // no token available for communication else { throw new RestException($"Cannot communicate with server. No authentication token available for '{adSettings.TokenAudience}'."); } } await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
static void Main(string[] args) { var resourceGroupName = "your resource group name of iot hub"; var iothubName = "your iot hub name"; var tenantId = "your tenant"; var subscriptionId = "your subscription"; #region for native client, based on user login var nativeClientId = "your native client id"; var redirectUri = "your native client redirect uri"; var adServiceSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(AzureEnvironment.AzureChinaCloud.AuthenticationEndpoint), TokenAudience = new Uri(AzureEnvironment.AzureChinaCloud.ResourceManagerEndpoint), ValidateAuthority = true }; var adClientSettings = new ActiveDirectoryClientSettings() { ClientId = nativeClientId, ClientRedirectUri = new Uri(redirectUri) }; SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); ServiceClientCredentials azureCredential = null; try { azureCredential = UserTokenProvider.LoginWithPromptAsync(tenantId, adClientSettings, adServiceSettings).Result; } catch (Exception ex) { Console.WriteLine($"Acquire credential failed: {ex.Message}"); } #endregion #region for web client, based on clientid and clientsecret //var webClientId = "your web client id"; //azureCredential = SdkContext.AzureCredentialsFactory.FromServicePrincipal( // webClientId, // "!!123abc", // tenantId, // AzureEnvironment.AzureChinaCloud); #endregion if (azureCredential != null) { var iothubClient = new IotHubClient(new Uri("https://management.chinacloudapi.cn/"), azureCredential, new RetryDelegatingHandler()); iothubClient.SubscriptionId = subscriptionId; var iothubResource = iothubClient.IotHubResource; // get iothub description var iothubDescription = iothubResource.Get(resourceGroupName, iothubName); Console.WriteLine($"Get iothub successfully: {iothubDescription.Name}"); // set C2D message default ttl to 2 hours iothubDescription.Properties.CloudToDevice.DefaultTtlAsIso8601 = TimeSpan.FromHours(2); try { // commit the change iothubResource.CreateOrUpdate(resourceGroupName, iothubName, iothubDescription); Console.WriteLine("Update iothub successfully!"); } catch (Exception ex) { Console.WriteLine($"Update iothub failed: {ex.Message}"); } } Console.WriteLine("Press ENTER to exit!"); Console.ReadLine(); }
public string GenerateConfirmEmailToken(User user) { return(UserTokenProvider.GenerateAsync("EmailConfirmation", this, user).Result); }
public bool ValidateConfirmEmailToken(User user, string token) { return(UserTokenProvider.ValidateAsync("EmailConfirmation", token, this, user).Result); }