/// <summary> /// Retrieves a new auth token from AAD. /// </summary> /// <param name="authUrl">The root of the authority url.</param> /// <param name="tenantDomain">The domain name of the Azure tenant as the second part of the authority url.</param> /// <param name="targetServiceUrl">The url of the service that should be accessed. Be sure to check trailing slashes!</param> /// <param name="clientId">The unique client id as it is configured in Azure Portal.</param> /// <param name="appKey">This value is optional and contains the App-Key-Secret if it is configured in azure portal.</param> /// <param name="redirectUrl">The redirect url as it is configured in Azure Portal.</param> /// <returns>The authentication token.</returns> public static async Task<string> RetrieveTokenAsync(string authUrl, string tenantDomain, string targetServiceUrl, string clientId, Uri redirectUrl, string appKey = null) { var authenticationContext = new AuthenticationContext($"{authUrl}/{tenantDomain}"); try { AuthenticationResult result = null; if (appKey.IsNullOrEmpty()) { // use user auth var parameters = new PlatformParameters(PromptBehavior.Auto); result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientId, redirectUrl, parameters).ConfigureAwait(false); } else { // use key auth var clientCredential = new ClientCredential(clientId, appKey); result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientCredential).ConfigureAwait(false); } if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } // store token for reuse return result.AccessToken; } catch (Exception ex) { throw new InvalidOperationException("Could not retrieve token.", ex); } }
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 ActionResult Index(string code) { CustomAuthenticationManager.CacheAuthenticationCode(code); ClientCredential credential = new ClientCredential(DemoConstants.ClientId, DemoConstants.ClientSecret); string resource = DemoConstants.TargetResource; Uri uriReplyUrl = new Uri(DemoConstants.ClientReplyUrl); AuthenticationContext authenticationContext = new AuthenticationContext(DemoConstants.urlAuthorizationEndpoint); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenByAuthorizationCode( code, uriReplyUrl, credential, resource); CustomAuthenticationManager.CacheAuthenticationResult(authenticationResult); ViewBag.AuthenticationCode = code; return View(authenticationResult); }
protected void Page_Load(object sender, EventArgs e) { //Redirect uri must match the redirect_uri used when requesting Authorization code. string redirectUri = Properties.Settings.Default.RedirectUrl; string authorityUri = "https://login.windows.net/common/oauth2/authorize/"; // Get the auth code string code = Request.Params.GetValues(0)[0]; // Get auth token from auth code TokenCache TC = new TokenCache(); AuthenticationContext AC = new AuthenticationContext(authorityUri, TC); ClientCredential cc = new ClientCredential (Properties.Settings.Default.ClientID, Properties.Settings.Default.ClientSecretKey); AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc); //Set Session "authResult" index string to the AuthenticationResult Session["authResult"] = AR; //Redirect back to Default.aspx Response.Redirect("/Default.aspx"); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = ConfigHelper.ClientId, Authority = ConfigHelper.Authority, PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = context => { ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey); string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value; AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId); return Task.FromResult(0); }, AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message); return Task.FromResult(0); } } }); }
private async Task AddRoles(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg) { var context = new Adal.AuthenticationContext("https://login.microsoftonline.com/" + tenant); var clientCredentials = new Adal.ClientCredential(GraphClientId, GraphClientSecret); var token = await context.AcquireTokenAsync("https://graph.windows.net/", clientCredentials); var userId = arg.AuthenticationTicket.Identity.Claims .First(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier") .Value; HttpClient http = new HttpClient(); string url = "https://graph.windows.net/b2ctestdes.onmicrosoft.com/users/" + userId + "/memberOf?api-version=1.6"; // Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme. HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken); HttpResponseMessage response = await http.SendAsync(request); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); dynamic groups = JObject.Parse(result); foreach (var group in groups.value) { string groupName = group.displayName; arg.AuthenticationTicket.Identity.AddClaim( new Claim(ClaimTypes.Role, groupName)); } } }
public IAuthenticationResult AcquireToken(string resource, ClientCredential clientCredential) { this._authenticationContext.CorrelationId = this.CorrelationId; var _result = this._authenticationContext.AcquireToken(resource, clientCredential); return _result == null ? null : new AuthenticationResultWrapper(_result); }
public static async Task <GraphServiceClient> GetGraphServiceClient2() { var authentication = new { Authority = "https://graph.microsoft.com/", Directory = WebConfigurationManager.AppSettings["ida:TenantId"], Application = WebConfigurationManager.AppSettings["ida:ClientId"], ClientSecret = WebConfigurationManager.AppSettings["ida:ClientSecret"], GraphResourceEndPoint = "v1.0", Instance = WebConfigurationManager.AppSettings["ida:AADInstance"], Domain = WebConfigurationManager.AppSettings["ida:Domain"] }; var graphAPIEndpoint = $"{authentication.Authority}{authentication.GraphResourceEndPoint}"; var newAuth = $"{authentication.Instance}{authentication.Directory}"; //var newAuth2 = $"{authentication.Instance}{authentication.Domain}"; AuthenticationContext authenticationContext = new AuthenticationContext(newAuth); Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(authentication.Application, authentication.ClientSecret); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(authentication.Authority, clientCred); var token = authenticationResult.AccessToken; var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString()); return(Task.FromResult(0)); }); var graphClient = new GraphServiceClient(graphAPIEndpoint, delegateAuthProvider); return(graphClient); }
public async static Task<AuthenticationResult> GetTokenAsync(AuthenticationContext ctx, string resourceId) { ClientCredential credential = new ClientCredential(OfficeSettings.ClientId, OfficeSettings.ClientSecret); var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; UserIdentifier ident = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); var redirectUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)); try { var result = await ctx.AcquireTokenSilentAsync(resourceId, credential, ident); //var result = await ctx.AcquireTokenAsync(resourceId, credential); LastAuthority = ctx.Authority; return result; } catch (AdalException) { ctx.TokenCache.Clear(); return null; } catch (Exception ex) { throw ex; } }
private async Task<AuthenticationResult> GetAccessToken() { AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority); var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); AuthenticationResult result = (AuthenticationResult)this.Session[SettingsHelper.UserTokenCacheKey]; return await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource); }
public static async Task<string> GetAccessToken() { if (string.IsNullOrEmpty(_accessToken)) { // fetch from stuff user claims var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value; // discover contact endpoint var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // create auth context AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EfAdalTokenCache(userObjectId)); // authenticate var authResult = await authContext.AcquireTokenSilentAsync( string.Format("https://{0}.sharepoint.com", SettingsHelper.Office365TenantId), clientCredential, userIdentifier); // obtain access token _accessToken = authResult.AccessToken; } return _accessToken; }
public string GetAccessToken() { ApplicationDbContext db = new ApplicationDbContext(); string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; string tenantId = ConfigurationManager.AppSettings["ida:TenantId"]; string Authority = aadInstance + tenantId; string claimIdName = ClaimTypes.NameIdentifier; string claimIdTenantId = "http://schemas.microsoft.com/identity/claims/tenantid"; string claimIdUserId = "http://schemas.microsoft.com/identity/claims/objectidentifier"; ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current; string signedInUserID = currentUserClaims.FindFirst(claimIdName).Value; string tenantID = currentUserClaims.FindFirst(claimIdTenantId).Value; string userObjectID = currentUserClaims.FindFirst(claimIdUserId).Value; // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc) ClientCredential clientcred = new ClientCredential(clientId, appKey); // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID)); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenSilentAsync(resource, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)).Result; return authenticationResult.AccessToken; }
// GET: Discovery public async Task<ActionResult> Index() { // get instance of the authentication context using the token cache we created previously var signedInUser = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signedInUser)); // create credentials for the application var appCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); // get user identifier var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value; var userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // create instance of DiscoveryClient var discoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint), async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, appCred, userId); return authResult.AccessToken; }); // query discovery service for endpoints var capabilitiesResults = await discoveryClient.DiscoverCapabilitiesAsync(); return View(capabilitiesResults); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = SettingsHelper.ClientId, Authority = SettingsHelper.AzureADAuthority, Notifications = new OpenIdConnectAuthenticationNotifications() { AuthorizationCodeReceived = (context) => { string code = context.Code; ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value; EFADALTokenCache cache = new EFADALTokenCache(userObjectId); AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, cache); Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)); AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId); return Task.FromResult(0); }, AuthenticationFailed = (context) => { context.HandleResponse(); return Task.FromResult(0); } }, TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = false } }); }
public static string GetAccessToken(string resource) { // get user ID in security cookie var signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; // get token cache for signed in user ApplicationDbContext db = new ApplicationDbContext(); ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID); AuthenticationContext authContext = new AuthenticationContext(Authority, userTokenCache); // Get credentials for user var clientCredential = new ClientCredential(clientId, clientSecret); // Create user identifier object using User ID for Azure Active Directory account string objectIdentifierID = "http://schemas.microsoft.com/identity/claims/objectidentifier"; var userObjectId = ClaimsPrincipal.Current.FindFirst(objectIdentifierID).Value; var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // call to ADAL to get access token from cache of across network var authResult = authContext.AcquireTokenSilent(resource, clientCredential, userIdentifier); // obtain access token return authResult.AccessToken; }
//Get the Service Principle credential for getting the access token private static ClientCredential GetCredential() { string filePath = "c:\\Users\\vmuser\\azure\\profiles\\default.profile"; ClientCredential creds; //obtain credential from default location - dev machine if (File.Exists(filePath)) { string[] secrets = GetCredentialFromProfile(filePath); creds = new ClientCredential(secrets[0], secrets[1]); } else if (true) //todo: change to check the Azure environment this app is running in { //obtain credential from custom data settings - App Services, Cloud Services var clientID = CloudConfigurationManager.GetSetting("ClientID"); var clientSecret = CloudConfigurationManager.GetSetting("ClientSecret"); creds = new ClientCredential(clientID, clientSecret); } else if (false) { //TODO: obtain credential from instance metadata -VM, VMSS } else creds = null; return creds; }
private async Task<OutlookServicesClient> EnsureClientCreated() { // fetch from stuff user claims var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value; // discover contact endpoint var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // create auth context AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId)); // create O365 discovery client DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint), async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier); return authResult.AccessToken; }); // query discovery service for endpoint for 'calendar' endpoint CapabilityDiscoveryResult dcr = await discovery.DiscoverCapabilityAsync("Contacts"); // create an OutlookServicesclient return new OutlookServicesClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential, userIdentifier); return authResult.AccessToken; }); }
/// <summary> /// Add the given credential to the in-memory store. /// </summary> /// <param name="credential">The credential to add.</param> public void AddCredential(ClientCredential credential) { if (!_credentials.ContainsKey(credential.ClientId)) { _credentials[credential.ClientId] = credential; } }
public void Configure(string name, OpenIdConnectOptions options) { options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}"; options.ClientId = _azureOptions.ClientId; options.ClientSecret = _azureOptions.ClientSecret; options.CallbackPath = _azureOptions.CallbackPath; options.UseTokenLifetime = true; options.RequireHttpsMetadata = true; options.Resource = "https://management.azure.com/"; options.ResponseType = OpenIdConnectResponseType.CodeIdToken; // do token-based auth options.SaveTokens = true; // save access_token where we can access it // trying to get refresh to work options.Scope.Add("offline_access"); // allow refreshing options.Events = new OpenIdConnectEvents { OnAuthorizationCodeReceived = async ctx => { var request = ctx.HttpContext.Request; var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path); var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret); var authContext = new AuthenticationContext(ctx.Options.Authority, true); var result = await authContext.AcquireTokenByAuthorizationCodeAsync( ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource); ctx.HandleCodeRedemption(result.AccessToken, result.IdToken); } }; }
public static string AcquireToken(string userObjectId) { ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey); AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId)); AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return result.AccessToken; }
private async Task InitOneNoteRestConnection() { // fetch from stuff user claims var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value; // discover onenote endpoint var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // create auth context AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId)); // authenticate with directory service var discoClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint), async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier); return authResult.AccessToken; }); // query discovery service for endpoint for onenote endpoint var discoCapabilityResult = await discoClient.DiscoverCapabilityAsync("Notes"); // get details around onedrive endpoint (replace 1.0 with 2.0 for the new REST API) _oneNoteResourceId = discoCapabilityResult.ServiceResourceId; _oneNoteEndpoint = discoCapabilityResult.ServiceEndpointUri.ToString(); var accessToken = (await authContext.AcquireTokenSilentAsync(_oneNoteResourceId, clientCredential, userIdentifier)).AccessToken; // set the access token on all requests for onenote API _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); return; }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = _appConfig.ClientID, Authority = Constants.Authentication.CommonAuthority, PostLogoutRedirectUri = _appConfig.PostLogoutRedirectURI, TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { // instead of using the default validation (validating against a single issuer value, as we do in line of business apps), // we inject our own multitenant validation logic ValidateIssuer = false, }, Notifications = new OpenIdConnectAuthenticationNotifications() { // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. AuthorizationCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(_appConfig.ClientID,_appConfig.ClientSecret); string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantID), new ADALTokenCache(signedInUserID)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, Constants.Authentication.GraphServiceUrl); return Task.FromResult(0); }, RedirectToIdentityProvider = (context) => { // This ensures that the address used for sign in and sign out is picked up dynamically from the request // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand. string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl; return Task.FromResult(0); }, AuthenticationFailed = (context) => { System.Diagnostics.Trace.TraceError(context.Exception.ToString()); string redirectPath = string.Format("/Error/?errorMessage={0}", context.Exception.Message); context.OwinContext.Response.Redirect(redirectPath); // context.OwinContext.Response.Redirect("/Error/Index"); context.HandleResponse(); // Suppress the exception return Task.FromResult(0); } } }); }
/// <summary> /// Creates a new instance of the <see cref="Tailspin.Surveys.Security.AdalCredential"/> /// </summary> /// <param name="clientCredential">A <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential"/> instance to store in this credential.</param> public AdalCredential(ClientCredential clientCredential) { Guard.ArgumentNotNull(clientCredential, nameof(clientCredential)); ClientCredential = clientCredential; CredentialType = AdalCredentialType.ClientCredential; }
public async Task<ActionResult> Open() { var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value; var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); string token = null; AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId)); // get the activation parameters submitted from SharePoint ActivationParameters parameters = this.LoadActivationParameters(); // get access token for unified api var authResult = await authContext.AcquireTokenSilentAsync(parameters.ResourceId, clientCredential, userIdentifier); token = authResult.AccessToken; // get contents of the file in SharePoint HttpWebRequest request = (HttpWebRequest)WebRequest.Create(parameters.FileGet); request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token); Stream responseStream = request.GetResponse().GetResponseStream(); StreamReader srReader = new StreamReader(responseStream); var fileContents = srReader.ReadToEnd(); // read XML feed XmlReader xmlReader = XmlReader.Create(fileContents); SyndicationFeed feed = SyndicationFeed.Load(xmlReader); xmlReader.Close(); ViewBag.FeedTitle = feed.Title.Text; ViewBag.Posts = feed.Items; return View(); }
private async Task <string> AuthorizationHeaderADAL() { if (!string.IsNullOrEmpty(_authorizationHeader) && (DateTime.UtcNow.AddSeconds(60) < AuthenticationResultADAL.ExpiresOn)) { return(_authorizationHeader); } var uri = new UriBuilder(_settings.AzureAuthEndpoint) { Path = _settings.AadTenant }; var aosUriAuthUri = new Uri(_settings.AosUri); string aosUriAuth = aosUriAuthUri.GetLeftPart(UriPartial.Authority); var authenticationContext = new AuthenticationContext(uri.ToString(), validateAuthority: false); if (_settings.UseServiceAuthentication) { var credentials = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_settings.AadClientId.ToString(), _settings.AadClientSecret); AuthenticationResultADAL = await authenticationContext.AcquireTokenAsync(aosUriAuth, credentials); } else { var credentials = new UserPasswordCredential(_settings.UserName, _settings.UserPassword); AuthenticationResultADAL = await authenticationContext.AcquireTokenAsync(aosUriAuth, _settings.AadClientId.ToString(), credentials); } return(_authorizationHeader = AuthenticationResultADAL.CreateAuthorizationHeader()); }
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; }
/// <summary> /// Acquires an IUserIdentity from Azure Active Directory using the argument authorizationCode. /// </summary> /// <param name="authorizationCode">An authorization code provided by Azure Active Directory used to retrieve an IUserIdentity</param> /// <returns>Returns an IUserIdentity representing a successfully authenticated Azure Active Directory user who has privileges for this configured application</returns> public static IUserIdentity GetAuthenticatedUserIDentity(string authorizationCode) { var authenticationContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", AAD.TENANT_ID)); var clientCredential = new ClientCredential(AAD.CLIENT_ID, AAD.CLIENT_KEY); var authenticationResult = authenticationContext.AcquireTokenByAuthorizationCode(authorizationCode, new Uri(AAD.REPLY_URL), clientCredential); return new UserIdentity(authenticationResult.UserInfo); }
public GraphData(IConfiguration config) { _teamsId = config["teamsId"]; _applicationId = config["GraphSettings:applicationId"]; _tenantId = config["GraphSettings:tenantId"]; _secret = config["GraphSettings:secret"]; _anonymousUserId = config["AnonymousUser:Id"]; _anonymousUserPassword = config["AnonymousUser:Password"]; _channelId = config["GraphSettings:channelId"]; _subscriptionUrl = config["GraphSettings:subscriptionUrl"]; IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(_applicationId) .WithTenantId(_tenantId) .WithClientSecret(_secret) .Build(); ClientCredentialProvider authProvide = new ClientCredentialProvider(confidentialClientApplication); _client = new GraphServiceClient(authProvide); _credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_applicationId, _secret); _authContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}/"); _httpClient = new HttpClient(); }
/// <summary> /// Methods for getting a token from ACS /// Updated 10/21, to use Active Directory Authn Library (ADAL) /// Method uses OAuth Client Credential Authn flow (2-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, string password) { string authString = String.Format(StringConstants.AzureADSTSURL, tenantName); AuthenticationContext authenticationContext = new AuthenticationContext(authString); ClientCredential applicationCreds = new ClientCredential(appPrincipalId, password); try { AuthenticationResult authenticationResult = authenticationContext.AcquireToken(StringConstants.GraphPrincipalId.ToString(), applicationCreds); 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; } }
public static string GetAccessToken(string resource) { // get ClaimsPrincipal for current user ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current; string signedInUserID = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; ApplicationDbContext db = new ApplicationDbContext(); ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID); string urlAuthorityRoot = ConfigurationManager.AppSettings["ida:AADInstance"]; string urlAuthorityTenant = urlAuthorityRoot + tenantID; AuthenticationContext authenticationContext = new AuthenticationContext(urlAuthorityTenant, userTokenCache); Uri uriReplyUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)); string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; ClientCredential clientCredential = new ClientCredential(clientId, clientSecret); UserIdentifier userIdentifier = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier).Result; return authenticationResult.AccessToken; }
private async Task <SharePointClient> EnsureClientCreated() { DiscoveryContext disco = GetFromCache("DiscoveryContext") as DiscoveryContext; if (disco == null) { disco = await DiscoveryContext.CreateAsync(); SaveInCache("DiscoveryContext", disco); } var dcr = await disco.DiscoverCapabilityAsync(MyFilesCapability); var ServiceResourceId = dcr.ServiceResourceId; var ServiceEndpointUri = dcr.ServiceEndpointUri; SaveInCache("LastLoggedInUser", dcr.UserId); return(new SharePointClient(ServiceEndpointUri, async() => { Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential creds = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential( disco.AppIdentity.ClientId, disco.AppIdentity.ClientSecret); return (await disco.AuthenticationContext.AcquireTokenSilentAsync( ServiceResourceId, creds, new UserIdentifier(dcr.UserId, UserIdentifierType.UniqueId))).AccessToken; })); }
/// <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; }
public void ConfigureAuth(IAppBuilder app) { ApplicationDbContext db = new ApplicationDbContext(); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = Authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. AuthorizationCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(clientId, appKey); string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); return Task.FromResult(0); } } }); }
public static List<Organization> GetUserOrganizations() { List<Organization> organizations = new List<Organization>(); string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1]; try { // Aquire Access Token to call Azure Resource Manager ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"], ConfigurationManager.AppSettings["ida:Password"]); // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB AuthenticationContext authContext = new AuthenticationContext( string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserUniqueName)); var items = authContext.TokenCache.ReadItems().ToList(); AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential, new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId)); items = authContext.TokenCache.ReadItems().ToList(); // Get a list of Organizations of which the user is a member string requestUrl = string.Format("{0}/tenants?api-version={1}", ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]); // Make the GET request HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); HttpResponseMessage response = client.SendAsync(request).Result; // Endpoint returns JSON with an array of Tenant Objects // id tenantId // -- -------- // /tenants/7fe877e6-a150-4992-bbfe-f517e304dfa0 7fe877e6-a150-4992-bbfe-f517e304dfa0 // /tenants/62e173e9-301e-423e-bcd4-29121ec1aa24 62e173e9-301e-423e-bcd4-29121ec1aa24 if (response.IsSuccessStatusCode) { string responseContent = response.Content.ReadAsStringAsync().Result; var organizationsResult = (Json.Decode(responseContent)).value; foreach (var organization in organizationsResult) organizations.Add(new Organization() { Id = organization.tenantId, //DisplayName = AzureADGraphAPIUtil.GetOrganizationDisplayName(organization.tenantId), objectIdOfCloudSenseServicePrincipal = AzureADGraphAPIUtil.GetObjectIdOfServicePrincipalInOrganization(organization.tenantId, ConfigurationManager.AppSettings["ida:ClientID"]) }); } } catch { } return organizations; }
public static string AcquireToken(string userObjectId) { 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), new TokenDbCache(userObjectId)); AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return result.AccessToken; }
public async Task <string> GetAccessTokenAdal() { var creds = new Adal.ClientCredential(CLIENT_ID, CLIENT_SECRET); var ctx = new Adal.AuthenticationContext($"https://login.microsoftonline.com/{TENANT_ID}", false); var token = await ctx.AcquireTokenAsync("https://database.windows.net/", creds); return(token.AccessToken); }
public static string GetAccessToken() { context = new AuthenticationContext(authority); credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey); Task <string> token = GetToken(); token.Wait(); return(token.Result); }
private async Task <string> GetGraphToken() { var authority = $"https://login.microsoftonline.com/{_config.Tenant}"; var authContext = new AuthenticationContext(authority); var credentials = new ClientCredential(_config.ClientId, _config.Secret); var authResult = await authContext.AcquireTokenAsync(_config.Resource.AbsoluteUri, credentials); return(await Task.FromResult(authResult.AccessToken)); }
private static async Task <Adalv2.AuthenticationResult> AcquireAadToken(string audience) { var authority = GetAuthority(audience); var credential = new Adalv2.ClientCredential(Config.InternalUsersClientId, Config.InternalUsersClientSecret); var authContext = new Adalv2.AuthenticationContext(authority); var result = await authContext.AcquireTokenAsync(Config.InternalUsersClientId, credential); return(result); }
private async Task <ServiceClientCredentials> GetCredentials(string tenantId, string clientId, string clientSecret) { var context = new AD.AuthenticationContext($"https://login.windows.net/{tenantId}"); var credential = new AD.ClientCredential(clientId, clientSecret); var result = await context.AcquireTokenAsync("https://management.core.windows.net/", credential); string token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); return(new TokenCredentials(token)); }
public async Task <Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> GetOldUserAccessTokenAsync() { // The AuthenticationContext is ADAL's primary class, in which you indicate the direcotry to use. this.authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant); // The ClientCredential is where you pass in your client_id and client_secret, which are // provided to Azure AD in order to receive an access_token using the app's identity. this.credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret); // First, use ADAL to acquire a token using the app's identity (the credential) // The first parameter is the resource we want an access_token for; in this case, the Graph API. //Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = authContext.AcquireTokenAsync("https://graph.windows.net", credential).Result; return(await authContext.AcquireTokenAsync("https://graph.windows.net", credential)); }
public async Task <string> RefreshToken() { var audience = ClaimsPrincipal.Current.FindFirst("aud").Value; var authority = GetAuthority(audience); var credential = new Adalv2.ClientCredential(Config.InternalUsersClientId, Config.InternalUsersClientSecret); var authContext = new Adalv2.AuthenticationContext(authority); var result = await authContext.AcquireTokenAsync(Config.InternalUsersClientId, credential); var res = await authContext.AcquireTokenByRefreshTokenAsync(result.RefreshToken, credential, Config.InternalUsersClientId); return(res.AccessToken); }
private static DynamicsTokenService ConfigureDynamicsTokenService(HttpClient client, HttpRequest req, string keyVaultBaseUrl, string urlDynamics, Guid keyVaultClientId, string keyVaultClientSecret) { var _secretService = new SecretService(keyVaultBaseUrl, keyVaultClientId, keyVaultClientSecret); var clientId = _secretService.GetSecretAsync("Dynamics365-AppCredentialClientId").Result; var clientSecret = _secretService.GetSecretAsync("Dynamics365-AppCredentialClientSecret").Result; //Create Service Instance var ap = AD.AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(urlDynamics)).Result; var authContext = new AD.AuthenticationContext(ap.Authority); var clientCred = new AD.ClientCredential(clientId.Value, clientSecret.Value); return(new DynamicsTokenService(authContext, clientCred, ap.Resource)); }
private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // good code // Acquire a Token for the Graph API and cache it. In the TodoListController, we'll use the cache to acquire a token to the Todo List API string userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret); AuthenticationContext authContext = new AuthenticationContext(authority, new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache(Encoding.Default.GetBytes(userObjectId))); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCodeAsync( notification.Code, new Uri(notification.RedirectUri), clientCred, GraphResourceId).Result; // decode token // https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens idToken = authResult.IdToken; accessToken = authResult.AccessToken; return(Task.FromResult(0)); //string authorizationCode = notification.Code; //ClientCredential clientCred = new ClientCredential(clientId, clientSecret); //AuthenticationResult tokenResult = notification.(authorizationCode, new Uri(notification.RedirectUri), clientCred); //return Task.FromResult(0); /* * var code = notification.Code; * string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; * * Microsoft.Identity.Client.TokenCache userTokenCache = new SessionTokenCache( * signedInUserID, * notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); * * * ConfidentialClientApplication cca = new ConfidentialClientApplicationBuilder( * clientId, * redirectUri, * new Microsoft.Identity.Client.ClientCredential(clientSecret), * userTokenCache, * null); * string[] scopes = graphScopes.Split(new char[] { ' ' }); * * Microsoft.Identity.Client.AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); * return Task.FromResult(0); */ }
public static async Task <string> SendGraphGetRequest(string api, string query) { //Microsoft.IdentityModel.Clients.ActiveDirectory.IClientAssertionCertificate cert = Certi; // First, use ADAL to acquire a token using the app's identity (the credential) // The first parameter is the resource we want an access_token for; in this case, the Graph API. //Microsoft.Identity.Client.AuthenticationResult result = authContext.AcquireTokenAsync("https://graph.windows.net", credential); // For B2C user managment, be sure to use the 1.6 Graph API version. string tenant = "kcstechnologiesb2c.onmicrosoft.com"; string clientId = "46fb6136-4e8c-4b24-89dd-e5200808ac9e"; string clientSecret = "Oc198PyN+HyApvpcZQsu5w/8JzP6PQ9h0HvGOKX3kMM="; authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant); credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret); HttpClient http = new HttpClient(); string url = "https://graph.windows.net/" + tenant + api + "?" + Constants.aadGraphVersion; if (!string.IsNullOrEmpty(query)) { url += "&" + query; } Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("GET " + url); Console.WriteLine("Authorization: Bearer " + App.AccessToken.Substring(0, 80) + "..."); Console.WriteLine(""); // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme. HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", App.AccessToken); HttpResponseMessage response = await http.SendAsync(request); if (!response.IsSuccessStatusCode) { string error = await response.Content.ReadAsStringAsync(); object formatted = JsonConvert.DeserializeObject(error); throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase); Console.WriteLine(""); return(await response.Content.ReadAsStringAsync()); }
static void InitializeAzureKeyVaultProvider() { string clientId = System.Environment.GetEnvironmentVariable("applicationADID"); string clientSecret = System.Environment.GetEnvironmentVariable("applicationADSecret"); _clientCredential = new ClientCredential(clientId, clientSecret); SqlColumnEncryptionAzureKeyVaultProvider azureKeyVaultProvider = new SqlColumnEncryptionAzureKeyVaultProvider(GetToken); Dictionary <string, SqlColumnEncryptionKeyStoreProvider> providers = new Dictionary <string, SqlColumnEncryptionKeyStoreProvider>(); providers.Add(SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, azureKeyVaultProvider); SqlConnection.RegisterColumnEncryptionKeyStoreProviders(providers); }
public static async Task <CRMWebAPI> GetAPI2(ITurnContext <IMessageActivity> context, IConfiguration ConfigurationManager, IStatePropertyAccessor <UserProfileState> userState) { string authority = "https://login.microsoftonline.com/"; string clientId = ConfigurationManager["AdClientId"]; string crmBaseUrl = ConfigurationManager["CrmServerUrlProd"]; string clientSecret = ConfigurationManager["ClientSecret"]; string tenantID = ConfigurationManager["TenantId"]; var clientcred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret); //var authContext = new AuthenticationContext(authority + tenantID); //var authenticationResult = authContext.AcquireToken(crmBaseUrl, clientcred); //var accessToken = GetAccessToken(); var accessToken = await GetCurrentAccessToken(context, ConfigurationManager, userState); return(new CRMWebAPI(crmBaseUrl + "/api/data/v8.1/", accessToken)); }
// 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.")); }
/// <summary> /// Fired when the user authenticates /// </summary> /// <param name="notification"></param> /// <returns></returns> private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Get the user's object id (used to name the token cache) string userObjId = notification.AuthenticationTicket.Identity.FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value; // Create a token cache HttpContextBase httpContext = notification.OwinContext.Get <HttpContextBase>(typeof(HttpContextBase).FullName); SessionTokenCache tokenCache = new SessionTokenCache(userObjId, httpContext); // Exchange the auth code for a token ADAL.ClientCredential clientCred = new ADAL.ClientCredential(Settings.AAD_APP_ID, Settings.AAD_APP_SECRET); // Create the auth context ADAL.AuthenticationContext authContext = new ADAL.AuthenticationContext( string.Format(CultureInfo.InvariantCulture, Settings.AAD_INSTANCE, "common", ""), false, tokenCache); ADAL.AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( notification.Code, notification.Request.Uri, clientCred, Settings.GRAPH_API_URL); }
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) { // Get the user's object id (used to name the token cache) string userObjId = notification.AuthenticationTicket.Identity .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; // Create a token cache HttpContextBase httpContext = notification.OwinContext.Get <HttpContextBase>(typeof(HttpContextBase).FullName); SessionTokenCache tokenCache = new SessionTokenCache(userObjId, httpContext); // Exchange the auth code for a token ADAL.ClientCredential clientCred = new ADAL.ClientCredential(appId, appSecret); // Create the auth context ADAL.AuthenticationContext authContext = new ADAL.AuthenticationContext( authority, false, tokenCache); ADAL.AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( notification.Code, notification.Request.Uri, clientCred, "https://graph.microsoft.com"); }
public async static Task <Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> GetAuthentication() { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult; try { if (string.IsNullOrEmpty(authority) && string.IsNullOrEmpty(appId) && string.IsNullOrEmpty(clientSecret) && string.IsNullOrEmpty(AADGraphResourceId)) { //Add Logger return(null); } AuthenticationContext authContext = new AuthenticationContext(authority); Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(appId, clientSecret); authenticationResult = await authContext.AcquireTokenAsync(AADGraphResourceId, credential); } catch (Exception ex) { throw ex; } return(authenticationResult); }
public static KeyVaultClient CreateKeyVaultClient(ILogger logger = null) { var armClientId = Environment.GetEnvironmentVariable("ARM_CLIENT_ID"); var armClientSecret = Environment.GetEnvironmentVariable("ARM_CLIENT_SECRET"); var armSubscriptionId = Environment.GetEnvironmentVariable("ARM_SUBSCRIPTION_ID"); var armTenantId = Environment.GetEnvironmentVariable("ARM_TENANT_ID"); KeyVaultClient keyVaultClient; if ( string.IsNullOrWhiteSpace(armClientId) || string.IsNullOrWhiteSpace(armClientSecret) || string.IsNullOrWhiteSpace(armSubscriptionId) || string.IsNullOrWhiteSpace(armTenantId) ) { if (logger != null) { logger.LogInformation("CreateKeyVaultClient is utilizing ARM_* Environment Variables"); } var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); keyVaultClient = new KeyVaultClient(authCallback); } else { if (logger != null) { logger.LogInformation("CreateKeyVaultClient is utilizing AuthenticationContext.AcquireTokenAsync Technique"); } keyVaultClient = new KeyVaultClient(async(authority, resource, scope) => { var adCredential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(armClientId, armClientSecret); var authenticationContext = new AuthenticationContext(authority, null); return((await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken); }); } return(keyVaultClient); }
internal async Task <string> GetAadToken(Options options, string resource = "https://management.core.windows.net/") { if (LoginInteractively) { var publicApp = PublicClientApplicationBuilder.Create(options.InteractiveClientId) .WithAuthority(AadAuthorityAudience.None) .WithTenantId(options.TenantId) .WithDefaultRedirectUri() .Build(); var scopes = new[] { $"{resource}/user_impersonation" }; var resultInteractive = publicApp.AcquireTokenInteractive(scopes); return((await resultInteractive.WithPrompt(Prompt.SelectAccount).ExecuteAsync()).AccessToken); } // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc) ClientCredential creds = new ClientCredential(options.ClientId, options.ClientSecret); // Get auth token from auth code var authContext = new AuthenticationContext(AUTHORITY + options.TenantId); var result = await authContext.AcquireTokenAsync(resource, creds); // Acquire user token for the interactive user for Kusto: return(result.AccessToken); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, PostLogoutRedirectUri = postLogoutRedirectUri, TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "roles" }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async(context) => { var code = context.Code; var userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var clientCredential = new ADAL.ClientCredential(clientId, clientSecret); var authContext = new ADAL.AuthenticationContext(authority, new NaiveSessionCache(userObjectID)); var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), clientCredential, targetResource); } } }); }
private void InitializeAzureKeyVaultProvider() { // Initialize the Azure Key Vault provider SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider = new SqlColumnEncryptionAzureKeyVaultProvider(KeyVaultAuthenticationCallback); SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("ContosoHRDatabase")); if (builder.Authentication != SqlAuthenticationMethod.ActiveDirectoryManagedIdentity) { var clientId = "f0f029e7-a654-4f34-8f66-db76c1b29752"; var secret = "U7O-B811m91~gN8nV-5fGzgpIlV_CLt6Mi"; _clientCredential = new ClientCredential(clientId, secret); } // Register the Azure Key Vault provider SqlConnection.RegisterColumnEncryptionKeyStoreProviders( customProviders: new Dictionary <string, SqlColumnEncryptionKeyStoreProvider>( capacity: 1, comparer: StringComparer.OrdinalIgnoreCase) { { SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, sqlColumnEncryptionAzureKeyVaultProvider } } ); }
// // The Client ID is used by the application to uniquely identify itself to Azure AD. // The App Key is a credential used to authenticate the application to Azure AD. Azure AD supports password and certificate credentials. // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD. // 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. // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out. // // This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API. public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = MediaLibraryWebApp.Configuration.ClientId, Authority = MediaLibraryWebApp.Configuration.Authority, PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { // // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. // AuthorizationCodeReceived = (context) => { var code = context.Code; System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken; string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value; Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey); NaiveSessionCache cache = new NaiveSessionCache(userObjectID); AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache); //Getting a token to connect with GraphApi later on userProfile page AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId); //Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId); string kdAccessToken = kdAPiresult.AccessToken; //Initializing MediaServicesCredentials in order to obtain access token to be used to connect var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey); //Forces to get access token amsCredentials.RefreshToken(); //Adding token to a claim so it can be accessible within controller context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData)); //Adding media services access token as claim so it can be accessible within controller context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken)); return(Task.FromResult(0)); } } }); }
public bool GetCRMConnection() { Credentials = new ClientCredentials(); try { XmlTextReader reader = new XmlTextReader("Connection.xml"); string element = ""; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { element = reader.Name; } else if (reader.NodeType == XmlNodeType.Text) { switch (element) { case "userlicence": //Display the text in each element. bool isValid = Guid.TryParse(reader.Value, out license); if (!isValid) { MessageBox.Show("The license is in an invalid format. Time Tracker will not be able to sycn to JARVIS"); return(false); } break; } } } reader.Close(); string organizationUrl = "https://csp.crm.dynamics.com"; string resourceURL = "https://csp.api.crm.dynamics.com" + "/api/data/"; string clientId = "c4e4407b-66d1-4452-9b05-db0a0ce9baef"; // Client Id string appKey = "Sy[?Mk106C2OvHXZ:Krytwj=_XN_KKlh"; //Client Secret //Create the Client credentials to pass for authentication Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientcred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey); //get the authentication parameters Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationParameters authParam = Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(resourceURL)).Result; //Generate the authentication context - this is the azure login url specific to the tenant string authority = authParam.Authority; //request token AuthenticationResult authenticationResult = new AuthenticationContext(authority).AcquireTokenAsync(organizationUrl, clientcred).Result; //get the token string token = authenticationResult.AccessToken; Uri serviceUrl = new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=9.1"); OrganizationWebProxyClient sdkService; sdkService = new OrganizationWebProxyClient(serviceUrl, false); sdkService.CallerId = license; sdkService.HeaderToken = token; _service = (Microsoft.Xrm.Sdk.IOrganizationService)sdkService != null ? (Microsoft.Xrm.Sdk.IOrganizationService)sdkService : null; Microsoft.Xrm.Sdk.Entity user = _service.Retrieve("systemuser", license, new Microsoft.Xrm.Sdk.Query.ColumnSet(true)); return(true); } catch (Exception ex) { MessageBox.Show("You do not have a valid license for JARIVS and will not be able to sync your time"); return(false); } }
/// <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="clientCredential">The client credential 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, ClientCredential clientCredential, UserAssertion userAssertion) { return(await this.AcquireTokenOnBehalfCommonAsync(resource, new ClientKey(clientCredential), userAssertion).ConfigureAwait(false)); }
/// <summary> /// Acquires security token without asking for user credential. /// </summary> /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param> /// <param name="clientCredential">The client credential to use for token acquisition.</param> /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param> /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns> public async Task <AuthenticationResult> AcquireTokenSilentAsync(string resource, ClientCredential clientCredential, UserIdentifier userId) { return(await this.AcquireTokenSilentCommonAsync(resource, new ClientKey(clientCredential), userId, null).ConfigureAwait(false)); }
public void Run() { // Try to obtain the authorization token var clientCredential = new ClientCredential(clientId, clientSecret); var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId)); var result = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result; if (result == null) { throw new InvalidOperationException("Failed to obtain authorization token"); } // Read the token and create the appropriate credentials object string token = result.AccessToken; var credentials = new TokenCredentials(token); // Read the template and parameter file contents JObject templateFileContents = GetJsonFileContents(pathToTemplateFile); JObject parameterFileContents = GetJsonFileContents(pathToParameterFile); // Create the resource manager client var resourceManagementClient = new ResourceManagementClient(credentials); resourceManagementClient.SubscriptionId = subscriptionId; // Create or check that resource group exists EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation); // Start a deployment DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents); }