public static AuthenticationResult GetToken(string serviceName) { var ctx = new AuthenticationContext(IdentitySettings.IssuerAddress, new NativeTokenCache()); var resource = Resource(serviceName); var appClientId = RuntimeFactory.Current.Context.GetServiceConfiguration().GetConfigParameter("OauthClientId"); var appClientSecret = RuntimeFactory.Current.Context.GetServiceConfiguration().GetSecureConfigParameter("OauthClientSecret"); try { AuthenticationResult token; var userToken = GetUserToken(); var userId = GetUserObjectId(); var clientCredential = new ClientCredential(appClientId, appClientSecret); if (userToken.ContainsCharacters()) { try { token = ctx.AcquireToken(resource, clientCredential, new UserAssertion(userToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", RuntimeFactory.Current.GetCurrentClaimsIdentity().Name)); } catch (Exception) { token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion()); } } else if (userId.ContainsCharacters()) token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion()); else { if (ConfigurationManagerHelper.GetValueOnKey("stardust.promptUserFOrCredentials", false)) token = ctx.AcquireToken(resource, appClientId, new Uri("http://" + Utilities.GetEnvironment() + "ters.dnvgl.com"), PromptBehavior.Auto); else token = ctx.AcquireToken(resource, clientCredential); } return token; } catch (AdalSilentTokenAcquisitionException adalex) { if (adalex.ErrorCode == AdalError.FailedToAcquireTokenSilently) { HttpContext.Current.GetOwinContext().Authentication.SignOut(); HttpContext.Current.GetOwinContext().Authentication.Challenge(); throw; } throw; } catch (System.Exception ex) { ex.Log(); throw; } }
static async Task MainAsync(string[] args) { var keyClient = new KeyVaultClient((authority, resource, scope) => { var adCredential = new ClientCredential(applicationId, applicationSecret); var authenticationContext = new AuthenticationContext(authority, null); return authenticationContext.AcquireToken(resource, adCredential).AccessToken; }); // Get the key details var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784"; var key = await keyClient.GetKeyAsync(keyIdentifier); var publicKey = Convert.ToBase64String(key.Key.N); using (var rsa = new RSACryptoServiceProvider()) { var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E }; rsa.ImportParameters(p); var byteData = Encoding.Unicode.GetBytes(textToEncrypt); // Encrypt and Decrypt var encryptedText = rsa.Encrypt(byteData, true); var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText); var decryptedText = Encoding.Unicode.GetString(decryptedData.Result); // Sign and Verify var hasher = new SHA256CryptoServiceProvider(); var digest = hasher.ComputeHash(byteData); var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest); var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result); } }
public static AuthenticationResult GetInteractiveLogin(String Username = null, String authority = "common") { var ctx = new AuthenticationContext(string.Format(Constants.loginAuthority + authority, Constants.tenant)); if (!String.IsNullOrWhiteSpace(Username)) { UserIdentifier user = new UserIdentifier(Username, UserIdentifierType.RequiredDisplayableId); return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Always, user); } else return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Always); }
public static AuthenticationResult RefreshTokenByAuthority(String authority) { var ctx = new AuthenticationContext(string.Format(Constants.loginAuthority + authority, Constants.tenant)); // Refresh the token for the logged in user only. UserIdentifier userName = new UserIdentifier(Properties.Settings.Default["ADUserName"].ToString(), UserIdentifierType.OptionalDisplayableId); try { return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Never, userName); } catch { return ctx.AcquireToken(Constants.appIdURI, Constants.clientID, new Uri(Constants.redirectURI), PromptBehavior.Auto, userName); } }
public string GetAccessTokenUsingServiceAccount(Item azureSetting) { string tenantId; string clientId; string url; SetAzureAuthAppInformation(azureSetting, out tenantId, out clientId, out url); if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(url)) { return string.Empty; } var authenticationContext = new AuthenticationContext("https://login.windows.net/" + tenantId); //get the service account user name and password from the settings node string userName = azureSetting["Service Account User Name"]; string password = azureSetting["Service Account Password"]; //Create a user credential object using the specified service account user name and password var credential = new UserCredential(userName, password); //Issue a request to obtain the access token var result = authenticationContext.AcquireToken("https://management.core.windows.net/", clientId, credential); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } //Set the access token to be returned string token = result.AccessToken; return token; }
private static string GetAuthorizationHeader() { AuthenticationResult result = null; var context = new AuthenticationContext("https://login.chinacloudapi.cn/82a8b6cc-3dcc-4661-8efb-d4e3ff10d28e"); var thread = new Thread(() => { result = context.AcquireToken( "https://management.core.chinacloudapi.cn/", "6f173395-839b-4139-a41d-6a566cf847a9", new Uri("http://localhost/11")); }); 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 GetAuthorizationHeader() { // string _aadTenantDomain = "cciccat.partner.onmschina.cn"; _aadTenantDomain = ConfigurationSettings.AppSettings["_aadTenantDomain"]; //_aadTenantDomain = "cciccat.com"; string _aadClientId = "9adbfe5e-2252-4d26-a3ad-68bbd1e25963"; _aadClientId = ConfigurationSettings.AppSettings["_aadClientId"]; AuthenticationResult result = null; var context = new AuthenticationContext("https://login.chinacloudapi.cn/" + _aadTenantDomain); // Directly specify the username and password. var credential = new UserCredential( ConfigurationSettings.AppSettings["CoAdminUser"], ConfigurationSettings.AppSettings["CoAdminPassword"]); result = context.AcquireToken( "https://management.core.chinacloudapi.cn/", _aadClientId, credential); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } string token = result.AccessToken; return token; }
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(); }
static void Main(string[] args) { var redirectUri = new Uri("http://AzureADOpenIdWebApiNativeClient"); var authContext = new AuthenticationContext(authority); var authResult = authContext.AcquireToken(apiResourceId, clientId, redirectUri); var client = new HttpClient(); string responseString = ""; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); Task.Run(async () => { HttpResponseMessage response = await client.GetAsync(apiBaseAddress + "api/me"); responseString = await response.Content.ReadAsStringAsync(); }).Wait(); Console.WriteLine("Message:" + responseString); Console.ReadLine(); }
static string GetAuthorizationHeader(string tenant, string clientId, string redirectUri) { AuthenticationResult result = null; var context = new AuthenticationContext( string.Format("https://login.windows.net/{0}", tenant) ); var thread = new Thread(() => { result = context.AcquireToken( clientId: clientId, redirectUri: new Uri(redirectUri), resource: "https://management.core.windows.net/", promptBehavior:PromptBehavior.Auto ); }); thread.SetApartmentState((ApartmentState.STA)); thread.Name = "AcquireTokenThread"; thread.Start(); thread.Join(); return result.CreateAuthorizationHeader().Substring("Bearer ".Length); }
/// <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; }
/// <summary> /// Returns token (requires user input) /// </summary> /// <returns></returns> public static string GetToken(string authEndpoint, string tenant, string clientId) { 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.CreateAuthorizationHeader().Substring("Bearer ".Length); }
public string GetApplicationAccountToken(string resourceUrl) { AuthenticationResult result = null; var authority = string.Format("https://login.microsoftonline.com/{0}/oauth2/token/", ConfigurationManager.AppSettings["TenantId"]); var context = new AuthenticationContext(authority); var 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"); } var token = result.AccessToken; return token; }
public string GetAToken() { try { //https://login.chinacloudapi.cn/ed0caab7-c6d4-45e9-9289-c7e5997c9241/oauth2/authorize //subscription id = ed0caab7-c6d4-45e9-9289-c7e5997c9241 //https://graph.windows.net/e4162ad0-e9e3-4a16-bf40-0d8a906a06d4 //ClientCredential AuthenticationContext authenticationContext = new AuthenticationContext("https://login.windows.net/e4162ad0-e9e3-4a16-bf40-0d8a906a06d4"); AuthenticationResult result = null; var thread = new Thread(() => { result = authenticationContext.AcquireToken( resource: "https://management.core.windows.net/", clientId: "06bbd520-87fb-4550-9b94-f6b68a858452", redirectUri: new Uri("https://localhost:44300/")); }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AquireTokenThread"; thread.Start(); thread.Join(); string token = result.AccessToken; return token; } catch (Exception e) { //throw; return null; } }
private async void btnCallDirect_Click(object sender, EventArgs e) { try { authContext = new AuthenticationContext(authority); AuthenticationResult authResult = authContext.AcquireToken(apiResourceId, clientId, redirectUri); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); HttpResponseMessage response = await client.GetAsync(apiBaseAddress + "api/add?a=100&b=100"); response.EnsureSuccessStatusCode(); string responseString = await response.Content.ReadAsStringAsync(); MessageBox.Show(responseString); } catch (HttpRequestException ex) { MessageBox.Show(ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private async void button_Click(object sender, RoutedEventArgs e) { var authContext = new AuthenticationContext("https://login.windows.net/microsoft.com"); AuthenticationResult result = null; try { result = authContext.AcquireToken("http://anandmsraazuretest.azurewebsites.net/", "ba1166f6-1dba-4794-8e7b-1e326c63085e", new Uri("https://MSRA"), PromptBehavior.Auto); //// A valid token is in the cache - get the To Do list. HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await httpClient.GetAsync("http://anandmsraazuretest.azurewebsites.net/odata/MSRAQuery"); } catch (AdalException ex) { if (ex.ErrorCode == "user_interaction_required") { // There are no tokens in the cache. Proceed without calling the To Do list service. } else { // An unexpected error occurred. string message = ex.Message; if (ex.InnerException != null) { message += "Inner Exception : " + ex.InnerException.Message; } MessageBox.Show(message); } return; } }
//Get access token: // To call a Data Catalog 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. static AuthenticationResult AccessToken() { if (authResult == null) { //Resource Uri for Data Catalog API string resourceUri = "https://datacatalog.azure.com"; //To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID string clientId = clientIDFromAzureAppRegistration; //A redirect uri gives AAD more details about the specific application that it will authenticate. //Since a client app does not have an external service to redirect to, this Uri is the standard placeholder for a client app. string redirectUri = "https://login.live.com/oauth20_desktop.srf"; // Create an instance of AuthenticationContext to acquire an Azure access token // OAuth2 authority Uri string authorityUri = "https://login.windows.net/common/oauth2/authorize"; AuthenticationContext authContext = new AuthenticationContext(authorityUri); // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint // AcquireToken takes a Client Id that Azure AD creates when you register your client app. authResult = authContext.AcquireToken(resourceUri, clientId, new Uri(redirectUri), PromptBehavior.RefreshSession); } return authResult; }
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 = "SharePointConfessions.onMicrosoft.com"; Uri uriAzureGraphApiResource = new Uri(urlAzureGraphApi + tenantDomain); // string clientID = "128d1e44-5e55-4027-96e6-bc36e5b10a0a"; 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.RefreshSession); // cache access token in AccessToken field AccessToken = userAuthnResult.AccessToken; }
/// <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(Uri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null) { Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid"); 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; }
private static string GetAuthorizationHeader(string tenantId, string authUrlHost, string clientId) { AuthenticationResult result = null; var thread = new Thread(() => { try { var authUrl = String.Format(authUrlHost + "/{0}", tenantId); var context = new AuthenticationContext(authUrl); result = context.AcquireToken( resource: "https://management.core.windows.net/", clientId: clientId, redirectUri: new Uri("{Your application URI}"), // replace with your application URI promptBehavior: PromptBehavior.Auto); } catch (Exception threadEx) { Console.WriteLine(threadEx.Message); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); thread.Join(); return result.CreateAuthorizationHeader(); }
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); } }
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> /// 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; } }
private static string GetAuthorizationHeader() { AuthenticationResult result = null; var url1 = "https://login.windows.net/"; // or "https://login.chinacloudapi.cn" for China var url2 = "https://management.core.windows.net/"; // or "https://management.core.chinacloudapi.cn/" for China var context = new AuthenticationContext(new Uri(new Uri(url1), tenantId).AbsoluteUri); var thread = new Thread(() => { result = context.AcquireToken( url2, "1950a258-227b-4e31-a9cf-717495945fc2", // clientId new Uri("urn:ietf:wg:oauth:2.0:oob")); }); 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 void Button_Click(object sender, RoutedEventArgs e) { string result = string.Empty; // Get token AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/SalesApplication.onmicrosoft.com");//the 'App ID URI' of the secured resource/API trying to access as configured in AAD AuthenticationResult ar = ac.AcquireToken("https://SalesApplication.onmicrosoft.com/WebAPIDemo", //the "name" of the secured resource/API trying to access as configured in AAD ('App ID URI') "5685ff14-3fb8-4785-a78e-6f81219b39f8",// the 'client ID' for this client application as configured in AAD new Uri("https://SalesApplication.onmicrosoft.com/myWebAPInativeclient"));// the redirect URI for this client application as configured in AAD // http://goo.gl/Ypb6yv // the following generates a security exception since we don't have a valid certificate ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation); // Call Web API HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ar.AccessToken); HttpResponseMessage response = httpClient.GetAsync("https://localhost:44304/api/Values").Result; // display the result if (response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; MessageBox.Show(result); } else { result = response.Content.ReadAsStringAsync().Result; MessageBox.Show(result, response.StatusCode.ToString(), MessageBoxButton.OK, MessageBoxImage.Error); } }
public static async Task<string> GetAsStringOnBehalfOfScriptUser(this HttpClient client, string url, string clientId, string appKey, string aadInstance, string graphResourceId) { string accessToken = HttpContext.Current.Request.Headers["Authorization"].Replace("Bearer", "").Trim(); var cacheSession = HttpContext.Current.Session?["cache"] as byte[]; TokenCache tokenCache = cacheSession != null ? new TokenCache(cacheSession) : new TokenCache(); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common"); var authContext = new AuthenticationContext(authority, tokenCache); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, to return an error immediately to the user and have the user initiate the retry. bool retry; var retryCount = 0; do { retry = false; try { AuthenticationResult result = authContext.AcquireToken( graphResourceId, new ClientCredential( clientId, appKey ), new UserAssertion( accessToken ) ); accessToken = result.AccessToken; } catch ( AdalException ex ) { if ( ex.ErrorCode == "temporarily_unavailable" ) { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep( 1000 ); } } catch ( Exception ex ) { Debug.Print( ex.ToString() ); throw; } } while (retry && (retryCount < 1)); if (accessToken == null) { return (null); } var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); HttpContext.Current.Session["cache"] = tokenCache.Serialize(); return (responseString); } // An unexpected error occurred calling the Graph API. Return a null profile. return await (response.Content.ReadAsStringAsync()); }
public static async Task<string> AcquireTokenAsApp() { ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey); string tenantId = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value; AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId)); AuthenticationResult result = authContext.AcquireToken(ConfigHelper.GraphResourceId, cred); return result.AccessToken; }
private string HandleKeyVaultAuthenticationCallback(string authority, string resource, string scope) { var adCredential = new ClientCredential( this.keyVaultConfiguration.ADApplicationClientId, this.keyVaultConfiguration.ADApplicationSecret); var authenticationContext = new AuthenticationContext(authority, null); return authenticationContext.AcquireToken(resource, adCredential).AccessToken; }
private static string GetBearerToken() { var authContext = new AuthenticationContext(string.Format(GetAuthority(), GetTenantId())); var apiResourceId = Utilities.GetConfigLocation(); var authResult = authContext.AcquireToken(apiResourceId, new ClientCredential(ConfigurationManagerHelper.GetValueOnKey("stardust.configUser"), ConfigurationManagerHelper.GetValueOnKey("stardust.configPassword"))); var bearerToken = authResult.CreateAuthorizationHeader(); return bearerToken; }
// GET: Location public async Task <ActionResult> Index() { AuthenticationResult result = null; int retryCount = 0; bool retry = false; do { retry = false; 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) { ViewBag.ErrorMessage = "UnexpectedError"; return(View("Index")); } HttpClient httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serviceBaseAddress + "api/location?cityName=dc"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string r = await response.Content.ReadAsStringAsync(); ViewBag.Results = r; return(View("Index")); } else { string r = await response.Content.ReadAsStringAsync(); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { authContext.TokenCache.Clear(); } ViewBag.ErrorMessage = "AuthorizationRequired"; return(View("Index")); } }
internal static string GetSharePointAccessToken(string url, string accessToken) { string clientID = ConfigurationManager.AppSettings["ClientID"]; string clientSecret = ConfigurationManager.AppSettings["ClientSecret"]; var appCred = new ClientCredential(clientID, clientSecret); var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common"); AuthenticationResult authResult = authContext.AcquireToken(new Uri(url).GetLeftPart(UriPartial.Authority), appCred, new UserAssertion(accessToken)); return(authResult.AccessToken); }
private static void LoginWithUsernamePassword(AuthenticationHeaderValue credentials, HttpApplication context) { var cred = EncodingFactory.ReadFileText(Convert.FromBase64String(credentials.Parameter)); var separator = cred.IndexOf(':'); var name = cred.Substring(0, separator); var password = cred.Substring(separator + 1); var ctx = new AuthenticationContext(RuntimeFactory.Current.Context.GetServiceConfiguration().IdentitySettings.IssuerAddress); var token = ctx.AcquireToken(Resource, RuntimeFactory.Current.Context.GetConfigParameter("ServiceAccountName"), new UserCredential(name, password)); var accessToken = token.AccessToken; ValidateToken(accessToken, context); }
/// <summary> /// WEBAPP and WEBAPI are in a different AAD APP /// Use this method if this app is protected by ADD-Application: CalcEnterpriseClient /// Authenticate to the API by using a service principal aka AAD App (with Delegate Permissions to /// CalcEnterpriseAPI) /// </summary> /// <returns></returns> public ActionResult Index() { string _ClientID = "<CalcEnterpriseClient AAD CLientID>"; // CalcEnterpriseClient - Client ID string _ClientSecret = "<CalcEnterpriseClient AAD App Secret/Key>"; // CalcEnterpriseClient - Client Secret string _Ressource = "<CalcEnterpriseAPI AAD CLientID>"; // CalcEnterpriseAPI - Client ID to be used if we call from middle tier! /* * https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-service-principal-auth/ * ida:ClientId and ida:Resource are different values for this tutorial because you're using separate Azure AD * applications for the middle tier and data tier. If you were using a single Azure AD application for the calling * API app and the protected API app, you would use the same value in both ida:ClientId and ida:Resource */ string _Authority = "https://login.microsoftonline.com/<yourTenantName>.onmicrosoft.com"; SessionTalk[] contacts = null; var clientCredential = new ClientCredential(_ClientID, _ClientSecret); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(_Authority, false); AuthenticationResult authenticationResult = context.AcquireToken( _Ressource, clientCredential); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(C_BASE_SERVICE_URI); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", C_CALC_API_SUBSCRIPTION_KEY); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authenticationResult.AccessTokenType, authenticationResult.AccessToken); string path = C_SERVICE_PATH; try { var json = client.GetStringAsync(path).Result; contacts = JsonConvert.DeserializeObject <SessionTalk[]>(json); } catch (Exception ed) { contacts = new SessionTalk[] { new SessionTalk() { Title = ed.ToString() } }; } } return(View(contacts)); }
public ActionResult AppOnlyAccessToken() { string urlTokenEndpointForTenant = string.Format("https://login.windows.net/{0}/oauth2/token", CustomAuthenticationManager.GetTenantID()); ADAL.AuthenticationContext authenticationContext = new ADAL.AuthenticationContext(urlTokenEndpointForTenant); string resource = DemoConstants.TargetResource; ADAL.ClientAssertionCertificate clientAssertionCertificate = DemoConstants.GetClientAssertionCertificate(); ADAL.AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientAssertionCertificate); string appOnlyAccessToken = authenticationResult.AccessToken; JwtSecurityToken jwtAppOnlyAccessToken = new JwtSecurityToken(appOnlyAccessToken); return(View(jwtAppOnlyAccessToken)); }
static void Main(string[] args) { ClientCredential clientCreds = new ClientCredential("73b9497a-9afb-4ad8-b0d8-fe7786c620d8", "BxAnEHi7r1yeUYaSxkm4YqJq+ZSyxmWhaFxeYJKPEfQ="); UserAssertion userAssertion = new UserAssertion("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL2dyYXBoLndpbmRvd3MubmV0IiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvNzdkMzA5NjMtNzg3Mi00ZDExLTkzNzQtMmMyYjJhMTJhZDY1LyIsImlhdCI6MTQ1MjczODgzMSwibmJmIjoxNDUyNzM4ODMxLCJleHAiOjE0NTI3NDI3MzEsImFjciI6IjEiLCJhbXIiOlsicHdkIl0sImFwcGlkIjoiNzNiOTQ5N2EtOWFmYi00YWQ4LWIwZDgtZmU3Nzg2YzYyMGQ4IiwiYXBwaWRhY3IiOiIxIiwiZmFtaWx5X25hbWUiOiJQb3J0ZXIiLCJnaXZlbl9uYW1lIjoiUm9zcyIsImlwYWRkciI6Ijc1LjEyOS4xNzkuMTEiLCJuYW1lIjoiUG9ydGVyLCBSb3NzIiwib2lkIjoiY2UzMDIzNmUtZWRhNC00N2FmLTk1NjgtMzFhOWRhZmZkNGZlIiwib25wcmVtX3NpZCI6IlMtMS01LTIxLTY5NzM3OTE5LTE2ODk1OTIzMjMtMTQxNTcxMzcyMi02MzIyIiwicHVpZCI6IjEwMDMzRkZGODVDREYxQTMiLCJzY3AiOiJGaWxlcy5SZWFkV3JpdGUgRmlsZXMuUmVhZFdyaXRlLkFwcEZvbGRlciBGaWxlcy5SZWFkV3JpdGUuU2VsZWN0ZWQgUGVvcGxlLlJlYWQgVXNlci5SZWFkIiwic3ViIjoiWE5RcFRPdE1TN0J6a05lMHhVSXhJd1VNcDhPR2FJVUdnRW1QUTV6MzZzNCIsInRpZCI6Ijc3ZDMwOTYzLTc4NzItNGQxMS05Mzc0LTJjMmIyYTEyYWQ2NSIsInVuaXF1ZV9uYW1lIjoici5wb3J0ZXJAdGVjaHNtaXRoLmNvbSIsInVwbiI6InIucG9ydGVyQHRlY2hzbWl0aC5jb20iLCJ2ZXIiOiIxLjAifQ.TwYHsRCsk1BMszGQ4tKNFXQGviEJ9o0070aKlXaQEYnp56coZcQp-hF6kJrzw_pSOBC4G6umzflTrH8NwkcEKdlvkGsHDc2LXu4pzU_4ndoUaPrn4LiNFf5taH-zWlPfGbgc64ok5-GB_XWWfk2EYnLBcI9-tu4qjM3MR-z5zI6aK3hWYSgqtFt7PeOYwrPfmwTFI5jdm9wTRYCnoBHSw3nFpWz_aBtlXlKTHR0EAF4-osqEu2rCk2G3siwdhZVBCIGZEVlsoQg1tmybU14f5EVf8ljVtCkGTC7okstyIkTNrp7TL6H7SlbtKzEcpvas2b310Z5uqazkYLNd-A-87g"); adalAuthContext context = new adalAuthContext("https://login.windows.net/common/"); Uri redirectUri = new Uri("http://client-connector/terminate"); try { var authResults = context.AcquireToken("https://api.office.com/discovery/", clientCreds, userAssertion); using (var webClient = new WebClient()) { webClient.Headers[HttpRequestHeader.Authorization] = authResults.CreateAuthorizationHeader(); try { var jsonData = webClient.DownloadString(discoveryApi); System.IO.File.WriteAllText("../../output.json", jsonData); var results = JObject.Parse(jsonData); } catch (WebException wex) { var response = wex.Response; Console.WriteLine(wex.ToString()); } } } catch (Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException adalErr) { var error = adalErr.ErrorCode; Console.WriteLine(adalErr.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); }
public static async Task <string> GetAsStringOnBehalfOfScriptUser(this HttpClient client, string url, string clientId, string appKey, string aadInstance, string graphResourceId) { string accessToken = HttpContext.Current.Request.Headers["Authorization"].Replace("Bearer", "").Trim(); var cacheSession = HttpContext.Current.Session?["cache"] as byte[]; TokenCache tokenCache = cacheSession != null ? new TokenCache(cacheSession) : new TokenCache(); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common"); var authContext = new AuthenticationContext(authority, tokenCache); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, to return an error immediately to the user and have the user initiate the retry. bool retry; var retryCount = 0; do { retry = false; try { AuthenticationResult result = authContext.AcquireToken( graphResourceId, new ClientCredential(clientId, appKey), new UserAssertion(accessToken)); accessToken = result.AccessToken; } catch (AdalException ex) { if (ex.ErrorCode == "temporarily_unavailable") { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } catch (Exception ex) { Debug.Print(ex.ToString()); throw; } } while (retry && (retryCount < 1)); if (accessToken == null) { return(null); } var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); HttpContext.Current.Session["cache"] = tokenCache.Serialize(); return(responseString); } // An unexpected error occurred calling the Graph API. Return a null profile. return(await(response.Content.ReadAsStringAsync())); }
public void GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery() { // // The Client ID is used by the application to uniquely identify itself to Azure AD. // The App Key is a credential used by the application to authenticate to Azure AD. // The Tenant is the name of the Azure AD tenant in which this application is registered. // The AAD Instance is the instance of Azure, for example public Azure or Azure China. // The Authority is the sign-in URL of the tenant. // string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; string appKey = ConfigurationManager.AppSettings["ida:AppKey"]; string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); // // To authenticate to the To Do list service, the client needs to know the service's App ID URI. // To contact the To Do list service we need it's URL as well. // string appResourceId = ConfigurationManager.AppSettings["app:AppResourceId"]; IContentKey contentKey = null; IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null; IContentKeyAuthorizationPolicyOption policyOption = null; var authContext = new AuthenticationContext(authority); var clientCredential = new ClientCredential(clientId, appKey); try { byte[] expectedKey = null; contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey, "GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery" + Guid.NewGuid().ToString()); TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenRestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration"); var result = authContext.AcquireToken(appResourceId, clientCredential); string jwtTokenString = result.AccessToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); Assert.IsTrue(handler.CanReadToken(jwtTokenString)); JwtSecurityToken token = handler.ReadToken(jwtTokenString) as JwtSecurityToken; Assert.IsNotNull(token); tokenRestrictionTemplate.Audience = token.Audiences.First(); tokenRestrictionTemplate.Issuer = token.Issuer; string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication"; string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate); policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted); List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption> { policyOption }; contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey); Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); Assert.IsNotNull(keyDeliveryServiceUri); // Enable once all accounts are enabled for per customer Key Delivery Urls //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId)); KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed); byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString); string expectedString = GetString(expectedKey); string fetchedString = GetString(key); Assert.AreEqual(expectedString, fetchedString); } finally { CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption); } }