static void Main(string[] args) { Console.WriteLine("Press enter to start.."); Console.Read(); AuthenticationResult result = null; int retryCount = 0; bool retry = false; do { try { result = authContext.AcquireToken(serviceResourceId, clientCredential); } catch (AdalException ex) { if (ex.ErrorCode == "temporarily_unavailable") { retry = true; retryCount++; Thread.Sleep(3000); } } } while ((retry == true) && (retryCount < 3)); if (result == null) { Console.WriteLine("Cancelling attempt..."); return; } Console.WriteLine("Authenticated successfully.. makeing HTTPS call.."); MakeHttpsCall(result).Wait(); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); SetIncidentId(); DefaultTokenCacheStore cache = new DefaultTokenCacheStore(this); authContext = new AuthenticationContext(this, Constants.AAD_AUTHORITY, false, cache); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.signIn_btn); button.Click += delegate { authContext.AcquireToken(this, Constants.SHAREPOINT_URL, Constants.AAD_CLIENT_ID, Constants.AAD_REDIRECT_URL, PromptBehavior.RefreshSession, new SignInCallback(this)); }; }
private string GetToken(string tenantId, PromptBehavior promptBehavior, bool updateUI = false) { //"d94647e7-c4ff-4a93-bbe0-d993badcc5b8" AuthenticationContext context = new AuthenticationContext(ServiceUrls.GetLoginUrl(app.Default.AzureAuth) + tenantId); AuthenticationResult result = null; try { result = context.AcquireToken(ServiceUrls.GetServiceManagementUrl(app.Default.AzureAuth), app.Default.ClientId, new Uri(app.Default.ReturnURL), promptBehavior); if (result == null) { throw new InvalidOperationException("Failed to obtain the token"); } if (updateUI) { // lblSignInText.Text = $"Signed in as {result.UserInfo.DisplayableId}"; } return(result.AccessToken); } catch (Exception exception) { DialogResult dialogresult = MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } }
protected static void GetAccessToken() { // shared login authority for all Office 365 tenants string authority = "https://login.microsoftonline.com/common"; // create new authentication context var authenticationContext = new AuthenticationContext(authority); // create URI for target resource string urlAzureGraphApi = "https://graph.windows.net/"; string tenantDomain = "CptLabs.onMicrosoft.com"; Uri uriAzureGraphApiResource = new Uri(urlAzureGraphApi + tenantDomain); // string clientID = "19f2d875-25b2-4ce1-89fc-8215f6de6dba"; string redirectUri = "https://localhost/AzureGraphNativeClient"; // use authentication context to trigger user sign-in and return access token var userAuthnResult = authenticationContext.AcquireToken(urlAzureGraphApi, clientID, new Uri(redirectUri), PromptBehavior.Auto); // cache access token in AccessToken field AccessToken = userAuthnResult.AccessToken; }
private static string GetAuthorizationHeader(string tenantId, string authUrlHost, string clientId, string resource) { AuthenticationResult result = null; var thread = new Thread(() => { try { var authUrl = String.Format(authUrlHost + "/{0}", tenantId); var context = new AuthenticationContext(authUrl); result = context.AcquireToken( resource: resource, clientId: clientId, redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"), promptBehavior: PromptBehavior.Auto); } catch (Exception threadEx) { Console.WriteLine(threadEx.Message); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); thread.Join(); return(result.CreateAuthorizationHeader()); }
/// <summary> /// Get the token for authenticating requests to Azure Resource Manager in customer tenant. /// </summary> /// <param name="appId">appid that is registered for this application in Azure Active Directory (AAD)</param> /// <param name="key">This is the key for this application in Azure Active Directory</param> /// <param name="customerTenantId">cid of the customer</param> /// <returns>Azure Auth Token in the context of the customer tenant.</returns> private static AuthenticationResult GetAzureAuthTokenForCustomerTenant(string appId, string credentialName, string customerTenantId) { AuthenticationResult authResult = null; string resource = "https://management.core.windows.net/"; var authenticationContext = new AuthenticationContext("https://login.windows.net/" + customerTenantId); try { authResult = authenticationContext.AcquireTokenSilent(resource: resource, clientId: appId); } catch (AdalException aex) { if (aex.ErrorCode == "failed_to_acquire_token_silently") { UserCredential uc = CredentialManager.GetCredential(credentialName); authResult = authenticationContext.AcquireToken(resource: resource, clientId: appId, userCredential: uc); } } catch (Exception ex) { throw; } return(authResult); }
public static string GetTokenForSpn(string authority, string audience, string domain, string applicationId, string secret) { var context = new AuthenticationContext(EnsureTrailingSlash(authority) + domain, true, TokenCache.DefaultShared); var authResult = context.AcquireToken(audience, new ClientCredential(applicationId, secret)); return(authResult.AccessToken); }
/// <summary> /// Get Token for Application. /// </summary> /// <returns>Token for application.</returns> public static string GetTokenForApplication() { AuthenticationContext authenticationContext = new AuthenticationContext(Constants.AuthString, false); // Config for OAuth client credentials //ClientCredential clientCred = new ClientCredential(Constants.ClientId, Constants.ClientSecret); //AuthenticationResult authenticationResult = authenticationContext.AcquireToken(Constants.ResourceUrl, // clientCred); AuthenticationResult result = null; var username = "******"; var password = "******"; // var userPasswordCredential = new UserPasswordCredential(username, password); UserCredential uc = new UserCredential(username, password); try { result = authenticationContext.AcquireToken(Constants.ResourceUrl, Constants.ClientId, uc); } catch (Exception e) { string a = e.Message.ToString(); } // authenticationContext.AcquireToken() string token = result.AccessToken; return(token); }
/// <summary> /// Methods for getting a token from ACS /// Updated 10/21, to use Active Directory Authn Library (ADAL) /// Method uses OAuth Authorization Code Grant flow (3-legged OAuth) /// ADAL package avaialble from https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/1.0.0 /// </summary> public static AADJWTToken GetAuthorizationToken(string tenantName, string appPrincipalId, Uri appUri) { string authString = String.Format(StringConstants.AzureADSTSURL, tenantName); AuthenticationContext authenticationContext = new AuthenticationContext(authString); try { AuthenticationResult authenticationResult = authenticationContext.AcquireToken(StringConstants.GraphPrincipalId.ToString(), appPrincipalId, appUri); if (authenticationResult != null) { AADJWTToken token = new AADJWTToken(); token.AccessToken = authenticationResult.AccessToken; token.TokenType = authenticationResult.AccessTokenType; token.ExpiresOn = authenticationResult.ExpiresOn.UtcTicks; token.AdalToken = authenticationResult; return(token); } else { return(null); } } catch (Exception e) { //Console.WriteLine("Exception: " + e.Message + " " + e.InnerException); return(null); } }
/// <summary> /// Returns token (requires user input) /// </summary> /// <returns></returns> public static AuthenticationResult GetToken(string authEndpoint, string tenant, string clientId) { var adalWinFormType = typeof(WebBrowserNavigateErrorEventArgs); Trace.WriteLine("Getting a random type from \'Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms\' to force it be deployed by mstest"); AuthenticationResult result = null; var thread = new Thread(() => { try { var context = new AuthenticationContext(Path.Combine(authEndpoint, tenant)); result = context.AcquireToken( resource: "https://management.core.windows.net/", clientId: clientId, redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"), promptBehavior: PromptBehavior.Auto); } catch (Exception threadEx) { Console.WriteLine(threadEx.Message); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); thread.Join(); return(result); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); SetIncidentId(); DefaultTokenCacheStore cache = new DefaultTokenCacheStore(this); authContext = new AuthenticationContext(this, Constants.AAD_AUTHORITY, false, cache); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.signIn_btn); button.Click += delegate { authContext.AcquireToken(this, Constants.SHAREPOINT_URL, Constants.AAD_CLIENT_ID, Constants.AAD_REDIRECT_URL, PromptBehavior.RefreshSession, new SignInCallback(this)); }; }
static void Main(string[] args) { AuthenticationContext authenticationContext = new AuthenticationContext(Authority); AuthenticationResult authenticationResult = authenticationContext.AcquireToken(ServiceResourceId, ClientId, RedirectUri, PromptBehavior.Always); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, ServiceAddress); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); HttpClient client = new HttpClient(); HttpResponseMessage response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { string content = response.Content.ReadAsStringAsync().Result; JArray result = JArray.Parse(content); foreach (JObject obj in result) { string type = obj["type"].ToString(); Console.Write(type); int padding = 72 - type.Length; for (int i = 0; i < padding; i++) { Console.Write(" "); } Console.WriteLine(obj["value"]); } } else { Console.WriteLine(response.StatusCode); } }
private async Task GetServices() { toolStripStatus.Text = "Getting Access Token..."; try { var discoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint), () => { AuthenticationResult result = authContext.AcquireToken(SettingsHelper.O365DiscoveryResourceId, SettingsHelper.ClientId, new Uri(SettingsHelper.RedirectUri)); return(result.AccessToken); }); var capabilities = await discoveryClient.DiscoverCapabilitiesAsync(); foreach (var item in capabilities) { int n = dgServicesList.Rows.Add(); dgServicesList.Rows[n].Cells[0].Value = item.Key; dgServicesList.Rows[n].Cells[1].Value = item.Value.ServiceResourceId; dgServicesList.Rows[n].Cells[2].Value = item.Value.ServiceEndpointUri; dgServicesList.Rows[n].Cells[3].Value = item.Value.ServiceApiVersion; } toolStripStatus.Text = "Ready"; } catch (Exception ex) { toolStripStatus.Text = ex.Message; } }
/// <summary> /// acquires a <see cref="TokenPair"/> from the authority via an interactive user logon /// prompt. /// </summary> /// <param name="targetUri"> /// The uniform resource indicator of the resource access tokens are being requested for. /// </param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="resource"> /// Identifier of the target resource that is the recipient of the requested token. /// </param> /// <param name="redirectUri"> /// Address to return to upon receiving a response from the authority. /// </param> /// <param name="queryParameters"> /// Optional: appended as-is to the query string in the HTTP authentication request to the /// authority. /// </param> /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns> public TokenPair AcquireToken(TargetUri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null) { Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null"); Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty"); Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty"); Debug.Assert(redirectUri != null, "The redirectUri parameter is null"); Debug.Assert(redirectUri.IsAbsoluteUri, "The redirectUri parameter is not an absolute Uri"); Trace.WriteLine("AzureAuthority::AcquireToken"); TokenPair tokens = null; queryParameters = queryParameters ?? String.Empty; try { Trace.WriteLine(String.Format(" authority host URL = '{0}'.", AuthorityHostUrl)); AuthenticationContext authCtx = new AuthenticationContext(AuthorityHostUrl, _adalTokenCache); AuthenticationResult authResult = authCtx.AcquireToken(resource, clientId, redirectUri, PromptBehavior.Always, UserIdentifier.AnyUser, queryParameters); tokens = new TokenPair(authResult); Trace.WriteLine(" token acquisition succeeded."); } catch (AdalException) { Trace.WriteLine(" token acquisition failed."); } return(tokens); }
public static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Client ready."); Console.WriteLine("Press any key to invoke the service"); Console.WriteLine("Press ESC to terminate"); ConsoleKeyInfo consoleKeyInfo; var authenticationContext = new AuthenticationContext("https://login.windows.net/SalesApplication.onmicrosoft.com"); do { consoleKeyInfo = Console.ReadKey(true); // get the access token AuthenticationResult authenticationResult = authenticationContext.AcquireToken( "https://SalesApplication.onmicrosoft.com/NancyDemoServer", "5461d04d-d248-47dd-8008-076458153331", "https://SalesApplication.onmicrosoft.com/nancyDemoNativeClient"); // invoke the Nancy API var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); HttpResponseMessage response = httpClient.GetAsync("http://localhost:9000/values").Result; // display the result if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; Console.WriteLine("==> Successfully invoked the service"); Console.WriteLine(result); } } while (consoleKeyInfo.Key != ConsoleKey.Escape); }
/// <summary> /// Authenticate. /// </summary> void Authenticate() { #if !PCL if (RootConfiguration == null) { RootConfiguration = (PowerBIConfiguration)ConfigurationManager.GetSection(typeof(PowerBIConfiguration).Name); } #endif if (AuthenticationContext == null) { var tokenCache = new TokenCache(); AuthenticationContext = new AuthenticationContext(Configuration.Authority, tokenCache); } //For PCL we need to use the ADAL 3.O alpha. Because this version isn't a release we use compilation //condition to not use it in the classic version (PCL version of the PowerBI.Api.Client is also a Pre-Release) //We use synchronous call (We be change in the next version of the library) #if !PCL var authResult = string.IsNullOrEmpty(AccessToken) ? AuthenticationContext.AcquireToken(Configuration.Resource, Configuration.Client, new UserCredential(Configuration.User, Configuration.Password)) : AuthenticationContext.AcquireTokenSilent(Configuration.Resource, Configuration.Client); AccessToken = authResult.AccessToken; #else var task = string.IsNullOrEmpty(AccessToken) ? AuthenticationContext.AcquireTokenAsync(Configuration.Resource, Configuration.Client, new UserCredential(Configuration.User, Configuration.Password)) : AuthenticationContext.AcquireTokenSilentAsync(Configuration.Resource, Configuration.Client); Task.WaitAll(task); AccessToken = task.Result.AccessToken; #endif }
public async Task <ActionResult> UserProfile() { string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; // Get a token for calling the Windows Azure Active Directory Graph AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId)); ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey); AuthenticationResult assertionCredential = authContext.AcquireToken(GraphUrl, credential); string authHeader = assertionCredential.CreateAuthorizationHeader(); string requestUrl = String.Format( CultureInfo.InvariantCulture, GraphUserUrl, HttpUtility.UrlEncode(tenantId), HttpUtility.UrlEncode(User.Identity.Name)); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.TryAddWithoutValidation("Authorization", authHeader); HttpResponseMessage response = await client.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); UserProfile profile = JsonConvert.DeserializeObject <UserProfile>(responseString); return(View(profile)); }
// This method taken from: http://msdn.microsoft.com/en-us/library/azure/dn790557.aspx private static string GetAuthorizationHeader() { AuthenticationResult result = null; var context = new AuthenticationContext("https://login.microsoftonline.com/" + TenantId); var thread = new Thread(() => { result = context.AcquireToken( "https://management.core.windows.net/", ClientId, RedirectUrl, PromptBehavior.Always); }); 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 string GetOAuthTokenFromAAD() { AuthenticationResult result = null; var authenticationContext = new AuthenticationContext(String.Format("{0}/{1}", ConfigurationManager.AppSettings["ADALServiceURL"], ConfigurationManager.AppSettings["TenantDomain"])); var thread = new Thread(() => { //Ask the logged in user to authenticate, so that this client app can get a token on his behalf result = authenticationContext.AcquireToken(String.Format("{0}/", ConfigurationManager.AppSettings["ARMBillingServiceURL"]), ConfigurationManager.AppSettings["ClientID"], new Uri(ConfigurationManager.AppSettings["ADALRedirectURL"]), PromptBehavior.Always); }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AquireTokenThread"; thread.Start(); thread.Join(); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return(result.AccessToken); }
private string AccessToken() { bool fireAgain = false; try { 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(this.OAuth2AuthorityUri, 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(); UserCredential user = new UserCredential(this.UserName, this.Password); token = authContext.AcquireToken(this.ResourceUri, this.ClientID, user).AccessToken.ToString(); ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "Toked Acquired", "", 0, ref fireAgain); } else { // Get the token in the cache token = authContext.AcquireTokenSilent(this.ResourceUri, this.ClientID).AccessToken; ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "Refresh Token Acquired", "", 0, ref fireAgain); } return(token); } catch (Exception e) { ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "Token Error:" + e.Message, "", 0, ref fireAgain); return(""); } }
public override void Run() { string authority = "https://login.windows.net/MOD878411.onmicrosoft.com"; string clientId = "dcd68e75-54d4-451c-9dfb-dbc43833ec1a"; Uri redirectUri = new Uri("http://localhost"); // string serverName = "outlook.office365.com"; string resource = "https://outlook.office365.com/"; AuthenticationResult authenticationResult = null; AuthenticationContext authenticationContext = new AuthenticationContext(authority, false); authenticationResult = authenticationContext.AcquireToken(resource, clientId, redirectUri); ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2007_SP1); exchangeService.Url = new Uri(resource + "ews/exchange.asmx"); exchangeService.TraceEnabled = true; exchangeService.TraceFlags = TraceFlags.All; exchangeService.Credentials = new OAuthCredentials(authenticationResult.AccessToken); UploadMIMEEmail(exchangeService); }
private string GetAuthorizationHeader() { AuthenticationResult result = null; var context = new AuthenticationContext(string.Format(loginpath, tenantId)); var thread = new Thread(() => { result = context.AcquireToken(apiEndpoint, clientId, new Uri(redirectUri)); }); 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); }
// Azure AD 認証 public static TokenCredentials AuthenticateUser(string tenantId, string appClientId, string appKey) { var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}"); var tokenAuthResult = authContext.AcquireToken("https://management.core.windows.net/", new ClientCredential(appClientId, appKey)); return(new TokenCredentials(tokenAuthResult.AccessToken)); }
private string GetToken() { string token = ""; try { // Attempt to acquire an OAuth access token for the given application configuration AuthenticationContext authContext = new AuthenticationContext(String.Format("{0}/{1}", ConfigurationManager.AppSettings["ida:AADInstance"], ConfigurationManager.AppSettings["ida:Domain"])); ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"], ConfigurationManager.AppSettings["ida:AppKey"]); AuthenticationResult result = authContext.AcquireToken(ConfigurationManager.AppSettings["ida:GraphResourceId"], credential); token = result.AccessToken; } catch (AuthenticationException ex) { LblError.Text = String.Format("Acquiring a token failed with the following error: {0}", ex.Message); if (ex.InnerException != null) { //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx //InnerException Message will contain the HTTP error status codes mentioned in the link above LblError.Text += String.Format("Error detail: {0}", ex.InnerException.Message); } } return(token); }
/// <summary> /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly. /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="clientId">The Azure AD Application Client ID</param> /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param> /// <param name="certificate"></param> /// <param name="environment"></param> /// <returns></returns> public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, X509Certificate2 certificate, AzureEnvironment environment = AzureEnvironment.Production) { var clientContext = new ClientContext(siteUrl); var authority = string.Format(CultureInfo.InvariantCulture, "https://login.windows.net/{0}/", tenant); if (environment == AzureEnvironment.PPE) { //windows-ppe.net authority = string.Format(CultureInfo.InvariantCulture, "https://login.windows-ppe.net/{0}/", tenant); } var authContext = new AuthenticationContext(authority); var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate); var host = new Uri(siteUrl); clientContext.ExecutingWebRequest += (sender, args) => { var ar = authContext.AcquireToken(host.Scheme + "://" + host.Host + "/", clientAssertionCertificate); args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken; }; return(clientContext); }
private static AuthenticationResult GetToken(string tenantId, string applicationId, string applicationSecret) { AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + tenantId); _token = authContext.AcquireToken("https://management.core.windows.net/", new ClientCredential(applicationId, applicationSecret)); return(_token); }
/// <summary> /// Returns a http authorization header containing the access token /// </summary> /// <returns></returns> string GetAuthorizationHeader() { AuthenticationResult authenticationResult = null; try { authenticationResult = _authenticationContext.AcquireToken(resourceAppIdUri, clientId, redirectUri); ClearCacheButton.IsEnabled = true; return(authenticationResult.CreateAuthorizationHeader()); } catch (ActiveDirectoryAuthenticationException ex) { string message = ex.Message; if (ex.InnerException != null) { message += "InnerException : " + ex.InnerException.Message; } MessageBox.Show(message); } return(null); }
public static string GetAuthorizationHeader() { AuthenticationResult result = null; var thread = new Thread(() => { try { var context = new AuthenticationContext(ConfigurationManager.AppSettings["ActiveDirectoryEndpoint"] + ConfigurationManager.AppSettings["ActiveDirectoryTenantId"]); result = context.AcquireToken( resource: ConfigurationManager.AppSettings["WindowsManagementUri"], clientId: ConfigurationManager.AppSettings["AdfClientId"], redirectUri: new Uri(ConfigurationManager.AppSettings["RedirectUri"]), promptBehavior: PromptBehavior.Always); } catch (Exception threadEx) { Console.WriteLine(threadEx.Message); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); thread.Join(); if (result != null) { return(result.AccessToken); } throw new InvalidOperationException("Failed to acquire token"); }
private IEnumerable <TfsClientCredentials> GetOAuthCredentials() { try { var usernameAndPassword = GetServiceIdentityUsernameAndPasswordFromConfig(); if (usernameAndPassword == null || string.IsNullOrEmpty(_config.TfsServerConfig.OAuthClientId) || string.IsNullOrEmpty(_config.TfsServerConfig.OAuthContext) || string.IsNullOrEmpty(_config.TfsServerConfig.OAuthResourceId)) { return(new List <TfsClientCredentials>()); } var userCredential = new UserCredential(usernameAndPassword.Item1, usernameAndPassword.Item2); var authContext = new AuthenticationContext(_config.TfsServerConfig.OAuthContext); var result = authContext.AcquireToken(_config.TfsServerConfig.OAuthResourceId, _config.TfsServerConfig.OAuthClientId, userCredential); var oauthToken = new OAuthTokenCredential(result.AccessToken); return(new List <TfsClientCredentials>() { new TfsClientCredentials(oauthToken) }); } catch (Exception ex) { Logger.WarnFormat("Error trying to generate OAuth Token for TFS connection\n{0}", ex); return(new List <TfsClientCredentials>()); } }
public string GetApplicationAccountToken(string resourceUrl) { AuthenticationResult result = null; string authority = string.Format("https://login.microsoftonline.com/{0}/oauth2/token/", ConfigurationManager.AppSettings["TenantId"]); var context = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["ClientSecret"]); var thread = new Thread(() => { result = context.AcquireToken(resourceUrl, credential); }); 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); }
private static string GetAuthorizationHeader() { AuthenticationResult result = null; var context = new AuthenticationContext(String.Format("https://login.windows.net/{0}", tenantId)); var thread = new Thread(() => { result = context.AcquireToken( "https://management.core.windows.net/", clientId, new Uri(redirectUri)); }); 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); }
private static string GetToken() { // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612 // and add using Microsoft.IdentityModel.Clients.ActiveDirectory //The client id that Azure AD created when you registered your client app. string clientID = "b0616183-7f43-4b5a-aab0-b9b68184894d"; //RedirectUri you used when you register your app. //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate. // You can use this redirect uri for your client app string redirectUri = "https://login.live.com/oauth20_desktop.srf"; //Resource Uri for Power BI API string resourceUri = "https://analysis.windows.net/powerbi/api"; //OAuth2 authority Uri string authorityUri = "https://login.microsoftonline.com/common/"; //Get access token: // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken // AuthenticationContext is part of the Active Directory Authentication Library NuGet package // To install the Active Directory Authentication Library NuGet package in Visual Studio, // run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console. // AcquireToken will acquire an Azure access token // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint AuthenticationContext authContext = new AuthenticationContext(authorityUri); string token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken; Console.WriteLine(token); Console.ReadLine(); return(token); }
private void GetTokenButton_Click(object sender, RoutedEventArgs e) { var context = new AuthenticationContext(Constants.ACS.IssuerUri); var credential = context.AcquireToken(Constants.Realm); if (credential != null) { if (!string.IsNullOrWhiteSpace(credential.Assertion)) { _token = credential.Assertion; OutputTextBox.Text = _token; } } }
/// <summary> /// Used to get the HTTP authorization header /// </summary> /// <returns>Returned a string value containing the auth text value</returns> private string GetAuthorizationHeader() { string authzHeader = null; try { var context = new AuthenticationContext(Properties.FullTenantAddress); var credential = new SymmetricKeyCredential(Properties.IssuingResource, Convert.FromBase64String(Properties.SymmetricKey)); var token = context.AcquireToken(Properties.ServiceRealm, credential); authzHeader = token.CreateAuthorizationHeader(); } catch (Exception ex) { var aex = ex as AALException; throw new ApplicationException(aex.Message); } return authzHeader; }
/// <summary> /// Get the token for authenticating requests to Azure Resource Manager in customer tenant. /// </summary> /// <param name="appId">appid that is registered for this application in Azure Active Directory (AAD)</param> /// <param name="key">This is the key for this application in Azure Active Directory</param> /// <param name="customerTenantId">cid of the customer</param> /// <returns>Azure Auth Token in the context of the customer tenant.</returns> private static AuthenticationResult GetAzureAuthTokenForCustomerTenant(string appId, string credentialName, string customerTenantId) { AuthenticationResult authResult = null; string resource = "https://management.core.windows.net/"; var authenticationContext = new AuthenticationContext("https://login.windows.net/" + customerTenantId); try { authResult = authenticationContext.AcquireTokenSilent(resource: resource, clientId: appId); } catch (AdalException aex) { if (aex.ErrorCode == "failed_to_acquire_token_silently") { UserCredential uc = CredentialManager.GetCredential(credentialName); authResult = authenticationContext.AcquireToken(resource: resource, clientId: appId, userCredential: uc); } } catch (Exception ex) { throw; } return authResult; }