/// <summary> /// Acquires an access token from the authority on behalf of a user. It requires using a user token previously received. /// </summary> /// <param name="ctx">Authentication context instance</param> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientAssertion">The client assertion to use for token acquisition.</param> /// <param name="userAssertion">The user assertion (token) to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time.</returns> public static async Task <AuthenticationResult> AcquireTokenAsync(this AuthenticationContext ctx, string resource, ClientAssertion clientAssertion, UserAssertion userAssertion) { return(await ctx.AcquireTokenOnBehalfCommonAsync(resource, new ClientKey(clientAssertion), userAssertion) .ConfigureAwait(false)); }
/// <summary> /// Get the access token /// </summary> /// <param name="clientId">Client ID of the Web API app</param> /// <param name="appKey">Client secret for the Web API app</param> /// <param name="aadInstance">The login URL for AAD</param> /// <param name="tenant">Your tenant (eg kirke.onmicrosoft.com)</param> /// <param name="resource">The resource being accessed ///(eg., https://rbinrais.sharepoint.com) /// </param> /// <returns>string containing the access token</returns> public static async Task<string> GetAccessToken( string clientId, string appKey, string aadInstance, string tenant, string resource) { string accessToken = null; AuthenticationResult result = null; ClientCredential clientCred = new ClientCredential(clientId, appKey); string authHeader = HttpContext.Current.Request.Headers["Authorization"]; string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim(); UserAssertion userAssertion = new UserAssertion(userAccessToken); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); AuthenticationContext authContext = new AuthenticationContext(authority); result = await authContext.AcquireTokenAsync(resource, clientCred, userAssertion); accessToken = result.AccessToken; return accessToken; }
private static string GetAccessToken(string resourceId) { string accessToken = null; // // Use ADAL to get a token On Behalf Of the current user. To do this we will need: // The Resource ID of the service we want to call. // The current user's access token, from the current request's authorization header. // The credentials of this application. // The username (UPN or email) of the user calling the API // ClientCredential clientCred = new ClientCredential(clientId, appKey); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value; string userAccessToken = bootstrapContext.Token; UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(authority, new DbTokenCache(userId)); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { AuthenticationResult result = authContext.AcquireToken(resourceId, clientCred, userAssertion); accessToken = result.AccessToken; //AuthenticationResult result = authContext.AcquireToken(sqlAzureResourceId, clientCred, userAssertion); ////result = authContext.AcquireToken(graphResourceId, clientCred, userAssertion); //accessToken = result.AccessToken; //AuthenticationResult result1 = authContext.AcquireToken(armResourceId, clientCred, userAssertion); //AuthenticationResult result2 = authContext.AcquireTokenByRefreshToken(result1.RefreshToken, clientCred, sqlAzureResourceId); //accessToken = result2.AccessToken; } catch (AdalException ex) { if (ex.ErrorCode == "temporarily_unavailable") { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } } while ((retry == true) && (retryCount < 1)); return accessToken; }
public AcquireTokenOnBehalfHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserAssertion userAssertion) : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.UserPlusClient) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; this.SupportADFS = true; }
public AcquireTokenOnBehalfHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserAssertion userAssertion, bool callSync) : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.UserPlusClient, callSync) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; this.SupportADFS = true; }
public AcquireTokenNonInteractiveHandler(RequestData requestData, UserAssertion userAssertion) : base(requestData) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } if (string.IsNullOrWhiteSpace(userAssertion.AssertionType)) { throw new ArgumentException(AdalErrorMessage.UserCredentialAssertionTypeEmpty, "userAssertion"); } this.userAssertion = userAssertion; }
public AcquireTokenOnBehalfHandler(RequestData requestData, UserAssertion userAssertion) : base(requestData) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; CacheQueryData.AssertionHash = PlatformPlugin.CryptographyHelper.CreateSha256Hash(userAssertion.Assertion); this.SupportADFS = true; }
public AcquireTokenOnBehalfHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserAssertion userAssertion, bool callSync) : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.UserPlusClient, callSync) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; this.assertionHash = PlatformSpecificHelper.CreateSha256Hash(userAssertion.Assertion); this.SupportADFS = true; }
public AcquireTokenOnBehalfHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, UserAssertion userAssertion) : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.UserPlusClient) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; CacheQueryData.AssertionHash = PlatformPlugin.CryptographyHelper.CreateSha256Hash(userAssertion.Assertion); this.SupportADFS = true; }
public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, UserAssertion userAssertion, bool callSync) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User, callSync) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } if (string.IsNullOrWhiteSpace(userAssertion.AssertionType)) { throw new ArgumentException(AdalErrorMessage.UserCredentialAssertionTypeEmpty, "userAssertion"); } this.userAssertion = userAssertion; }
internal async Task <AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserAssertion userAssertion) { RequestData requestData = new RequestData { Authenticator = this.Authenticator, TokenCache = this.TokenCache, Resource = resource, ClientKey = new ClientKey(clientId), ExtendedLifeTimeEnabled = this.ExtendedLifeTimeEnabled, }; var handler = new AcquireTokenNonInteractiveHandler(requestData, userAssertion); return(await handler.RunAsync().ConfigureAwait(false)); }
public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, UserAssertion userAssertion) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } if (string.IsNullOrWhiteSpace(userAssertion.AssertionType)) { throw new ArgumentException(AdalErrorMessage.UserCredentialAssertionTypeEmpty, "userAssertion"); } this.userAssertion = userAssertion; }
public AcquireTokenOnBehalfHandler(RequestData requestData, UserAssertion userAssertion) : base(requestData) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; CacheQueryData.AssertionHash = CryptographyHelper.CreateSha256Hash(userAssertion.Assertion); CallState.Logger.Verbose(CallState, string.Format(CultureInfo.InvariantCulture, "Username provided in user assertion - " + string.IsNullOrEmpty(this.DisplayableId))); this.SupportADFS = true; }
// GET api/GetToken // This routine creates AzureAd token, another routine creates jwtBearer depending on which works with dual auth with cookies public async Task <HttpResponseMessage> Get() { // OWIN middleware validated the audience and issuer, but the scope must also be validated; must contain "access_as_user". string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' '); if (addinScopes.Contains("access_as_user")) { var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext; Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion userAssertion = new Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion(bootstrapContext.Token); authContextADAL = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, new FileCache()); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientIdAddin, PasswordAddin); result = await authContextADAL.AcquireTokenAsync(enterpriseAppResourceId, clientCred, userAssertion); HttpResponseMessage response = null; try { //response = ODataHelper.SendRequestWithAccessToken(enterpriseAppBaseAddress + "api/branches", result.AccessToken); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken); // Call the To Do list service. // Or call to /api/outlook/branches/user response = await httpClient.GetAsync(enterpriseAppBaseAddress + "api/branches/user"); if (response.IsSuccessStatusCode) { return(response); } else { string failureDescription = await response.Content.ReadAsStringAsync(); return(SendErrorToClient(HttpStatusCode.Unauthorized, null, $"{response.ReasonPhrase}\n {failureDescription} " + "- An error occurred while getting /api/branches")); } } catch (MsalServiceException e) { itemNames.Add("e.Message: " + e.Message); } } // The token from the client does not have "access_as_user" permission. return(SendErrorToClient(HttpStatusCode.Unauthorized, null, "Missing access_as_user.")); }
protected override async Task PreTokenRequest() { await base.PreTokenRequest(); UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState); Logger.Information(this.CallState, "User '{0}' detected as '{1}'", this.userCredential.UserName, userRealmResponse.AccountType); if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0) { if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl)) { var ex = new AdalException(AdalError.MissingFederationMetadataUrl); Logger.LogException(this.CallState, ex); throw ex; } Uri wsTrustUrl = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState); Logger.Information(this.CallState, "WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustUrl, userRealmResponse.FederationMetadataUrl); WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustUrl, this.userCredential, this.CallState); Logger.Information(this.CallState, "Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType); // We assume that if the response token type is not SAML 1.1, it is SAML 2 this.samlAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer); } else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0) { // handle password grant flow for the managed user if (this.userCredential.PasswordToCharArray() == null) { var ex = new AdalException(AdalError.PasswordRequiredForManagedUserError); Logger.LogException(this.CallState, ex); throw ex; } } else { var ex = new AdalException(AdalError.UnknownUserType); Logger.LogException(this.CallState, ex); throw ex; } }
public AcquireTokenForMSAHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, UserAssertion userAssertion, bool callSync) : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.UserPlusClient, callSync) { if (userAssertion == null) { throw new ArgumentNullException("userAssertion"); } if (string.IsNullOrWhiteSpace(userAssertion.AssertionType)) { var ex = new ArgumentException(AdalErrorMessage.UserCredentialAssertionTypeEmpty, "userAssertion"); Logger.LogException(this.CallState, ex); throw ex; } this.userAssertion = userAssertion; this.DisplayableId = userAssertion.UserName; }
protected override async Task PreTokenRequest() { await base.PreTokenRequest().ConfigureAwait(false); if (this.PerformUserRealmDiscovery()) { UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState).ConfigureAwait(false); PlatformPlugin.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " User with hash '{0}' detected as '{1}'", PlatformPlugin.CryptographyHelper.CreateSha256Hash(this.userCredential.UserName), userRealmResponse.AccountType)); if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0) { if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl)) { throw new AdalException(AdalError.MissingFederationMetadataUrl); } WsTrustAddress wsTrustAddress = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState).ConfigureAwait(false); PlatformPlugin.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustAddress.Uri, userRealmResponse.FederationMetadataUrl)); WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, this.userCredential, this.CallState, userRealmResponse.CloudAudienceUrn).ConfigureAwait(false); PlatformPlugin.Logger.Information(this.CallState, string.Format(CultureInfo.CurrentCulture, " Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType)); // We assume that if the response token type is not SAML 1.1, it is SAML 2 this.userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer); } else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0) { // handle password grant flow for the managed user if (this.userCredential.PasswordToCharArray() == null) { throw new AdalException(AdalError.PasswordRequiredForManagedUserError); } } else { throw new AdalException(AdalError.UnknownUserType); } } }
// GET: api/DiscoveryResource public async Task<IEnumerable<DiscoveryResources>> Get() { ClientCredential clientCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; string userAccessToken = bootstrapContext.Token; UserAssertion userAssertion = new UserAssertion(userAccessToken); AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, SettingsHelper.Tenant)); DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, () => { var authResult = authContext.AcquireToken(SettingsHelper.DiscoveryServiceResourceId, clientCred, userAssertion); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilitiesAsync(); IEnumerable<DiscoveryResources> appCapabilities = dcr.Select(p => new DiscoveryResources { CapabilityName = p.Key, ServiceEndpointUri = p.Value.ServiceEndpointUri.ToString(), ServiceResourceId = p.Value.ServiceResourceId }); return appCapabilities; }
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(); }
private async Task<AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserAssertion userAssertion, bool callSync = false) { var handler = new AcquireTokenForMSAHandler(this.Authenticator, this.TokenCache, resource, clientId, userAssertion, callSync); return await handler.RunAsync(); }
/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="ctx">Authentication context instance</param> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="userAssertion">The assertion to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns> public static async Task <AuthenticationResult> AcquireTokenAsync(this AuthenticationContext ctx, string resource, string clientId, UserAssertion userAssertion) { return(await ctx.AcquireTokenCommonAsync(resource, clientId, userAssertion).ConfigureAwait(false)); }
/// <summary> /// This method will get access for the web api from the Azure Active Directory. /// This method internally uses the Authorization token sent by the UI application /// </summary> /// <returns>Access Token for the web api service</returns> private async Task<string> GetAccessToken() { try { string clientId = generalSettings.ClientId; string appKey = generalSettings.AppKey; string aadInstance = generalSettings.AADInstance; string tenant = generalSettings.Tenant; string resource = generalSettings.SiteURL; ClientCredential clientCred = new ClientCredential(clientId, appKey); string accessToken = Context.Request.Headers["Authorization"].ToString().Split(' ')[1]; UserAssertion userAssertion = new UserAssertion(accessToken); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); //ToDo: Set the TokenCache to null. Need to implement custom token cache to support multiple users //If we dont have the custom cache, there will be some performance overhead. AuthenticationContext authContext = new AuthenticationContext(authority, null); AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred, userAssertion); return result.AccessToken; } catch(AggregateException ex) { throw; } catch(Exception ex) { customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable); throw; } }
protected override async Task PreTokenRequest() { await base.PreTokenRequest(); if (this.PerformUserRealmDiscovery()) { UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState); PlatformPlugin.Logger.Information(this.CallState, string.Format("User with hash '{0}' detected as '{1}'", PlatformPlugin.CryptographyHelper.CreateSha256Hash(this.userCredential.UserName), userRealmResponse.AccountType)); if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0) { if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl)) { throw new AdalException(AdalError.MissingFederationMetadataUrl); } WsTrustAddress wsTrustAddress = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState); PlatformPlugin.Logger.Information(this.CallState, string.Format("WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustAddress.Uri, userRealmResponse.FederationMetadataUrl)); WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, this.userCredential, this.CallState); PlatformPlugin.Logger.Information(this.CallState, string.Format("Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType)); // We assume that if the response token type is not SAML 1.1, it is SAML 2 this.userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer); } else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0) { // handle password grant flow for the managed user if (this.userCredential.PasswordToCharArray() == null) { throw new AdalException(AdalError.PasswordRequiredForManagedUserError); } } else { throw new AdalException(AdalError.UnknownUserType); } } }
/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="credential">The credential to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns> internal IAsyncOperation <AuthenticationResult> AcquireTokenAsync(string resource, string clientId, UserAssertion credential) { return(RunTaskAsAsyncOperation(this.AcquireTokenCommonAsync(resource, clientId, credential))); }
private async Task<AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserAssertion userAssertion) { var handler = new AcquireTokenNonInteractiveHandler(this.Authenticator, this.TokenCache, resource, clientId, userAssertion); return await handler.RunAsync(); }
// // GET: /UserProfile/ public async Task<ActionResult> Index() { // // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API. // UserProfile profile; AuthenticationResult result = null; try { string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; AuthenticationContext authContext = new AuthenticationContext("https://login.chinacloudapi.cn/common/"); ClientCredential clientCred = new ClientCredential(clientId, appKey); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value; string tenant = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; ; UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName); result = await authContext.AcquireTokenAsync(graphResourceId, clientCred, userAssertion); // // Call the Graph API and retrieve the user's profile. // string graphUserUrl = string.Format("https://graph.chinacloudapi.cn/{0}/me?api-version=2013-11-08", tenant); string requestUrl = string.Format(CultureInfo.InvariantCulture, graphUserUrl, HttpUtility.UrlEncode(tenantId)); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = await client.SendAsync(request); // // Return the user's profile in the view. // if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); profile = JsonConvert.DeserializeObject<UserProfile>(responseString); } else { // // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again. // var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == graphResourceId); foreach (TokenCacheItem tci in todoTokens) authContext.TokenCache.DeleteItem(tci); profile = new UserProfile(); profile.DisplayName = " "; profile.GivenName = " "; profile.Surname = " "; ViewBag.ErrorMessage = "UnexpectedError"; } return View(profile); } catch (AdalException ee) { // // If the user doesn't have an access token, they need to re-authorize. // // // If refresh is set to true, the user has clicked the link to be authorized again. // if (Request.QueryString["reauth"] == "True") { // // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties(), OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // profile = new UserProfile(); profile.DisplayName = " "; profile.GivenName = " "; profile.Surname = " "; ViewBag.ErrorMessage = "AuthorizationRequired"; return View(profile); } }
/// <summary> /// Acquires an access token from the authority on behalf of a user. It requires using a user token previously received. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientAssertion">The client assertion to use for token acquisition.</param> /// <param name="userAssertion">The user assertion (token) to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time.</returns> public async Task <AuthenticationResult> AcquireTokenAsync(string resource, ClientAssertion clientAssertion, UserAssertion userAssertion) { return(await this.AcquireTokenOnBehalfCommonAsync(resource, new ClientKey(clientAssertion), userAssertion)); }
private async Task <AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserAssertion userAssertion) { var handler = new AcquireTokenNonInteractiveHandler(this.Authenticator, this.TokenCache, resource, clientId, userAssertion); return(await handler.RunAsync()); }
/// <summary> /// Acquires an access token from the authority on behalf of a user. It requires using a user token previously received. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientCertificate">The client certificate to use for token acquisition.</param> /// <param name="userAssertion">The user assertion (token) to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time.</returns> public async Task <AuthenticationResult> AcquireTokenAsync(string resource, IClientAssertionCertificate clientCertificate, UserAssertion userAssertion) { return(await this.AcquireTokenOnBehalfCommonAsync(resource, new ClientKey(clientCertificate, this.Authenticator), userAssertion).ConfigureAwait(false)); }
/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="credential">The credential to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns> internal IAsyncOperation<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, UserAssertion credential) { return RunTaskAsAsyncOperation(this.AcquireTokenCommonAsync(resource, clientId, credential)); }
public static async Task<UserProfile> CallGraphAPIOnBehalfOfUser() { UserProfile profile = null; string accessToken = null; AuthenticationResult result = null; // // Use ADAL to get a token On Behalf Of the current user. To do this we will need: // The Resource ID of the service we want to call. // The current user's access token, from the current request's authorization header. // The credentials of this application. // The username (UPN or email) of the user calling the API // ClientCredential clientCred = new ClientCredential(clientId, appKey); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value; string userAccessToken = bootstrapContext.Token; UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(authority, new DbTokenCache(userId)); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { result = authContext.AcquireToken(graphResourceId, clientCred, userAssertion); accessToken = result.AccessToken; } catch (AdalException ex) { if (ex.ErrorCode == "temporarily_unavailable") { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } } while ((retry == true) && (retryCount < 1)); if (accessToken == null) { // An unexpected error occurred. return (null); } // // Call the Graph API and retrieve the user's profile. // string requestUrl = String.Format( CultureInfo.InvariantCulture, graphUserUrl, HttpUtility.UrlEncode(tenant)); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); // // Return the user's profile. // if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); profile = JsonConvert.DeserializeObject<UserProfile>(responseString); return (profile); } // An unexpected error occurred calling the Graph API. Return a null profile. return (null); }
public static async Task<UserProfile> CallGraphAPIOnBehalfOfUser() { UserProfile profile = null; string accessToken = null; AuthenticationResult result = null; // // Use ADAL to get a token On Behalf Of the current user. To do this we will need: // The Resource ID of the service we want to call. // The current user's access token, from the current request's authorization header. // The credentials of this application. // ClientCredential clientCred = new ClientCredential(clientId, appKey); string authHeader = HttpContext.Current.Request.Headers["Authorization"]; // The header is of the form "bearer <accesstoken>", so extract to the right of the whitespace to find the access token. string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim(); UserAssertion userAssertion = new UserAssertion(userAccessToken); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); // ADAL has a default in-memory cache that is used for all AcquireToken calls (but not with AcquireTokenWith* calls). // This sample uses the in-memory cache, which has limited effectiveness if there are multiple instances of the TodoListService (e.g. a farm). // You can also implement your own cache for access tokens and refresh tokens by storing them separately, for example in a database. // If you wish to do that, use the AuthenticationContext constructor that passes null for the token cache. // AuthenticationContext authContext = new AuthenticationContext(authority, null); AuthenticationContext authContext = new AuthenticationContext(authority); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { result = authContext.AcquireToken(graphResourceId, userAssertion, clientCred); accessToken = result.AccessToken; } catch (ActiveDirectoryAuthenticationException ex) { if (ex.ErrorCode == "temporarily_unavailable") { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } } while ((retry == true) && (retryCount < 1)); if (accessToken == null) { // An unexpected error occurred. return (null); } // // Call the Graph API and retrieve the user's profile. // string requestUrl = String.Format( CultureInfo.InvariantCulture, graphUserUrl, HttpUtility.UrlEncode(tenant)); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); // // Return the user's profile. // if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); profile = JsonConvert.DeserializeObject<UserProfile>(responseString); return (profile); } // An unexpected error occurred calling the Graph API. Return a null profile. return (null); }
/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="userAssertion">The assertion to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns> public async Task<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, UserAssertion userAssertion) { return await this.AcquireTokenCommonAsync(resource, clientId, userAssertion); }
private async Task <AuthenticationResult> AcquireTokenOnBehalfCommonAsync(string resource, ClientKey clientKey, UserAssertion userAssertion) { RequestData requestData = new RequestData { Authenticator = this.Authenticator, TokenCache = this.TokenCache, Resource = resource, ClientKey = clientKey, ExtendedLifeTimeEnabled = this.ExtendedLifeTimeEnabled }; var handler = new AcquireTokenOnBehalfHandler(requestData, userAssertion); return(await handler.RunAsync().ConfigureAwait(false)); }
private async Task <AuthenticationResult> AcquireTokenOnBehalfCommonAsync(string resource, ClientKey clientKey, UserAssertion userAssertion) { var handler = new AcquireTokenOnBehalfHandler(this.Authenticator, this.TokenCache, resource, clientKey, userAssertion); return(await handler.RunAsync()); }
/// <summary> /// Acquires an access token from the authority on behalf of a user. It requires using a user token previously received. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientAssertion">The client assertion to use for token acquisition.</param> /// <param name="userAssertion">The user assertion (token) to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time.</returns> public async Task<AuthenticationResult> AcquireTokenAsync(string resource, ClientAssertion clientAssertion, UserAssertion userAssertion) { return await this.AcquireTokenOnBehalfCommonAsync(resource, new ClientKey(clientAssertion), userAssertion); }
/// <summary> /// Acquires security token from the authority. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientId">Identifier of the client requesting the token.</param> /// <param name="userAssertion">The assertion to use for token acquisition.</param> /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns> internal async Task <AuthenticationResult> AcquireTokenAsync(string resource, string clientId, UserAssertion userAssertion) { return(await this.AcquireTokenCommonAsync(resource, clientId, userAssertion)); }
private async Task<AuthenticationResult> AcquireTokenOnBehalfCommonAsync(string resource, ClientKey clientKey, UserAssertion userAssertion) { var handler = new AcquireTokenOnBehalfHandler(this.Authenticator, this.TokenCache, resource, clientKey, userAssertion); return await handler.RunAsync(); }
private async Task <AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserAssertion userAssertion, bool callSync = false) { var handler = new AcquireTokenForMSAHandler(this.Authenticator, this.TokenCache, resource, clientId, userAssertion, callSync); return(await handler.RunAsync()); }
/// <summary> /// Gets an Active Directory client. /// </summary> /// <returns>An ActiveDirectoryClient instance.</returns> /// <remarks>When no objectidentifier claim is present, this will return null.</remarks> public static async Task<ActiveDirectoryClient> GetActiveDirectoryClient() { // When no objectidentifier claim is present, this will return null. if (!string.IsNullOrEmpty(GetUserId())) { string tenantId = GetTenantId(); string authority = string.Format(_aadInstance, tenantId); AuthenticationContext authContext = new AuthenticationContext(authority); AuthenticationResult result; if (string.IsNullOrEmpty(_appKey)) { X509Certificate2 cert = LoadCertificate(); string authHeader = HttpContext.Current.Request.Headers["Authorization"]; string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim(); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; userAccessToken = bootstrapContext.Token; UserAssertion userAssertion = new UserAssertion(userAccessToken); ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(_clientId, cert); result = await authContext.AcquireTokenAsync(_graphResourceId, clientAssertionCertificate, userAssertion); } else { ClientCredential clientCredential = new ClientCredential(_clientId, _appKey); result = await authContext.AcquireTokenAsync(_graphResourceId, clientCredential); } string accessToken = result.AccessToken; Uri serviceRoot = new Uri(new Uri(_graphResourceId), tenantId); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, () => { return Task.FromResult(accessToken); }); return activeDirectoryClient; } return null; }