/// <summary> /// Retrieves an authentication result for the specified resource. /// </summary> /// <param name="resource">The resource to authenticate.</param> /// <returns>The <see cref="IAuthenticationResult"/> returned for the resource.</returns> protected override async Task<IAuthenticationResult> AuthenticateResourceAsync(string resource) { IAuthenticationResult authenticationResult = null; var adalServiceInfo = this.ServiceInfo as AdalServiceInfo; if (adalServiceInfo == null) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = "AdalAppOnlyServiceInfoProvider requires an AdalServiceInfo." }); } if (adalServiceInfo.ClientCertificate == null) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = "Client certificate is required for app-only authentication." }); } var clientAssertionCertificate = new ClientAssertionCertificate(adalServiceInfo.AppId, adalServiceInfo.ClientCertificate); try { authenticationResult = await this.authenticationContextWrapper.AcquireTokenAsync(resource, clientAssertionCertificate); } catch (Exception exception) { AuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { AuthenticationExceptionHelper.HandleAuthenticationException(null); } return authenticationResult; }
public void ConfigureAuth(IAppBuilder app) { 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 = async (context) => { var code = context.Code; if ( certName.Length != 0) { // Create a Client Credential Using a Certificate // // Initialize the Certificate Credential to be used by ADAL. // First find the matching certificate in the cert store. // X509Certificate2 cert = null; X509Store store = new X509Store(StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); // Place all certificates in an X509Certificate2Collection object. X509Certificate2Collection certCollection = store.Certificates; // Find unexpired certificates. X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); // From the collection of unexpired certificates, find the ones with the correct name. X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false); if (signingCert.Count == 0) { // No matching certificate found. return; } // Return the first certificate in the collection, has the right name and is current. cert = signingCert[0]; } finally { store.Close(); } // Then create the certificate credential. ClientAssertionCertificate credential = new ClientAssertionCertificate(clientId, cert); string userObjectID = context.AuthenticationTicket.Identity.FindFirst( "http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID)); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); AuthenticationHelper.token = result.AccessToken; } else { // Create a Client Credential Using an Application Key ClientCredential credential = new ClientCredential(clientId, appKey); string userObjectID = context.AuthenticationTicket.Identity.FindFirst( "http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID)); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); AuthenticationHelper.token = result.AccessToken; } } } }); }
public SharePointFileManager(string serverAppIdUri, string odataUri, string webname, string aadTenantId, string clientId, string certFileName, string certPassword, string ssgUsername, string ssgPassword, string nativeBaseUri) { OdataUri = odataUri; ServerAppIdUri = serverAppIdUri; NativeBaseUri = nativeBaseUri; WebName = webname; // ensure the webname has a slash. if (!string.IsNullOrEmpty(WebName) && WebName[0] != '/') { WebName = "/" + WebName; } string listDataEndpoint = odataUri + "/_vti_bin/listdata.svc/"; ApiEndpoint = odataUri + "/_api/"; if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { // add authentication. var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); // Create the Client cert. X509Certificate2 cert = new X509Certificate2(certFileName, certPassword); ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, cert); //ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientAssertionCertificate); task.Wait(); authenticationResult = task.Result; Authorization = authenticationResult.CreateAuthorizationHeader(); } else { // authenticate using the SSG. string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ssgUsername + ":" + ssgPassword)); Authorization = "Basic " + credentials; } // create the HttpClient that is used for our direct REST calls. client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); client.DefaultRequestHeaders.Add("Authorization", Authorization); var digestTask = GetDigest(client); digestTask.Wait(); string digest = digestTask.Result; client.DefaultRequestHeaders.Add("X-RequestDigest", digest); }
internal AzureActiveDirectoryTokenProvider(AuthenticationContext authContext, ClientAssertionCertificate clientAssertionCertificate) { this.clientAssertionCertificate = clientAssertionCertificate; this.authContext = authContext; this.authType = AuthType.ClientAssertionCertificate; this.clientId = clientAssertionCertificate.ClientId; }
private async Task <string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate assertionCert) { var context = new AuthenticationContext(authority, TokenCache.DefaultShared); var result = await context.AcquireTokenAsync(resource, assertionCert).ConfigureAwait(false); return(result.AccessToken); }
/// <summary> /// Initializes a new instance of the <see cref="AdalAuthenticator"/> class. /// </summary> /// <param name="clientCertificate">A client credential that includes a X509Certificate.</param> /// <param name="configurationOAuth">A configuration object for OAuth client credential authentication.</param> /// <param name="customHttpClient">A customized instance of the HttpClient class.</param> /// <param name="logger">The type used to perform logging.</param> public AdalAuthenticator(ClientAssertionCertificate clientCertificate, OAuthConfiguration configurationOAuth, HttpClient customHttpClient = null, ILogger logger = null) : this(clientCertificate, false, configurationOAuth, customHttpClient, logger) { }
private static async Task RunProcess() { // Establish connection to CosmosDB string connectionString = @"MONGO-CONNECTION-STRING-HERE"; MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString)); settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 }; var mongoClient = new MongoClient(settings); var db = mongoClient.GetDatabase("richdizzready"); var collection = db.GetCollection <User>("users"); // Query all users that we have github tokens for var users = await collection.Find(i => i.alias != null).ToListAsync(); foreach (var user in users) { Console.WriteLine($"Processing {user.alias}"); // Read the certificate private key from the executing location // NOTE: This is a hack...Azure Key Vault is best approach...also certPath format will vary by platform var certPath = System.Reflection.Assembly.GetEntryAssembly().Location; certPath = certPath.Substring(0, certPath.LastIndexOf("/bin", StringComparison.CurrentCultureIgnoreCase)) + "/RichdizzReadyKey.pfx"; var certfile = System.IO.File.OpenRead(certPath); var certificateBytes = new byte[certfile.Length]; certfile.Read(certificateBytes, 0, (int)certfile.Length); var cert = new X509Certificate2( certificateBytes, "P@ssword", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); //switchest are important to work in webjob ClientAssertionCertificate cac = new ClientAssertionCertificate("f0dc44ea-333f-4060-9c89-a7730f9b92fe", cert); // Get the access token to the Microsoft Graph using the ClientAssertionCertificate Console.WriteLine("Getting app-only access token to Microsoft Graph"); string authority = "https://login.microsoftonline.com/rzna.onmicrosoft.com/"; // Currently hard-coded to be single-tenant AuthenticationContext authenticationContext = new AuthenticationContext(authority, false); var authenticationResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", cac); var token = authenticationResult.AccessToken; Console.WriteLine("App-only access token retreived"); // Check for a delta token which would indicate if we have ever processed this user if (String.IsNullOrEmpty(user.delta_token)) { // This is a new user so we need to get their sent items folder id and process items string endpoint = $"https://graph.microsoft.com/v1.0/users/{user.alias}/mailfolders"; HttpClient foldersClient = new HttpClient(); foldersClient.DefaultRequestHeaders.Add("Accept", "application/json"); foldersClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var folders = await foldersClient.GetJArray(endpoint, token); // Get the "Sent Items" folder for the user string sentItemsFolderId = String.Empty; foreach (var folder in folders) { if (folder["displayName"].Value <string>() == "Sent Items") { sentItemsFolderId = folder["id"].Value <string>(); break; } } user.delta_token = $"https://graph.microsoft.com/v1.0/users/{user.alias}/mailfolders('{sentItemsFolderId}')/messages/delta?$select=id,body"; } // Prepare the request to recursively get messages in the sent folder HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); client.DefaultRequestHeaders.Add("Prefer", "outlook.body-content-type=\"text\""); // We want body as text JArray messages = new JArray(); var deltaToken = await client.GetJArrayPaged(user.delta_token, messages); // Build up a payload of all messages so we can make just one call into the text analytics service var payload = new Documents(); for (var i = 0; i < messages.Count; i++) { payload.documents.Add(new Document() { id = i, language = "en", text = messages[i].SelectToken("body.content").Value <string>() }); } // Only try to get sentiment if we are processing one or more messages if (payload.documents.Count > 0) { // Get sentiment for all the messages HttpClient sentimentClient = new HttpClient(); sentimentClient.DefaultRequestHeaders.Add("Accept", "application/json"); sentimentClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "03c751a65dcd4263a8cec60be5fdcfa5"); StringContent content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"); using (var resp = await sentimentClient.PostAsync("https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment", content)) { if (resp.IsSuccessStatusCode) { // Add the sentiment as an open extension on the message var sentimentResponse = await resp.Content.ReadAsStringAsync(); var docs = (JArray)JObject.Parse(sentimentResponse)["documents"]; for (var j = 0; j < messages.Count; j++) { string openExtension = @" { '@odata.type':'microsoft.graph.openTypeExtension', 'extensionName':'com.richdizz.sentiment', 'sentiment':'" + docs[j].SelectToken("score").Value <Decimal>() + @"' }" ; client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); StringContent extContent = new StringContent(openExtension, Encoding.UTF8, "application/json"); var extEndpoint = $"https://graph.microsoft.com/v1.0/users/{user.alias}/messages/{messages[j].SelectToken("id").Value<String>()}/extensions"; using (var extResp = await client.PostAsync(extEndpoint, extContent)) { // throw exception if open extension failed if (!extResp.IsSuccessStatusCode) { throw new Exception(await extResp.Content.ReadAsStringAsync()); } } } // Save the ner delta token for the user user.last_run = DateTime.UtcNow; var filter = Builders <User> .Filter.Eq(u => u.alias, user.alias); await collection.ReplaceOneAsync(filter, user); } else { // Do not store the new deltalink...let it reprocess } } } else { // Save the ner delta token for the user user.last_run = DateTime.UtcNow; var filter = Builders <User> .Filter.Eq(u => u.alias, user.alias); await collection.ReplaceOneAsync(filter, user); } Console.WriteLine($"Complete {user.alias}"); } Console.WriteLine($"Processing complete"); }
public SharePointFileManager(IConfiguration Configuration) { // create the HttpClient that is used for our direct REST calls. _CookieContainer = new CookieContainer(); _HttpClientHandler = new HttpClientHandler() { UseCookies = true, AllowAutoRedirect = false, CookieContainer = _CookieContainer }; _Client = new HttpClient(_HttpClientHandler); _Client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); // SharePoint configuration settings. string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"]; string sharePointOdataUri = Configuration["SHAREPOINT_ODATA_URI"]; string sharePointWebname = Configuration["SHAREPOINT_WEBNAME"]; string sharePointNativeBaseURI = Configuration["SHAREPOINT_NATIVE_BASE_URI"]; // ADFS using fed auth string sharePointStsTokenUri = Configuration["SHAREPOINT_STS_TOKEN_URI"]; // Full URI to the STS service we will use to get the initial token. string sharePointRelyingPartyIdentifier = Configuration["SHAREPOINT_RELYING_PARTY_IDENTIFIER"]; // use Fiddler to grab this from an interactive session. Will normally start with urn: string sharePointUsername = Configuration["SHAREPOINT_USERNAME"]; // Service account username. Be sure to add this user to the SharePoint instance. string sharePointPassword = Configuration["SHAREPOINT_PASSWORD"]; // Service account password // SharePoint Online string sharePointAadTenantId = Configuration["SHAREPOINT_AAD_TENANTID"]; string sharePointClientId = Configuration["SHAREPOINT_CLIENT_ID"]; string sharePointCertFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"]; string sharePointCertPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"]; // Basic Auth (SSG API Gateway) string ssgUsername = Configuration["SSG_USERNAME"]; // BASIC authentication username string ssgPassword = Configuration["SSG_PASSWORD"]; // BASIC authentication password // sometimes SharePoint could be using a different username / password. string sharePointSsgUsername = Configuration["SHAREPOINT_SSG_USERNAME"]; string sharePointSsgPassword = Configuration["SHAREPOINT_SSG_PASSWORD"]; if (string.IsNullOrEmpty(sharePointSsgUsername)) { sharePointSsgUsername = ssgUsername; } if (string.IsNullOrEmpty(sharePointSsgPassword)) { sharePointSsgPassword = ssgPassword; } OdataUri = sharePointOdataUri; ServerAppIdUri = sharePointServerAppIdUri; NativeBaseUri = sharePointNativeBaseURI; WebName = sharePointWebname; // ensure the webname has a slash. if (!string.IsNullOrEmpty(WebName) && WebName[0] != '/') { WebName = "/" + WebName; } ApiEndpoint = sharePointOdataUri; // ensure there is a trailing slash. if (!ApiEndpoint.EndsWith("/")) { ApiEndpoint += "/"; } ApiEndpoint += "_api/"; FedAuthValue = null; // Scenario #1 - ADFS (2016) using FedAuth if (!string.IsNullOrEmpty(sharePointRelyingPartyIdentifier) && !string.IsNullOrEmpty(sharePointUsername) && !string.IsNullOrEmpty(sharePointPassword) && !string.IsNullOrEmpty(sharePointStsTokenUri) ) { Authorization = null; var samlST = Authentication.GetStsSamlToken(sharePointRelyingPartyIdentifier, sharePointUsername, sharePointPassword, sharePointStsTokenUri).GetAwaiter().GetResult(); //FedAuthValue = Authentication.GetFedAuth(sharePointOdataUri, samlST, sharePointRelyingPartyIdentifier, _Client, _CookieContainer).GetAwaiter().GetResult(); } // Scenario #2 - SharePoint Online (Cloud) using a Client Certificate else if (!string.IsNullOrEmpty(sharePointAadTenantId) && !string.IsNullOrEmpty(sharePointCertFileName) && !string.IsNullOrEmpty(sharePointCertPassword) && !string.IsNullOrEmpty(sharePointClientId) ) { // add authentication. var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + sharePointAadTenantId); // Create the Client cert. X509Certificate2 cert = new X509Certificate2(sharePointCertFileName, sharePointCertPassword); ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(sharePointClientId, cert); //ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(sharePointServerAppIdUri, clientAssertionCertificate); task.Wait(); authenticationResult = task.Result; Authorization = authenticationResult.CreateAuthorizationHeader(); } else // Scenario #3 - Using an API Gateway with Basic Authentication. The API Gateway will handle other authentication and have different credentials, which may be NTLM { // authenticate using the SSG. string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(sharePointSsgUsername + ":" + sharePointSsgPassword)); Authorization = "Basic " + credentials; } // Authorization header is used for Cloud or Basic API Gateway access if (!string.IsNullOrEmpty(Authorization)) { _Client.DefaultRequestHeaders.Add("Authorization", Authorization); } // Add a Digest header. Needed for certain API operations Digest = GetDigest(_Client).GetAwaiter().GetResult(); if (Digest != null) { _Client.DefaultRequestHeaders.Add("X-RequestDigest", Digest); } // Standard headers for API access _Client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); _Client.DefaultRequestHeaders.Add("OData-Version", "4.0"); }
public JWTHeader(ClientAssertionCertificate credential) { Credential = credential; }
private static string EncodeHeaderToJson(ClientAssertionCertificate credential) { JWTHeaderWithCertificate header = new JWTHeaderWithCertificate(credential); return(JsonHelper.SerializeToJson(header)); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, //PostLogoutRedirectUri = postLogoutRedirectUri, **Will be set dynamically later Resource = resource, Notifications = new OpenIdConnectAuthenticationNotifications() { AuthenticationFailed = (context) => { //This section added to handle scenario where user logs in, but cancels consenting to rights to read directory profile //Sometimes the Consent Framework doesn't kick in so this code is also executed in that sitiation. The user is redirected to the log out page string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + postLogoutRedirectUri; context.HandleResponse(); context.Response.Redirect(context.ProtocolMessage.RedirectUri); return(System.Threading.Tasks.Task.FromResult(0)); }, RedirectToIdentityProvider = (context) => { //Dynamically set RedirectUri & PostLogoutRedirectUri string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl + postLogoutRedirectUri; //context.ProtocolMessage.Prompt = "admin_consent"; return(System.Threading.Tasks.Task.FromResult(0)); }, AuthorizationCodeReceived = async(context) => { var code = context.Code; //ClientCredential credential = new ClientCredential(clientId, clientSecret); ClientAssertionCertificate credential = new ClientAssertionCertificate(clientId, cert); //string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; string tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; //System.Security.Claims.ClaimsPrincipal claimsPrincipal = System.Security.Claims.ClaimsPrincipal.Current; AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantId, new Utils.EFADALTokenCache($"{tenantId}:{userObjectId}")); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, resource); result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, webApiResource); } }, TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = false, //RoleClaimType = "groups", //SaveSigninToken = true } } ); // This makes any middleware defined above this line run before the Authorization rule is applied in web.config app.UseStageMarker(PipelineStage.Authenticate); }
/// <summary> /// Get an access token from Azure AD using client credentials. /// If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each /// </summary> private static async Task <string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate assertionCert) { // // Get an access token from Azure AD using client credentials. // If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each. // AuthenticationResult result = null; int retryCount = 0; bool retry = false; do { retry = false; errorCode = 0; try { // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired. result = await authContext.AcquireTokenAsync(resource, assertionCert); } catch (AdalException ex) { if (ex.ErrorCode == "temporarily_unavailable") { retry = true; retryCount++; Thread.Sleep(3000); } Console.WriteLine( String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n", DateTime.Now.ToString(), ex.ToString(), retry.ToString())); errorCode = -1; } } while ((retry == true) && (retryCount < 3)); return(result.AccessToken); }
/// <summary> /// Gets an Access token for the given resource on behalf of the user in the provided access token /// </summary> /// <param name="userAccessToken">The access token</param> /// <param name="tenantId">Tenant ID</param> /// <param name="resource">Resource ID</param> /// <param name="tokenCachingOptions">Token caching options</param> /// <returns>Authentication result which contains on behalf of token</returns> public async Task <AuthenticationResult> GetAccessTokenForResourceFromUserTokenAsync( string userAccessToken, string tenantId, string resource, TokenCachingOptions tokenCachingOptions) { trace.TraceInformation("Start GetAccessTokenForResourceFromUserTokenAsync"); var aadInstance = GetAADInstance(this.aadClientConfig.AADInstance, tenantId); var exceptions = new List <Exception>(); var thumbprints = this.aadClientConfig.ClientCertificateThumbprintList; var userName = this.GetUserName(); AuthenticationResult result = null; try { if (tokenCachingOptions == TokenCachingOptions.PreferCache && this.TryGetAccessToken(resource, tenantId, userName, out result)) { trace.TraceInformation("Retrieved access token from cache."); return(result); } foreach (var thumbprint in thumbprints) { try { // Construct context var authority = this.aadClientConfig.AADInstance.FormatWithInvariantCulture(tenantId); var context = new AuthenticationContext(authority, false); context.CorrelationId = new Guid(); // Construct client assertion certificate var certificate = this.certificateManager.FindByThumbprint(thumbprint, StoreName.My, StoreLocation.LocalMachine); var clientAssertionCertificate = new ClientAssertionCertificate(this.aadClientConfig.ClientId, certificate); // User Assertion if (string.IsNullOrEmpty(userAccessToken)) { trace.TraceInformation("Calling AcquireTokenAsync without User Assertion."); result = await context.AcquireTokenAsync(resource, clientAssertionCertificate); } else { trace.TraceInformation("Calling AcquireTokenAsync with User Assertion."); var userAssertion = new UserAssertion(TrimBearerToken(userAccessToken)); result = await context.AcquireTokenAsync(resource, clientAssertionCertificate, userAssertion); } trace.TraceInformation($"Requesting access token for Resource: '{resource}', AADInstance: '{aadInstance}', ClientID: '{this.aadClientConfig.ClientId}, CorrelationId: '{context.CorrelationId}'"); if (!string.IsNullOrEmpty(userName)) { // Set Cache this.SetAccessTokenCache(this.graphConfig.GraphResourceId, this.graphConfig.GraphTenant, userName, result); } return(result); } catch (AdalServiceException ex) { // trace.TraceWarning($"AdalServiceException: error code- {ex.ErrorCode}, error message- {ex.Message}"); exceptions.Add(ex); //} //catch (CertificateNotFoundException ex) //{ // exceptions.Add(ex); } catch (Exception ex) { exceptions.Add(ex); break; } } } catch (AdalException exception) { HandleAzureActiveDirectoryClientException(exception); return(null); } throw new AggregateException($"Could not successfully acquire certificate using thumbprints: {string.Join(", ", aadClientConfig.ClientCertificateThumbprintList)}", exceptions); }
/// <summary> /// Initializes a new instance of the <see cref="CertificateAppCredentials"/> class. /// </summary> /// <param name="clientCertificate">Client certificate to be presented for authentication.</param> /// <param name="channelAuthTenant">Optional. The oauth token tenant.</param> /// <param name="customHttpClient">Optional <see cref="HttpClient"/> to be used when acquiring tokens.</param> /// <param name="logger">Optional <see cref="ILogger"/> to gather telemetry data while acquiring and managing credentials.</param> public CertificateAppCredentials(ClientAssertionCertificate clientCertificate, string channelAuthTenant = null, HttpClient customHttpClient = null, ILogger logger = null) : this(clientCertificate, false, channelAuthTenant, customHttpClient, logger) { }
/// <summary>Creates an Azure Active Directory token provider.</summary> /// <param name="authContext">AuthenticationContext for AAD.</param> /// <param name="clientAssertionCertificate">The client assertion certificate credential.</param> /// <returns>The <see cref="TokenProvider" /> for returning Json web token.</returns> public static TokenProvider CreateAadTokenProvider(AuthenticationContext authContext, ClientAssertionCertificate clientAssertionCertificate) { Guard.ArgumentNotNull(nameof(authContext), authContext); Guard.ArgumentNotNull(nameof(clientAssertionCertificate), clientAssertionCertificate); return(new AzureActiveDirectoryTokenProvider(authContext, clientAssertionCertificate)); }
public JWTHeaderWithCertificate(ClientAssertionCertificate credential) : base(credential) { }
public async Task <ActionResult> Upload(HttpPostedFileBase uploadFile, string access, string visibility) { if (uploadFile == null) { return(View("ValidationError", new ValidationErrorModel("please specify a file to upload"))); } string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string authority = string.Format(aadInstance, tenantId); AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserID)); ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate); AuthenticationResult authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(signedInUserID, UserIdentifierType.UniqueId)); string requestUri = nugetPublishServiceBaseAddress.TrimEnd('/') + "/catalog/apiapp"; HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); request.Content = new StreamContent(uploadFile.InputStream); HttpResponseMessage response; try { response = await client.SendAsync(request); } catch (Exception e) { return(View("ServiceError", new ServiceErrorModel(e))); } if (response.IsSuccessStatusCode) { return(View(new UploadModel())); } else { try { JObject publishServiceResponse = JObject.Parse(await response.Content.ReadAsStringAsync()); string type = publishServiceResponse["type"].ToString(); if (type == "ValidationError") { return(View(new UploadModel(publishServiceResponse["errors"].Select((t) => t.ToString())))); } else { string error = publishServiceResponse["error"].ToString(); return(View(new UploadModel(string.Format("uploaded file \"{0}\" contains the following errors \"{1}\"", uploadFile.FileName, error)))); } } catch (Exception e) { return(View("ServiceError", new ServiceErrorModel(e))); } } }
internal static async Task AcquireTokenOnBehalfAndClientCertificateTestAsync(Sts sts) { SetCredential(sts); var context = new AuthenticationContextProxy(sts.Authority, sts.ValidateAuthority); AuthenticationResultProxy result = context.AcquireToken(sts.ValidConfidentialClientId, sts.ValidClientId, sts.ValidDefaultRedirectUri, PromptBehaviorProxy.Auto, sts.ValidUserId); VerifySuccessResult(sts, result); var clientCertificate = new ClientAssertionCertificate(sts.ValidConfidentialClientId, new X509Certificate2(sts.ConfidentialClientCertificateName, sts.ConfidentialClientCertificatePassword)); RecorderJwtId.JwtIdIndex = 5; AuthenticationResultProxy result2 = await context.AcquireTokenAsync(null, clientCertificate, result.AccessToken); VerifyErrorResult(result2, Sts.InvalidArgumentError, "resource"); result2 = await context.AcquireTokenAsync(sts.ValidResource, clientCertificate, null); VerifyErrorResult(result2, Sts.InvalidArgumentError, "userAssertion"); result2 = await context.AcquireTokenAsync(sts.ValidResource, (ClientAssertionCertificate)null, result.AccessToken); RecorderJwtId.JwtIdIndex = 6; VerifyErrorResult(result2, Sts.InvalidArgumentError, "clientCertificate"); result2 = await context.AcquireTokenAsync(sts.ValidResource, clientCertificate, result.AccessToken); VerifySuccessResult(sts, result2, true, false); // Testing cache AuthenticationContextProxy.Delay(2000); // 2 seconds delay AuthenticationResultProxy result3 = await context.AcquireTokenAsync(sts.ValidResource, clientCertificate, result.AccessToken); VerifySuccessResult(sts, result3, true, false); VerifyExpiresOnAreEqual(result2, result3); // Using MRRT in cached token to acquire token for a different resource AuthenticationResultProxy result4 = await context.AcquireTokenAsync(sts.ValidResource2, clientCertificate, result.AccessToken + "x"); VerifySuccessResult(sts, result4, true, false); AuthenticationContextProxy.ClearDefaultCache(); result2 = await context.AcquireTokenAsync(sts.ValidResource + "x", clientCertificate, result.AccessToken); VerifyErrorResult(result2, Sts.InvalidResourceError, null); result2 = await context.AcquireTokenAsync(sts.ValidResource, clientCertificate, result.AccessToken + "x"); VerifyErrorResult(result2, "invalid_grant", "invalid signature"); var invalidClientCredential = new ClientAssertionCertificate(sts.ValidConfidentialClientId.Replace('1', '2'), new X509Certificate2(sts.ConfidentialClientCertificateName, sts.ConfidentialClientCertificatePassword)); RecorderJwtId.JwtIdIndex = 7; result2 = await context.AcquireTokenAsync(sts.ValidResource, invalidClientCredential, result.AccessToken); VerifyErrorResult(result2, Sts.UnauthorizedClient, "not found"); result2 = await context.AcquireTokenAsync(sts.ValidResource, clientCertificate, result.AccessToken); VerifySuccessResult(sts, result2, true, false); // Using MRRT in cached token to acquire token for a different resource result3 = await context.AcquireTokenSilentAsync(sts.ValidResource2, sts.ValidConfidentialClientId); VerifyErrorResult(result3, AdalError.FailedToAcquireTokenSilently, null); // Using MRRT in cached token to acquire token for a different resource result3 = await context.AcquireTokenSilentAsync(sts.ValidResource2, clientCertificate, UserIdentifier.AnyUser); VerifySuccessResult(sts, result3, true, false); }
/** * public static string GetAADToken(string resourceName, string clientSecretKey) * { * * * //Encrypted client guid for the AD App AxScmService * string clientId = ""; * * * //token for AxScmService AD App for connecting endpoints * string appToken = ""; * * //Login Authority for ADAL * string authorityUri = "https://login.windows.net/{0}"; * * //Resource for which AAD token has to be acquired * string resourceUri = "http://local.microsoft.onmicrosoft.com/pricing"; * * string authority = string.Format(authorityUri, appToken); * * * //Encrypted Secret key for the AxScmService Ad App * // string clientSecretKey = "test"; * * string clientSecret = ""; * //keyvault.GetSecretString(clientSecretKey); * * * * AuthenticationResult _currentToken = null; * * * var authContext = new AuthenticationContext(authority); * _currentToken = GetAccessToken(authority, resourceUri, string.Empty, new ClientCredential(clientId, clientSecret)).GetAwaiter().GetResult(); * * return _currentToken.AccessToken; * } * **/ private static async Task <string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate clientCredential) { var context = new AuthenticationContext(authority, null); var result = await context.AcquireTokenAsync(resource, clientCredential); return(result.AccessToken); }
private KeyVaultClient InitializeClient() { _clientAssertionCertificate = new ClientAssertionCertificate(_configuration.ClientId, _configuration.Certificate); return(new KeyVaultClient(GetTokenAsync)); }
static void Main(string[] args) { string environment = null, installerArgs1 = null, installerArgs2 = null; int argsLength = args.Length; if (argsLength < 3) { Console.WriteLine("Insufficient arguements passed"); Console.ReadLine(); return; } else { environment = args[0]; installerArgs1 = args[1]; installerArgs2 = args[2]; } // var keyClient = new KeyVaultClient((authority, resource, scope) => { var authenticationContext = new AuthenticationContext(authority, null); X509Certificate2 certificate; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, "0910BE605954E8E055DDAAFC90B22E431294F170", false); if (certificateCollection == null || certificateCollection.Count == 0) { throw new Exception("Certificate not installed in the store"); } certificate = certificateCollection[0]; } finally { store.Close(); } var clientAssertionCertificate = new ClientAssertionCertificate(ConfigurationManager.AppSettings["KeyVault.Authentication.ClientId"], certificate); return(GetAccessToken(authority, resource, scope, clientAssertionCertificate)); }); var key = ""; if (environment.ToLower().Equals("test")) { key = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "testwebADpwd").GetAwaiter().GetResult().Value; } else if (environment.ToLower().Equals("dev")) { key = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "testdADpwd").GetAwaiter().GetResult().Value; } else if (environment.ToLower().Equals("prod")) { key = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "testpADpwd").GetAwaiter().GetResult().Value; } ReplacePwd(key); Console.WriteLine("Press enter to continue"); Console.ReadLine(); RunInstaller(installerArgs1, installerArgs2); MoveOneBoxConfigBack(key); //var key1 = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "").GetAwaiter().GetResult().Value; //var key3 = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "").GetAwaiter().GetResult().Value; //var key2 = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "").GetAwaiter().GetResult().Value; //var key4 = keyClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVault.Vault.Address"], "").GetAwaiter().GetResult().Value; //Console.WriteLine("The values are : " + key0 + ", " + key2 + ", " + key3 + ", " + key4); //Console.ReadLine(); }
static void Main(string[] args) { KeyBundle keyBundle = null; // The key specification and attributes SecretBundle secret = null; CertificateBundle certificateBundle = null; string keyName = string.Empty; string secretName = string.Empty; string certificateName = string.Empty; string certificateCreateName = string.Empty; inputValidator = new InputValidator(args); ServiceClientTracing.AddTracingInterceptor(new ConsoleTracingInterceptor()); ServiceClientTracing.IsEnabled = inputValidator.GetTracingEnabled(); var clientId = ConfigurationManager.AppSettings["AuthClientId"]; var cerificateThumbprint = ConfigurationManager.AppSettings["AuthCertThumbprint"]; var certificate = FindCertificateByThumbprint(cerificateThumbprint); var assertionCert = new ClientAssertionCertificate(clientId, certificate); keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback( (authority, resource, scope) => GetAccessToken(authority, resource, scope, assertionCert)), new InjectHostHeaderHttpMessageHandler()); // SECURITY: DO NOT USE IN PRODUCTION CODE; FOR TEST PURPOSES ONLY //ServicePointManager.ServerCertificateValidationCallback += ( sender, cert, chain, sslPolicyErrors ) => true; List <KeyOperationType> successfulOperations = new List <KeyOperationType>(); List <KeyOperationType> failedOperations = new List <KeyOperationType>(); foreach (var operation in inputValidator.GetKeyOperations()) { try { Console.Out.WriteLine("\n\n {0} is in process ...", operation); switch (operation) { //case KeyOperationType.CREATE_KEY: // keyBundle = CreateKey(keyBundle, out keyName); // break; //case KeyOperationType.IMPORT_KEY: // keyBundle = ImportKey(out keyName); // break; //case KeyOperationType.GET_KEY: // keyBundle = GetKey(keyBundle); // break; //case KeyOperationType.LIST_KEYVERSIONS: // ListKeyVersions(keyName); // break; //case KeyOperationType.UPDATE_KEY: // keyBundle = UpdateKey(keyName); // break; //case KeyOperationType.DELETE_KEY: // DeleteKey(keyName); // break; //case KeyOperationType.BACKUP_RESTORE: // keyBundle = BackupRestoreKey(keyName); // break; //case KeyOperationType.SIGN_VERIFY: // SignVerify(keyBundle); // break; //case KeyOperationType.ENCRYPT_DECRYPT: // EncryptDecrypt(keyBundle); // break; //case KeyOperationType.ENCRYPT: // Encrypt(keyBundle); // break; //case KeyOperationType.DECRYPT: // Decrypt(keyBundle); // break; //case KeyOperationType.WRAP_UNWRAP: // WrapUnwrap(keyBundle); // break; //case KeyOperationType.CREATE_SECRET: // secret = CreateSecret(out secretName); // break; //case KeyOperationType.GET_SECRET: // secret = GetSecret(secret.Id); // break; //case KeyOperationType.LIST_SECRETS: // ListSecrets(); // break; //case KeyOperationType.DELETE_SECRET: // secret = DeleteSecret(secretName); // break; case KeyOperationType.CREATE_CERTIFICATE: certificateBundle = CreateCertificate(out certificateCreateName); break; case KeyOperationType.IMPORT_CERTIFICATE: certificateBundle = ImportCertificate(out certificateName); break; case KeyOperationType.EXPORT_CERTIFICATE: var x509Certificate = ExportCertificate(certificateBundle); break; case KeyOperationType.LIST_CERTIFICATEVERSIONS: ListCertificateVersions(certificateName); break; case KeyOperationType.LIST_CERTIFICATES: ListCertificates(); break; case KeyOperationType.DELETE_CERTIFICATE: certificateBundle = DeleteCertificate(certificateName); certificateBundle = DeleteCertificate(certificateCreateName); break; } successfulOperations.Add(operation); } catch (KeyVaultErrorException exception) { // The Key Vault exceptions are logged but not thrown to avoid blocking execution for other commands running in batch Console.Out.WriteLine("Operation failed: {0}", exception.Body.Error.Message); failedOperations.Add(operation); } } Console.Out.WriteLine("\n\n---------------Successful Key Vault operations:---------------"); foreach (KeyOperationType type in successfulOperations) { Console.Out.WriteLine("\t{0}", type); } if (failedOperations.Count > 0) { Console.Out.WriteLine("\n\n---------------Failed Key Vault operations:---------------"); foreach (KeyOperationType type in failedOperations) { Console.Out.WriteLine("\t{0}", type); } } Console.Out.WriteLine(); Console.Out.Write("Press enter to continue . . ."); Console.In.Read(); }
/// <summary> /// Get access token using asymmetric key associated with an Azure AD application. /// </summary> /// <param name="resource">Resource to access.</param> /// <param name="authority">Authority where resource is.</param> /// <returns></returns> public override async Task <AppAuthenticationResult> GetAuthResultAsync(string resource, string authority, CancellationToken cancellationToken = default(CancellationToken)) { // If authority is not specified and tenantId was present in connection string, create it using azureAdInstance and tenantId. if (string.IsNullOrWhiteSpace(authority) && !string.IsNullOrWhiteSpace(_tenantId)) { authority = $"{_azureAdInstance}{_tenantId}"; } List <X509Certificate2> certs = null; switch (_certificateIdentifierType) { case CertificateIdentifierType.KeyVaultCertificateSecretIdentifier: // Get certificate for the given Key Vault secret identifier try { var keyVaultCert = await _keyVaultClient.GetCertificateAsync(_certificateIdentifier, cancellationToken); certs = new List <X509Certificate2>() { keyVaultCert }; // If authority is still not specified, create it using azureAdInstance and tenantId. Tenant ID comes from Key Vault access token. if (string.IsNullOrWhiteSpace(authority)) { _tenantId = _keyVaultClient.PrincipalUsed.TenantId; authority = $"{_azureAdInstance}{_tenantId}"; } } catch (Exception exp) { throw new AzureServiceTokenProviderException(ConnectionString, resource, authority, $"{AzureServiceTokenProviderException.KeyVaultCertificateRetrievalError} {exp.Message}"); } break; case CertificateIdentifierType.SubjectName: case CertificateIdentifierType.Thumbprint: // Get certificates for the given thumbprint or subject name. bool isThumbprint = _certificateIdentifierType == CertificateIdentifierType.Thumbprint; certs = CertificateHelper.GetCertificates(_certificateIdentifier, isThumbprint, _storeLocation); if (certs == null || certs.Count == 0) { throw new AzureServiceTokenProviderException(ConnectionString, resource, authority, AzureServiceTokenProviderException.LocalCertificateNotFound); } break; } // If multiple certs were found, use in order of most recently created. // This helps if old cert is rolled over, but not removed. certs = certs.OrderByDescending(p => p.NotBefore).ToList(); // To hold reason why token could not be acquired per cert tried. Dictionary <string, string> exceptionDictionary = new Dictionary <string, string>(); foreach (X509Certificate2 cert in certs) { if (!string.IsNullOrEmpty(cert.Thumbprint)) { try { ClientAssertionCertificate certCred = new ClientAssertionCertificate(_clientId, cert); var authResult = await _authenticationContext.AcquireTokenAsync(authority, resource, certCred).ConfigureAwait(false); var accessToken = authResult?.AccessToken; if (accessToken != null) { PrincipalUsed.CertificateThumbprint = cert.Thumbprint; PrincipalUsed.IsAuthenticated = true; PrincipalUsed.TenantId = AccessToken.Parse(accessToken).TenantId; return(authResult); } } catch (Exception exp) { // If token cannot be acquired using a cert, try the next one exceptionDictionary[cert.Thumbprint] = exp.Message; } } } // Could not acquire access token, throw exception string message = $"Tried {certs.Count} certificate(s). {AzureServiceTokenProviderException.GenericErrorMessage}"; // Include exception details for each cert that was tried int count = 1; foreach (string thumbprint in exceptionDictionary.Keys) { message += Environment.NewLine + $"Exception for cert #{count} with thumbprint {thumbprint}: {exceptionDictionary[thumbprint]}"; count++; } throw new AzureServiceTokenProviderException(ConnectionString, resource, authority, message); }
public async Task <IAuthenticationResultAdapter> AcquireTokenAsync(string resource, ClientAssertionCertificate cac) { return((await _context.AcquireTokenAsync(resource, cac)).ToAdapterResult()); }
public async Task ConfidentialClientWithX509Test() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); var certificate = new ClientAssertionCertificate(TestConstants.DefaultClientId, new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword)); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" } } }); AuthenticationResult result = await context.AcquireTokenByAuthorizationCodeAsync("some-code", TestConstants.DefaultRedirectUri, certificate, TestConstants.DefaultResource); Assert.IsNotNull(result.AccessToken); try { await context.AcquireTokenByAuthorizationCodeAsync(null, TestConstants.DefaultRedirectUri, certificate, TestConstants.DefaultResource); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "authorizationCode"); } try { await context.AcquireTokenByAuthorizationCodeAsync(string.Empty, TestConstants.DefaultRedirectUri, certificate, TestConstants.DefaultResource); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "authorizationCode"); } try { // Send null for redirect await context.AcquireTokenByAuthorizationCodeAsync("some-code", null, certificate, TestConstants.DefaultResource); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "redirectUri"); } try { await context.AcquireTokenByAuthorizationCodeAsync("some-code", TestConstants.DefaultRedirectUri, (ClientAssertionCertificate)null, TestConstants.DefaultResource); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "clientCertificate"); } }
private async static Task doStuffInOffice365() { //set the authentication context //you can do multi-tenant app-only, but you cannot use /common for authority...must get tenant ID string authority = "https://login.windows.net/rzna.onmicrosoft.com/"; AuthenticationContext authenticationContext = new AuthenticationContext(authority, false); //read the certificate private key from the executing location //NOTE: This is a hack...Azure Key Vault is best approach var certPath = System.Reflection.Assembly.GetExecutingAssembly().Location; certPath = certPath.Substring(0, certPath.LastIndexOf('\\')) + "\\O365AppOnly_private.pfx"; var certfile = System.IO.File.OpenRead(certPath); var certificateBytes = new byte[certfile.Length]; certfile.Read(certificateBytes, 0, (int)certfile.Length); var cert = new X509Certificate2( certificateBytes, PRIVATE_KEY_PASSWORD, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); //switchest are important to work in webjob ClientAssertionCertificate cac = new ClientAssertionCertificate(CLIENT_ID, cert); //get the access token to SharePoint using the ClientAssertionCertificate Console.WriteLine("Getting app-only access token to SharePoint Online"); var authenticationResult = await authenticationContext.AcquireTokenAsync("https://rzna.sharepoint.com/", cac); var token = authenticationResult.AccessToken; Console.WriteLine("App-only access token retreived"); //perform a post using the app-only access token to add SharePoint list item in Attendee list HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); //create the item payload for saving into SharePoint var itemPayload = new { __metadata = new { type = "SP.Data.SampleListItem" }, Title = String.Format("Created at {0} {1} from app-only AAD token", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()) }; //setup the client post HttpContent content = new StringContent(JsonConvert.SerializeObject(itemPayload)); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose"); Console.WriteLine("Posting ListItem to SharePoint Online"); using (HttpResponseMessage response = await client.PostAsync("https://rzna.sharepoint.com/_api/web/Lists/getbytitle('Sample')/items", content)) { if (!response.IsSuccessStatusCode) { Console.WriteLine("ERROR: SharePoint ListItem Creation Failed!"); } else { Console.WriteLine("SharePoint ListItem Created!"); } } }
public async Task AcquireTokenOnBehalfAndClientCertificateCredentialTest() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); string accessToken = "some-access-token"; TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", accessToken, DateTimeOffset.UtcNow) }; ClientAssertionCertificate clientCredential = new ClientAssertionCertificate(TestConstants.DefaultClientId, new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword)); try { await context.AcquireTokenAsync(null, clientCredential, new UserAssertion(accessToken)); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "resource"); } try { await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, null); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "userAssertion"); } try { await context.AcquireTokenAsync(TestConstants.DefaultResource, (ClientAssertionCertificate)null, new UserAssertion(accessToken)); } catch (ArgumentNullException exc) { Assert.AreEqual(exc.ParamName, "clientCertificate"); } HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Post, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"access_token\":\"some-other-token\"}") }, PostData = new Dictionary <string, string>() { { "client_id", TestConstants.DefaultClientId }, { "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer" } } }); var result = await context.AcquireTokenAsync(TestConstants.AnotherResource, clientCredential, new UserAssertion(accessToken)); Assert.IsNotNull(result.AccessToken); }
/// <summary> /// /// </summary> /// <param name="configurtaion"></param> public static void GetCert(IConfiguration configurtaion) { var clientAssertionCertPfx = CertificateHelper.FindCertificateByThumbprint(configurtaion["General:KeyVaultCertThumbPrint"].ToString()); AssertionCert = new ClientAssertionCertificate(configurtaion["General:KeyVaultClientID"], clientAssertionCertPfx); }
protected override async Task <IAuthenticationResult> AuthenticateResourceAsync(string resource) { IAuthenticationResult authenticationResult = null; var adalServiceInfo = this.ServiceInfo as AdalServiceInfo; ClientAssertionCertificate clientAssertionCertificate = null; ClientCredential clientCredential = this.GetClientCredentialForAuthentication(); var userIdentifier = this.GetUserIdentifierForAuthentication(); try { if (adalServiceInfo != null && adalServiceInfo.ClientCertificate != null) { clientAssertionCertificate = new ClientAssertionCertificate(this.serviceInfo.AppId, adalServiceInfo.ClientCertificate); authenticationResult = await this.authenticationContextWrapper.AcquireTokenSilentAsync(resource, clientAssertionCertificate, userIdentifier); } else if (clientCredential != null) { authenticationResult = await this.authenticationContextWrapper.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier); } else { authenticationResult = await this.authenticationContextWrapper.AcquireTokenSilentAsync(resource, this.serviceInfo.AppId); } } catch (Exception) { // If an exception happens during silent authentication try interactive authentication. } if (authenticationResult != null) { return(authenticationResult); } try { var redirectUri = new Uri(this.ServiceInfo.ReturnUrl); if (clientAssertionCertificate != null || clientCredential != null) { var webAuthenticationUi = this.serviceInfo.WebAuthenticationUi ?? new FormsWebAuthenticationUi(); var requestUri = new Uri(this.OAuthRequestStringBuilder.GetAuthorizationCodeRequestUrl()); var authenticationResponseValues = await webAuthenticationUi.AuthenticateAsync( requestUri, redirectUri); OAuthErrorHandler.ThrowIfError(authenticationResponseValues); string code; if (authenticationResponseValues != null && authenticationResponseValues.TryGetValue("code", out code)) { if (clientAssertionCertificate != null) { authenticationResult = await this.authenticationContextWrapper.AcquireTokenByAuthorizationCodeAsync( code, redirectUri, clientAssertionCertificate, resource); } else { authenticationResult = await this.authenticationContextWrapper.AcquireTokenByAuthorizationCodeAsync( code, redirectUri, clientCredential, resource); } } } else { authenticationResult = this.authenticationContextWrapper.AcquireToken( resource, this.ServiceInfo.AppId, redirectUri, PromptBehavior.Auto, userIdentifier); } } catch (Exception exception) { AuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { AuthenticationExceptionHelper.HandleAuthenticationException(null); } return(authenticationResult); }
private async Task RunAsync(CancellationToken cancellationToken) { var context = new AuthenticationContext("https://login.microsoftonline.com/88c25c7a-38aa-45d5-bd8d-e939dd68c4f2"); var queue = new QueueClient(ConfigurationManager.AppSettings["connectionString"], "2009v13-990EZ"); RestClient rest = new RestClient("http://s3.amazonaws.com/irs-form-990/"); DateTimeOffset hasExpired = DateTimeOffset.MinValue; string accessToken = null; queue.RegisterMessageHandler(async(msg, token) => { var url = Encoding.UTF8.GetString(msg.Body); string version = null; try { var resp = rest.Get(new RestRequest(url)); XDocument doc = XDocument.Parse(resp.Content.Replace("xsi:schemaLocation=\"http://www.irs.gov/efile\"", "").Replace( "xmlns=\"http://www.irs.gov/efile\"", "").Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "").Replace("\r\n", "")); version = doc.Root.Attribute("returnVersion").Value.Replace(".", ""); var rtn = doc.Element("Return"); PerformancePlanOrReport report = new PerformancePlanOrReport(); report.OtherInformation = "FORM-990"; report.Name = rtn.Element("ReturnHeader").Element("Filer").Element("Name").Element("BusinessNameLine1").Value + "- FORM 990 " + rtn.Element("ReturnHeader").Element("TaxPeriodEndDate").Value; report.Type = PerformancePlanOrReportType.Performance_Report; report.AdministrativeInformation = new AdministrativeInformationType(); report.AdministrativeInformation.EndDate = rtn.Element("ReturnHeader").Element("TaxPeriodEndDate").Value; report.AdministrativeInformation.Identifier = Guid.NewGuid().ToString(); report.AdministrativeInformation.Source = "http://s3.amazonaws.com/irs-form-990/" + url; report.AdministrativeInformation.PublicationDate = rtn.Element("ReturnHeader").Element("Timestamp").Value; report.Description = rtn.Element("ReturnHeader").Element("ReturnType").Value; report.StrategicPlanCore = new StrategicPlanCore(); report.StrategicPlanCore.Mission = new Mission(); report.StrategicPlanCore.Mission.Description = rtn.Element("ReturnData").Element("IRS990EZ").Element("PrimaryExemptPurpose").Value; report.StrategicPlanCore.Mission.Identifier = Guid.NewGuid().ToString(); var stakeholders = rtn.Element("ReturnData").Element("IRS990EZ" ).Elements("OfficerDirectorTrusteeKeyEmpl").Select(o => new Stakeholder() { StakeholderTypeType = StakeholderStakeholderTypeType.Person, StakeholderTypeTypeSpecified = true, Name = o.Element("PersonName").Value, Role = new Core.Two.Role[] { new Core.Two.Role() { RoleType = new RoleType[] { RoleType.Performer }, Name = o.Element("Title").Value, Description = "Title" } } }).ToArray(); report.StrategicPlanCore.Organization = new Organization[] { new Organization() { Identifier = rtn.Element("ReturnHeader").Element("Filer").Element("EIN").Value, Acronym = rtn.Element("ReturnHeader").Element("Filer").Element("NameControl").Value, Name = rtn.Element("ReturnHeader").Element("Filer").Element("Name").Element("BusinessNameLine1").Value, Stakeholder = stakeholders } }; report.StrategicPlanCore.Goal = new Goal[] { new Goal() { Identifier = "UID-EmployeeHours", Name = "Employee Hours and Compensation", SequenceIndicator = "2", Objective = rtn.Element("ReturnData").Element("IRS990EZ").Elements("OfficerDirectorTrusteeKeyEmpl").Select(e => new ObjectiveType() { Identifier = Guid.NewGuid().ToString(), Name = e.Element("PersonName").Value, Description = e.Element("Title").Value, PerformanceIndicator = new PerformanceIndicator[] { new PerformanceIndicator() { PerformanceIndicatorType = PerformanceIndicatorTypeType.Quantitative, PerformanceIndicatorTypeSpecified = true, Identifier = Guid.NewGuid().ToString(), MeasurementInstance = new MeasurementInstance[] { new MeasurementInstance() { ActualResult = new ActualResult[] { new ActualResult() { Description = "Average Hours Per Week", NumberOfUnits = e.Element("AvgHoursPerWkDevotedToPosition").Value } } }, new MeasurementInstance() { ActualResult = new ActualResult[] { new ActualResult() { Description = "Compensation", NumberOfUnits = e.Element("Compensation").Value } } } } } } }).ToArray(), Stakeholder = stakeholders } }; RestClient client = new RestClient("https://stratml.services/api/PartTwo"); var request = new RestRequest(Method.POST) { RequestFormat = DataFormat.Xml }; request.AddParameter("application/xml", report.Serialize(), ParameterType.RequestBody); var response = await client.ExecuteTaskAsync(request, token); } catch (Exception ex) { if (version != null) { var cerificateThumbprint = CloudConfigurationManager.GetSetting("KeyVaultAuthCertThumbprint"); var authenticationClientId = CloudConfigurationManager.GetSetting("KeyVaultAuthClientId"); var cert = CertificateHelper.FindCertificateByThumbprint(cerificateThumbprint); var assertionCert = new ClientAssertionCertificate(authenticationClientId, cert); string connectionStirng = null; string subscriptionID = null; using (var vault = new KeyVaultClient(async(authority, resource, scope) => { var authenticationContext = new AuthenticationContext(authority); var result = await authenticationContext.AcquireTokenAsync(resource, assertionCert); return(result.AccessToken); })) { connectionStirng = (await vault.GetSecretAsync("https://stratml-keys.vault.azure.net/secrets/ServiceBusConnectionString/", cancellationToken)).Value; subscriptionID = (await vault.GetSecretAsync("https://stratml-keys.vault.azure.net/secrets/SubscriptionID/", cancellationToken)).Value; } if (hasExpired < DateTime.UtcNow.AddMinutes(-2)) { var loginContext = new AuthenticationContext("https://login.microsoftonline.com/88c25c7a-38aa-45d5-bd8d-e939dd68c4f2"); var result = await loginContext.AcquireTokenAsync( "https://management.core.windows.net/", assertionCert ); accessToken = result.AccessToken; hasExpired = result.ExpiresOn; } TokenCredentials creds = new TokenCredentials(accessToken); using (ServiceBusManagementClient sb = new ServiceBusManagementClient(creds) { SubscriptionId = subscriptionID }) { await sb.Queues.CreateOrUpdateAsync("stratml", "stratml", version + "-errors", new SBQueue()); var q = new QueueClient(connectionStirng, version + "-errors"); await q.SendAsync(new Message(Encoding.UTF8.GetBytes($"{{'url':'{url}','ex':'{ex.ToString()}'}}"))); await q.CloseAsync(); } } } }, new MessageHandlerOptions(evt => Task.FromException(evt.Exception)) { MaxConcurrentCalls = 4, AutoComplete = true }); while (!cancellationToken.IsCancellationRequested) { await Task.Delay(60000, cancellationToken); } await queue.CloseAsync(); }
public static async Task <AuthenticationResult> GetToken(OAuthContext oAuthContext) { // Get OAuth token using client credentials string tenantName = oAuthContext.tenantName; if (_authenticationContext == null) { _authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(oAuthContext.authUrl + "/" + tenantName, _tokenCache); } AuthenticationResult authenticationResult = null; if (oAuthContext.ObtainUserConsent) { // We need to get user consent FormGetUserPermission formGetPermission = new FormGetUserPermission(oAuthContext); if (formGetPermission.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string code = formGetPermission.Code; // When we get our token, it will be cached in the TokenCache, so next time the silent calls will work if (oAuthContext.cert == null) { ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey); authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCred); } else { ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert); authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCert); } } return(authenticationResult); } if (oAuthContext.isNativeApplication) { if (oAuthContext.adminConsent) { authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource, oAuthContext.clientId, new Uri(oAuthContext.redirectUrl), new PlatformParameters(PromptBehavior.Always), UserIdentifier.AnyUser, "prompt=admin_consent"); } else { authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource, oAuthContext.clientId, new Uri(oAuthContext.redirectUrl), new PlatformParameters(PromptBehavior.Always)); } } else { if (!String.IsNullOrEmpty(oAuthContext.userId)) { // We have the UserId for the mailbox we want to access, so we'll try to get a token silently (we should have a cached token) try { if (oAuthContext.cert == null) { ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey); authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCred, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId)); } else { ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert); authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCert, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId)); } return(authenticationResult); } catch (Exception ex) { _lastError = ex; } } } return(authenticationResult); }
private Task<IAuthenticationResult> AuthenticateUsingCertificate(AdalServiceInfo adalServiceInfo, string resource) { var returnUri = new Uri(this.ServiceInfo.ReturnUrl); var clientAssertionCertificate = new ClientAssertionCertificate(adalServiceInfo.AppId, adalServiceInfo.ClientCertificate); return this.authenticationContextWrapper.AcquireTokenByAuthorizationCodeAsync( this.authenticationCode, returnUri, clientAssertionCertificate, resource); }
private Task<IAuthenticationResult> AuthenticateUsingCertificate(AdalServiceInfo adalServiceInfo, string refreshToken) { var clientAssertionCertificate = new ClientAssertionCertificate(adalServiceInfo.AppId, adalServiceInfo.ClientCertificate); return this.authenticationContextWrapper.AcquireTokenByRefreshTokenAsync( refreshToken, clientAssertionCertificate, adalServiceInfo.ServiceResource); }