/// <summary> /// Create the authorization header /// </summary> /// <param name="tenantId"></param> /// <param name="clientId"></param> //Application ID /// <param name="clientSecrets"></param> /// <returns></returns> private static string GetAuthorizationHeader(string tenantId, string clientId, string clientSecrets) { //https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal AuthenticationResult result = null; var context = new AuthenticationContext(String.Format("https://login.windows.net/{0}", tenantId)); var thread = new Thread(() => { var authParam = new PlatformParameters(PromptBehavior.Never, null); result = context.AcquireTokenAsync( "https://management.core.windows.net/", new ClientCredential(clientId, clientSecrets)).Result; }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AquireTokenThread"; thread.Start(); thread.Join(); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } string token = result.AccessToken; return(token); }
public static async Task <string> GetAuthTokenByUserCredentialsInteractiveAsync(Settings input) { var resource = GetResourceUrl(input); if (string.IsNullOrWhiteSpace(input.Tenant) || string.IsNullOrWhiteSpace(input.ClientId) || string.IsNullOrWhiteSpace(resource) || string.IsNullOrWhiteSpace(input.ReplyUrl)) { throw new ArgumentException($"To use the User-credentials interactive-flow, please provide valid Tenant, ClientId, ResourceUrl, ReplyUrl in '{input.AppSettingsFile}'"); } var accessToken = await AuthTokens.GetOrAdd(input.Tenant ?? string.Empty, k => { return(new Lazy <Task <string> >(async() => { var ctx = GetAuthenticationContext(input.Tenant); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; var promptBehavior = new PlatformParameters(PromptBehavior.SelectAccount, new CustomWebUi()); ColorConsole.Write("Authenticating...\n"); try { result = await ctx.AcquireTokenAsync(resource, input.ClientId, new Uri(input.ReplyUrl), promptBehavior); } catch (UnauthorizedAccessException) { // If the token has expired, prompt the user with a login prompt result = await ctx.AcquireTokenAsync(resource, input.ClientId, new Uri(input.ReplyUrl), promptBehavior); } return result?.AccessToken; })); }).Value; return(accessToken); }
public async Task <bool> InitializeAsync() { var tenant = _configurationReader["AAD_Tenant"]; var instance = _configurationReader["AAD_Instance"]; var resourceId = _configurationReader["AAD_ResourceId"]; var clientId = _configurationReader["AAD_ClientId"]; var callbackUrl = _configurationReader["AAD_CallbackUri"]; var callbackUri = new Uri(callbackUrl); var authority = String.Format(CultureInfo.InvariantCulture, instance, tenant); var redirectUri = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); var authContext = new AuthenticationContext(authority); var platformParameters = new PlatformParameters(PromptBehavior.Auto, false); _authenticationResult = await authContext.AcquireTokenAsync(resourceId, clientId, callbackUri, platformParameters); if (_authenticationResult == null) { return(false); } return(true); }
private async Task <Dictionary <AuthenticationAccessToken, AuthenticationResult> > GetAccessToken() { Dictionary <AuthenticationAccessToken, AuthenticationResult> authResult = new Dictionary <AuthenticationAccessToken, AuthenticationResult>(); AuthenticationResult result1 = null; AuthenticationResult result2 = null; try { var authority = $"{AadInstance}{Tenant}"; var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared); //PromptBehavior //Auto == prompt only when necessary (use cached token if it exists) //Always == useful for debug as you will always have to authenticate var authParms = new PlatformParameters(PromptBehavior.SelectAccount); var keyvaultauthparams = new PlatformParameters(PromptBehavior.Auto); result1 = authContext.AcquireTokenAsync(Resource, ClientId, new Uri(RedirectUri), authParms).Result; result2 = authContext.AcquireTokenAsync(KeyvaultResource, ClientId, new Uri(RedirectUri), keyvaultauthparams).Result; if (result1 != null && result2 != null && !string.IsNullOrEmpty(result1.AccessToken) && !string.IsNullOrEmpty(result2.AccessToken)) { authResult.Add(AuthenticationAccessToken.IntegrationAccount, result1); authResult.Add(AuthenticationAccessToken.KeyVault, result2); return(authResult); } else { throw new Exception("Failed to retrieve the access token"); } } catch (Exception x) { throw new Exception(ExceptionHelper.GetExceptionMessage(x)); } }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. GetTokenButton.TouchUpInside += async(sender, e) => { try { // Use ADAL directly in this app //var context = new AuthenticationContext(authority); //var platformParameters = new PlatformParameters(this); //var response = await context.AcquireTokenAsync(resource, clientId, new Uri(returnUrl), platformParameters); //TokenTextView.Text = response.AccessToken; // Use ADAL via another PCL var tokenService = new PortableLibrary.TokenService(Authority); var platformParameters = new PlatformParameters(this); var token = await tokenService.GetTokenAsync(Resource, ClientId, ReturnUrl, platformParameters); TokenTextView.Text = token; } catch (Exception ex) { TokenTextView.Text = $"Exception: {ex.Message}"; } }; }
/// <summary> /// Attempt interactive authentication through the broker. /// </summary> /// <param name="platformParams"> Additional paramaters for authentication.</param> /// <returns>The AuthenticationResult on succes, null otherwise.</returns> public async Task <AuthenticationResult> SignInWithPrompt(PlatformParameters platformParams) { AuthenticationResult result = null; try { Log.Info(_logTagAuth, "Attempting interactive authentication"); result = await AuthContext.AcquireTokenAsync( _resourceID, _clientID, new Uri(_redirectURI), platformParams); } catch (AdalException e) { string msg = Resource.String.err_auth + e.Message; Log.Error(_logTagAuth, Throwable.FromException(e), msg); Toast.MakeText(platformParams.CallerActivity, msg, ToastLength.Long).Show(); return(null); } isAuthenticated = true; return(result); }
public AuthenticatorDroid() { var platformParameters = new PlatformParameters((Activity)Forms.Context, false, PromptBehavior.Auto); _authenticatorService = new AuthenticatorService(platformParameters); }
internal Guid Connect(string whoamiUrl) { const string authority = "https://login.microsoftonline.com/common"; var context = new AuthenticationContext(authority, false); var platformParameters = new PlatformParameters(PromptBehavior.SelectAccount); string accessToken = context.AcquireTokenAsync(baseUrl, clientId, new Uri(redirectUri), platformParameters, UserIdentifier.AnyUser).Result.AccessToken; client = new HttpClient(); client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); client.Timeout = new TimeSpan(0, 2, 0); client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); client.DefaultRequestHeaders.Add("OData-Version", "4.0"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Use the WhoAmI function var response = client.GetAsync(whoamiUrl).Result; //Get the response content and parse it. response.EnsureSuccessStatusCode(); JObject body = JObject .Parse(response.Content.ReadAsStringAsync().Result); Guid userId = (Guid)body["UserId"]; return(userId); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task <IAdalToken> AcquireTokenWithUI(CancellationToken cancellationToken) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { #if NETFRAMEWORK var authenticationContext = new AuthenticationContext(authority, tokenCache); var parameters = new PlatformParameters(PromptBehavior.Always); try { var result = await authenticationContext.AcquireTokenAsync(resource, clientId, new Uri(NativeClientRedirect), parameters); cancellationToken.ThrowIfCancellationRequested(); return(new AdalToken(result)); } catch (AdalServiceException e) { if (e.ErrorCode == AdalError.AuthenticationCanceled) { return(null); } throw; } #else // no UI in ADAL on netcore return(null); #endif }
// Get an access token for the given context and resourceId. An attempt is first made to // acquire the token silently. If that fails, then we try to acquire the token by prompting the user. private static async Task <string> GetTokenHelperAsync(AuthenticationContext context, string resourceId) { string accessToken = null; AuthenticationResult result = null; try { // can use this app inside a corporate intranet. If the value of UseCorporateNetwork // is true, you also need to add the Enterprise Authentication, Private Networks, and // Shared User Certificates capabilities in the Package.appxmanifest file. var platformParameters = new PlatformParameters(PromptBehavior.Auto, true); result = await context.AcquireTokenAsync(resourceId, ClientID, redirectUri, platformParameters); accessToken = result.AccessToken; //Store values for logged-in user, tenant id, and authority, so that //they can be re-used if the user re-opens the app without disconnecting. _settings.Values["LoggedInUser"] = result.UserInfo.GivenName; _settings.Values["LoggedInUserEmail"] = result.UserInfo.DisplayableId; _settings.Values["TenantId"] = result.TenantId; _settings.Values["LastAuthority"] = context.Authority; AccessToken = accessToken; return(accessToken); } catch { return(null); } }
private static async Task <AuthenticationResult> GetAuthenticationResult(bool retry = false) { var authCtx = GetAuthenticationContext(); try { var platformParameters = new PlatformParameters(PromptBehavior.Auto, true); var authResult = await authCtx.AcquireTokenAsync(_resourceId, _clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"), platformParameters); System.Diagnostics.Debug.WriteLine("Token expires on: " + authResult.ExpiresOn); return(authResult); } catch (UnauthorizedAccessException ex) { throw ex; } catch (AdalServiceException ex) { if (ex.ErrorCode == "authentication_canceled" && retry) { authCtx.TokenCache.Clear(); // Try again return(await GetAuthenticationResult(false)); } else { throw ex; } } }
public async Task <AuthenticationResult> Authenticate(Activity context, string authority, string resource, string clientId, string returnUri) { var authContext = new AuthenticationContext(authority); if (authContext.TokenCache.ReadItems().Any()) { authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); } //var result = await authContext.AcquireDeviceCodeAsync("https://login.windows.net/common", B2CConfig.ClientId); var uri = new Uri(returnUri); var platformParams = new PlatformParameters(context); try { var authResult = await authContext.AcquireTokenAsync(clientId, clientId, uri, platformParams); //var authResult = await authContext.AcquireTokenAsync("https://CSUB2C.onmicrosoft.com/EMTestDeploy", new ClientCredential(B2CConfig.ClientId, B2CConfig.ClientSecret)); var re = await authContext.AcquireTokenByAuthorizationCodeAsync(authResult.AccessToken, uri, new ClientCredential(B2CConfig.ClientId, B2CConfig.ClientSecret)); return(authResult); } catch (AdalException) { return(null); } }
//public bool Do_OAuth(ref ExchangeService oService, ref string MailboxBeingAccessed, ref string AccountAccessingMailbox, // string sAuthority, string sAppId, string sRedirectURL, string sServername) //{ // bool bRet = false; // // See // https://msdn.microsoft.com/en-us/library/office/dn903761(v=exchg.150).aspx // // get authentication token // string authority = sAuthority; // string clientID = sAppId; // Uri clientAppUri = new Uri(sRedirectURL); // string serverName = sServername; // AuthenticationContext authenticationContext = new AuthenticationContext(authority, false); // PlatformParameters oPlatformParameters = new PlatformParameters(PromptBehavior.Always); // AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(serverName, clientID, clientAppUri, oPlatformParameters).Result; // //System.Diagnostics.Debug.WriteLine(authenticationResult.UserInfo.DisplayableId); // MailboxBeingAccessed = authenticationResult.UserInfo.DisplayableId; // AccountAccessingMailbox = authenticationResult.UserInfo.DisplayableId; // oAuth at this time does not support delegate or impersonation access - may need to change this in the future. // // Add authenticaiton token to requests // oService.Credentials = new OAuthCredentials(authenticationResult.AccessToken); // bRet = true; // return bRet; //} public ExchangeCredentials Do_OAuth(ref string MailboxBeingAccessed, ref string AccountAccessingMailbox, string sAuthority, string sAppId, string sRedirectURL, string sServername, ref string sBearerToken, PromptBehavior oPromptBehavior) { ExchangeCredentials oExchangeCredentials = null; // See // https://msdn.microsoft.com/en-us/library/office/dn903761(v=exchg.150).aspx // get authentication token string authority = sAuthority; string clientID = sAppId; Uri clientAppUri = new Uri(sRedirectURL); string serverName = sServername; AuthenticationContext authenticationContext = new AuthenticationContext(authority, false); PlatformParameters oPlatformParameters = new PlatformParameters(oPromptBehavior); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(serverName, clientID, clientAppUri, oPlatformParameters).Result; sBearerToken = authenticationResult.AccessToken; // Add authenticaiton token to requests oExchangeCredentials = new OAuthCredentials(authenticationResult.AccessToken); MailboxBeingAccessed = authenticationResult.UserInfo.DisplayableId; AccountAccessingMailbox = authenticationResult.UserInfo.DisplayableId; // oAuth at this time does not support delegate or impersonation access - may need to change this in the future. return(oExchangeCredentials); }
private string GetAuthorizationHeader() { string tenantId = "{your-tenant-id}"; string clientId = "your-aad-app-client-id"; string clientSecrets = "{your-aad-app-client-secret}"; AuthenticationResult result = null; var context = new AuthenticationContext(String.Format("https://login.windows.net/{0}", tenantId)); var thread = new Thread(() => { var authParam = new PlatformParameters(PromptBehavior.Never, null); result = context.AcquireTokenAsync( "https://management.azure.com/" , new ClientCredential(clientId, clientSecrets) ).Result; }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AquireTokenThread"; thread.Start(); thread.Join(); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } string token = result.AccessToken; return(token); }
public override async Task <AuthenticationResult> AuthenticateUser(string resource) { var controller = UIApplication.SharedApplication.KeyWindow.RootViewController; var _platformParams = new PlatformParameters(controller); var uri = new Uri(returnUri); var authContext = new AuthenticationContext(authority); if (authContext.TokenCache.ReadItems().Any()) { if (authContext.TokenCache.ReadItems().First().Authority.Equals(authority)) { authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); } } try { var authResult = await authContext.AcquireTokenAsync(resource, PrivateKeys.ProspectMgmtClientId, uri, _platformParams); return(authResult); } catch (AdalException ex) { Logout(); var authResult = await authContext.AcquireTokenAsync(resource, PrivateKeys.ProspectMgmtClientId, uri, _platformParams); return(authResult); } }
public void Initialize() { HttpMessageHandlerFactory.InitializeMockProvider(); InstanceDiscovery.InstanceCache.Clear(); HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityCommonTenant))); platformParameters = new PlatformParameters(PromptBehavior.Auto); }
internal const string azureDevOpsResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Constant value to target Azure DevOps. Do not change public static void Main(string[] args) { AuthenticationContext ctx = GetAuthenticationContext(null); AuthenticationResult result = null; IPlatformParameters promptBehavior = new PlatformParameters(); #if NET452 promptBehavior = new PlatformParameters(PromptBehavior.Always); #endif try { //PromptBehavior.RefreshSession will enforce an authn prompt every time. NOTE: Auto will take your windows login state if possible result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, new Uri(replyUri), promptBehavior).Result; Console.WriteLine("Token expires on: " + result.ExpiresOn); var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken); ListProjects(bearerAuthHeader); } catch (UnauthorizedAccessException) { // If the token has expired, prompt the user with a login prompt result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, new Uri(replyUri), promptBehavior).Result; } catch (Exception ex) { Console.WriteLine("{0}: {1}", ex.GetType(), ex.Message); } }
private static IPlatformParameters GetPlatformParametersInstance(string promptBehaviorString) { IPlatformParameters platformParameters = null; PromptBehavior pb = PromptBehavior.Auto; if (!string.IsNullOrEmpty(promptBehaviorString)) { pb = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), promptBehaviorString, true); } #if __ANDROID__ platformParameters = new PlatformParameters(this); #else #if __IOS__ platformParameters = new PlatformParameters(this); #else #if (WINDOWS_UWP || WINDOWS_APP) platformParameters = new PlatformParameters(PromptBehavior.Always, false); #else //desktop platformParameters = new PlatformParameters(pb, null); #endif #endif #endif return(platformParameters); }
public async Task <ADToken> AuthenticationAsync() { try { var platformParams = new PlatformParameters(CrossCurrentActivity.Current.Activity); var authContext = new AuthenticationContext(TenantUrl); if (authContext.TokenCache.ReadItems().Any()) { authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority); } var authResult = await authContext.AcquireTokenAsync(WebApiADClientId, ADClientId, returnUriId, platformParams); return(new ADToken() { AccessToken = authResult.AccessToken, TokenType = authResult.AccessTokenType, Expires = authResult.ExpiresOn.Ticks, UserName = authResult.UserInfo.DisplayableId }); } catch (Exception ex) { throw ex; } }
/// <summary> /// Acquires a token from Azure AD to be used in subsequent calls to the Graph API /// </summary> /// <returns>Bearer token</returns> private static async Task <AuthenticationResult> GetToken() { var authority = $"{aadInstance}{tenant}"; authContext = new AuthenticationContext(authority); AuthenticationResult result = null; try { //PromptBehavior //Auto == prompt only when necessary (use cached token if it exists) //Always == useful for debug as you will always have to authenticate var authParms = new PlatformParameters(PromptBehavior.Auto, false); result = await authContext.AcquireTokenAsync(ResourceId, clientId, redirectURI, authParms); } catch (Exception x) { if (x.Message == "User canceled authentication") { // Do nothing } return(null); } return(result); }
public async Task <IAdalToken> AcquireTokenWithUI(CancellationToken cancellationToken) { var authenticationContext = new AuthenticationContext(authority, tokenCache); var parameters = #if NETFRAMEWORK new PlatformParameters(PromptBehavior.Always); #else new PlatformParameters(); #endif try { var result = await authenticationContext.AcquireTokenAsync(resource, clientId, new Uri(NativeClientRedirect), parameters); cancellationToken.ThrowIfCancellationRequested(); return(new AdalToken(result)); } catch (AdalServiceException e) { if (e.ErrorCode == AdalError.AuthenticationCanceled) { return(null); } throw; } }
public async Task <AuthenticationResult> AcquireTokenAsync() { // Clear the cache. TokenCache.DefaultShared.Clear(); // Create the authentication context. var authenticationContext = new AuthenticationContext(Constants.Authority); // Create the platform parameters. var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController; var platformParameters = new PlatformParameters(viewController); try { // Authenticate the user. var authenticationResult = await authenticationContext.AcquireTokenAsync( Constants.GraphResource, Constants.ClientId, Constants.RedirectUri, platformParameters); return(authenticationResult); } catch (AdalException ex) { if (ex.ErrorCode == AdalError.AuthenticationCanceled) { return(null); } throw; } }
public override void AddPromptBehaviorQueryParameter(IPlatformParameters parameters, DictionaryRequestParameters authorizationRequestParameters) { PlatformParameters authorizationParameters = (parameters as PlatformParameters); if (authorizationParameters == null) { throw new ArgumentException("parameters should be of type PlatformParameters", "parameters"); } PromptBehavior promptBehavior = authorizationParameters.PromptBehavior; switch (promptBehavior) { case PromptBehavior.Always: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.Login; break; case PromptBehavior.SelectAccount: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.SelectAccount; break; case PromptBehavior.RefreshSession: authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.RefreshSession; break; } }
public static async Task <string> GetAuthTokenAsync(string tenantId) { var accessToken = await AuthTokens.GetOrAdd(tenantId ?? string.Empty, k => { return(new Lazy <Task <string> >(async() => { var ctx = GetAuthenticationContext(tenantId); // null AuthenticationResult result = null; var promptBehavior = new PlatformParameters(PromptBehavior.SelectAccount, new CustomWebUi()); ColorConsole.WriteLine("Authenticating..."); try { result = await ctx.AcquireTokenAsync(AzureDevOpsResourceId, ClientId, new Uri(ReplyUri), promptBehavior); } catch (UnauthorizedAccessException) { // If the token has expired, prompt the user with a login prompt result = await ctx.AcquireTokenAsync(AzureDevOpsResourceId, ClientId, new Uri(ReplyUri), promptBehavior); } return result?.AccessToken; })); }).Value; return(accessToken); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); RegisterForPushNotifications(); RegisterFragments(bundle); SetContentView(Resource.Layout.MainView); var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); _drawerLayout = FindViewById <DrawerLayout>(Resource.Id.drawer_layout); _drawerLayout.SetDrawerShadow(Resource.Drawable.drawer_shadow_light, (int)GravityFlags.Start); _drawerToggle = new MvxActionBarDrawerToggle(this, _drawerLayout, Resource.String.drawer_open, Resource.String.drawer_close); _drawerToggle.DrawerClosed += (_, e) => InvalidateOptionsMenu(); _drawerToggle.DrawerOpened += (_, e) => InvalidateOptionsMenu(); SupportActionBar.SetDisplayShowTitleEnabled(false); SupportActionBar.SetDisplayHomeAsUpEnabled(true); _drawerToggle.DrawerIndicatorEnabled = true; _drawerLayout.SetDrawerListener(_drawerToggle); _drawerLayout.Post(() => _drawerToggle.SyncState()); _bindableProgress = new BindableProgress(this); SetUpBindings(); Akavache.BlobCache.ApplicationName = "MyHealth"; ViewModel.ShowMenu(); ViewModel.ShowHome(); var authContext = new PlatformParameters(this); Task.Run(() => SignIn(authContext)); }
public async Task Authenticate(PlatformParameters pp = null) { _httpClient = new HttpClient(); var authorityURL = new Uri(new Uri(LOGIN_SERVICE_URL), TenantName).ToString(); AuthenticationResult result; var authenticationContext = new AuthenticationContext(authorityURL); // ADAL if (ClientSecret == null) { // user interactive authentication // On NET4.5 --> PlatformParameters pp = new PlatformParameters(PromptBehavior.Auto); result = await authenticationContext.AcquireTokenAsync(MANAGEMENT_URL, ClientId, new Uri(RedirectUrl), pp); } else { // application authentication ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret); result = await authenticationContext.AcquireTokenAsync(MANAGEMENT_URL, clientCred); } if (result == null) { throw new ApplicationException("Cannot obtain token"); } string accessToken = result.AccessToken; _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // <--- JWT token for all requests }
private StorageCredentials GetStorageCredentials() { //generate Access Token and its Expire Time string tenantId = ConfigurationManager.AppSettings["TenantId"]; AuthenticationContext authenticationContext = new AuthenticationContext("https://login.windows.net/" + tenantId); string resource = "https://management.azure.com/"; string clientId = ConfigurationManager.AppSettings["ClientId"]; Uri redirectUri = new Uri("http://backupapp"); IPlatformParameters platformParameters = new PlatformParameters(PromptBehavior.Auto); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientId, redirectUri, platformParameters).Result; var settings = ConfigurationManager.AppSettings["CloudStorageAccountName"].Split(' '); if (settings.Count() != 3) { throw new Exception("Configuration value for storage account is wrong, it should be looks like: apimmigratedev ydou-apim-migration f9b96b36-1f5e-4021-8959-51527e26e6d3."); } StorageManagementClient mClient = new StorageManagementClient(new TokenCloudCredentials(settings[2], authenticationResult.AccessToken)); var keys = mClient.StorageAccounts.ListKeys(settings[1], settings[0]); StorageAccountName = settings[0]; return(new StorageCredentials(settings[0], keys.StorageAccountKeys.Key1)); }
private async Task <AuthenticationResult> GetAccessToken() { AuthenticationResult authResult = null; try { var authority = $"{AadInstance}{Tenant}"; var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared); //PromptBehavior //Auto == prompt only when necessary (use cached token if it exists) //Always == useful for debug as you will always have to authenticate var authParms = new PlatformParameters(PromptBehavior.SelectAccount); authResult = authContext.AcquireTokenAsync(Resource, ClientId, new Uri(RedirectUri), authParms).Result; if (authResult != null && !string.IsNullOrEmpty(authResult.AccessToken)) { return(authResult); } else { throw new Exception("Failed to retrieve the access token"); } } catch (Exception x) { throw (x); } }
internal async Task <AuthenticationResult> LoginAzureProvider(AzureEnvironment azureEnvironment) { _LogProvider.WriteLog("LoginAzureProvider", "Start token request"); _LogProvider.WriteLog("LoginAzureProvider", "Azure Environment: " + azureEnvironment.ToString()); string authenticationUrl = AzureServiceUrls.GetAzureLoginUrl(azureEnvironment) + "common"; _LogProvider.WriteLog("LoginAzureProvider", "Authentication Url: " + authenticationUrl); AuthenticationContext context = new AuthenticationContext(authenticationUrl); PlatformParameters platformParams = new PlatformParameters(PromptBehavior.Always, null); AuthenticationResult authenticationResult = await context.AcquireTokenAsync(AzureServiceUrls.GetASMServiceManagementUrl(azureEnvironment), strClientId, new Uri(strReturnUrl), platformParams); if (authenticationResult == null) { _LogProvider.WriteLog("LoginAzureProvider", "Failed to obtain the token (null AuthenticationResult returned)."); } _AuthenticationResult = authenticationResult; _LogProvider.WriteLog("LoginAzureProvider", "End token request for Azure Environment " + azureEnvironment.ToString()); return(_AuthenticationResult); }
public async Task GetToken(AzureSubscription azureSubscription) { _LogProvider.WriteLog("GetToken", "Start token request"); if (azureSubscription == null) { _LogProvider.WriteLog("GetToken", "Azure Subscription cannot be null."); throw new ArgumentNullException("Azure Subscription cannot be null."); } _LogProvider.WriteLog("GetToken", "Azure Subscription: " + azureSubscription.ToString()); string authenticationUrl = AzureServiceUrls.GetAzureLoginUrl(azureSubscription.AzureEnvironment) + azureSubscription.AzureAdTenantId.ToString(); _LogProvider.WriteLog("GetToken", "Authentication Url: " + authenticationUrl); _AuthenticationResult = null; AuthenticationContext context = new AuthenticationContext(authenticationUrl); PlatformParameters platformParams = new PlatformParameters(PromptBehavior.Auto, null); _AuthenticationResult = await context.AcquireTokenAsync(AzureServiceUrls.GetASMServiceManagementUrl(azureSubscription.AzureEnvironment), strClientId, new Uri(strReturnUrl), platformParams); _LogProvider.WriteLog("GetToken", "End token request"); }
public async System.Threading.Tasks.Task<AuthenticationResult> Authenticate(string authority, string clientId, string returnUri, string policy) { var authContext = new AuthenticationContext(authority); if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); var platformParams = new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController); //var authResult = await authContext.AcquireTokenAsync(new string[] { clientId }, null, clientId, new Uri(returnUri), platformParams, "B2C_1_TestB2C"); var authResult = await authContext.AcquireTokenAsync(new string[] { clientId }, null, clientId, new Uri(returnUri), platformParams, policy); //var authResult = await authContext.AcquireTokenAsync(resource, clientId, new Uri(returnUri), // new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController)); return authResult; }