public async Task <ActionResult> PublishCalendars(List <UserDetails> users) { //We create separate lists for users who will have a published calendar, //and those who will not have one (terming it unpublished) List <UserDetails> usersPublished = new List <UserDetails>(); List <UserDetails> usersUnpublished = new List <UserDetails>(); foreach (var item in users) { if (item.PublishedCal == true) { usersPublished.Add(item); } else { usersUnpublished.Add(item); } } //Powershell it //Connect to Exchange Online Using Remote PowerShell //http://technet.microsoft.com/en-US/library/jj984289.aspx WSManConnectionInfo o365Connection = Office365Remoting.getOffice365Connection(); //Enable calendar for the "checked" users Office365Remoting.enablePublishedCalendars(usersPublished, o365Connection); //Disable for the "unchecked" users Office365Remoting.disablePublishedCalendars(usersUnpublished, o365Connection); //Retrieve the urls for the users who have a public calendar users = Office365Remoting.getCalendarUrls(usersPublished, o365Connection); //When presenting the view we want to display all users //Users without a public calendar on the lower part of the list users.AddRange(usersUnpublished); //If we've come this far we would like to add the values to our directory string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; // Get a token for calling the Windows Azure Active Directory Graph AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId)); ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey); AuthenticationResult assertionCredential = authContext.AcquireToken(GraphUrl, credential); string authHeader = assertionCredential.CreateAuthorizationHeader(); string appObjectId = await DirectoryExtensions.getAppObjectId(tenantId, authHeader); string extensionName = string.Empty; //Check if PublishedCalendar extension is registered by trying to get the id extensionName = await DirectoryExtensions.checkExtensionRegistered(tenantId, authHeader, appObjectId, "PublishedCalendarUrl"); if (extensionName == "false") { extensionName = await DirectoryExtensions.registerExtension(tenantId, authHeader, appObjectId, "PublishedCalendarUrl"); } foreach (var user in users) { await DirectoryExtensions.setExtensionValue(tenantId, authHeader, user.userPrincipalName, extensionName, user.PublishedCalendarUrl); } return(View(users)); }
public async Task <AddRemoveRequestSAPResponse> SendSAPRequest(List <ContractAmendmentRequestARDetailsDTO> contractAmendmentRequestARDetailsDTOList) { try { _addremoveRequest = new AddRemoveRequestCompositeEntity(); _addremoveRequest.ContractAddRemoveRequestDetails = contractAmendmentRequestARDetailsDTOList; //Service SAPRFCService = new Service(); //string strURL = System.Configuration.ConfigurationManager.AppSettings["ContractManagementSAPURL"]; AddRemoveRequestSAPResponse addremoveResp = null; ZLW_AGR_ADD_REM_CONTRACT[] sapAddRemoveProductData = null; ZLW_OUT_GENERAL_DATA[] sapOutput = null; BAPIRET2[] messageOutput = null; int numberOfProducts = contractAmendmentRequestARDetailsDTOList.Count; sapAddRemoveProductData = new ZLW_AGR_ADD_REM_CONTRACT[numberOfProducts]; sapOutput = new ZLW_OUT_GENERAL_DATA[0]; messageOutput = new BAPIRET2[numberOfProducts]; int count = 0; foreach (ContractAmendmentRequestARDetailsDTO addRemoveProduct in contractAmendmentRequestARDetailsDTOList) { sapAddRemoveProductData[count] = new ZLW_AGR_ADD_REM_CONTRACT(); messageOutput[count] = new BAPIRET2(); if (addRemoveProduct.Action == 1) { sapAddRemoveProductData[count].ACTN_CODE = "A"; } else { sapAddRemoveProductData[count].ACTN_CODE = "R"; } sapAddRemoveProductData[count].VBELN = addRemoveProduct.ContractNumber; sapAddRemoveProductData[count].MATNR = addRemoveProduct.LicensableID; sapAddRemoveProductData[count].ITEM_CATEG = addRemoveProduct.BillingTypeCode; count++; } Z_V_OSW_R_ADD_REM_CONTRACTRequest request = new Z_V_OSW_R_ADD_REM_CONTRACTRequest(); request.In_Agr_Add_Rem_Contract_In = sapAddRemoveProductData; request.Out_General_Data_In = sapOutput; request.Out_Messages_In = messageOutput; // HttpConnector client = new HttpConnector(); HttpClient httpClient = new HttpClient(); var baseUri = "https://saptstws.trafficmanager.net/MST/MSSDOEMCONTRACT/"; httpClient.BaseAddress = new Uri(baseUri); string token = ""; AuthenticationResult accessToken = await GetToken(); token = accessToken.AccessToken; // httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "c55ddee3fc0643eab5534af29776892c"); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("Authorization", accessToken.CreateAuthorizationHeader()); httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "c55ddee3fc0643eab5534af29776892c"); httpClient.DefaultRequestHeaders.Add("Ocp-Apim-trace", "true"); httpClient.DefaultRequestHeaders.Add("X-CorrelationId", Guid.NewGuid().ToString()); var myContent = JsonConvert.SerializeObject(request); var buffer = System.Text.Encoding.UTF8.GetBytes(myContent); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await httpClient.PostAsync("api/Contracts/AddOrRemove", byteContent); //var response = await httpClient.PostAsync("api/Contracts/AddOrRemove/", request, new JsonMediaTypeFormatter()); var responseContent = await response.Content.ReadAsStringAsync(); Z_V_Osw_R_Add_Rem_Contract_RFCReturn RFCStrOutput = JsonConvert.DeserializeObject <Z_V_Osw_R_Add_Rem_Contract_RFCReturn>(responseContent); addremoveResp = ProcessSAPResponse(RFCStrOutput); addremoveResp.SAPResponse = SerializeObject(RFCStrOutput, typeof(Z_V_Osw_R_Add_Rem_Contract_RFCReturn)); return(addremoveResp); } catch (Exception ex) { // _logger.LogError(ex, ex.Message); throw ex; } }
public void AuthorizeRequest(Action <string, string> authTokenSetter) { var header = _result.CreateAuthorizationHeader(); authTokenSetter(_result.AccessTokenType, _result.AccessToken); }
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/"; // 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"); }
private void SetupDynamics(IServiceCollection services) { string redisServer = Configuration["REDIS_SERVER"]; string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; string aadTenantId = Configuration["DYNAMICS_AAD_TENANT_ID"]; string serverAppIdUri = Configuration["DYNAMICS_SERVER_APP_ID_URI"]; string clientKey = Configuration["DYNAMICS_CLIENT_KEY"]; string clientId = Configuration["DYNAMICS_CLIENT_ID"]; string ssgUsername = Configuration["SSG_USERNAME"]; string ssgPassword = Configuration["SSG_PASSWORD"]; if (string.IsNullOrEmpty(redisServer)) { services.AddDistributedRedisCache(options => { options.Configuration = redisServer; }); } AuthenticationResult authenticationResult = null; // authenticate using ADFS. if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; } services.AddSingleton(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) => { ServiceClientCredentials serviceClientCredentials = null; if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length); serviceClientCredentials = new TokenCredentials(token); } else { serviceClientCredentials = new BasicAuthenticationCredentials() { UserName = ssgUsername, Password = ssgPassword }; } IDynamicsClient client = new DynamicsClient(new Uri(Configuration["DYNAMICS_ODATA_URI"]), serviceClientCredentials); // set the native client URI if (string.IsNullOrEmpty(Configuration["DYNAMICS_NATIVE_ODATA_URI"])) { client.NativeBaseUri = new Uri(Configuration["DYNAMICS_ODATA_URI"]); } else { client.NativeBaseUri = new Uri(Configuration["DYNAMICS_NATIVE_ODATA_URI"]); } return(client); })); Interfaces.Microsoft.Dynamics.CRM.System context = new Interfaces.Microsoft.Dynamics.CRM.System(new Uri(Configuration["DYNAMICS_ODATA_URI"])); // determine if we have a SSG connection. if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { context.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add( "Authorization", authenticationResult.CreateAuthorizationHeader()); } else { // authenticate using the SSG. string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ssgUsername + ":" + ssgPassword)); context.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add( "Authorization", "Basic " + credentials); } services.AddSingleton <Interfaces.Microsoft.Dynamics.CRM.System>(context); // add SharePoint. string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"]; string sharePointOdataUri = Configuration["SHAREPOINT_ODATA_URI"]; string sharePointWebname = Configuration["SHAREPOINT_WEBNAME"]; string sharePointAadTenantId = Configuration["SHAREPOINT_AAD_TENANTID"]; string sharePointClientId = Configuration["SHAREPOINT_CLIENT_ID"]; string sharePointCertFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"]; string sharePointCertPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"]; services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(sharePointServerAppIdUri, sharePointOdataUri, sharePointWebname, sharePointAadTenantId, sharePointClientId, sharePointCertFileName, sharePointCertPassword, ssgUsername, ssgPassword)); // add BCeID Web Services string bceidUrl = Configuration["BCEID_SERVICE_URL"]; string bceidSvcId = Configuration["BCEID_SERVICE_SVCID"]; string bceidUserid = Configuration["BCEID_SERVICE_USER"]; string bceidPasswd = Configuration["BCEID_SERVICE_PASSWD"]; services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl)); // add BCEP services var bcep_svc_url = Environment.GetEnvironmentVariable("BCEP_SERVICE_URL"); var bcep_svc_svcid = Environment.GetEnvironmentVariable("BCEP_MERCHANT_ID"); var bcep_svc_hashid = Environment.GetEnvironmentVariable("BCEP_HASH_KEY"); var bcep_base_uri = Environment.GetEnvironmentVariable("BASE_URI"); var bcep_base_path = Environment.GetEnvironmentVariable("BASE_PATH"); var bcep_conf_path = Environment.GetEnvironmentVariable("BCEP_CONF_PATH"); services.AddTransient <BCEPWrapper>(_ => new BCEPWrapper(bcep_svc_url, bcep_svc_svcid, bcep_svc_hashid, bcep_base_uri + bcep_base_path + bcep_conf_path)); }
public async Task <string> BuscarAuthorizationHeaderComUsuarioSenha() { // o nome do usuário também poderia ser // [email protected] // pois cadastramos os dois string usuario = "postuser"; // a senha que foi gerada ou inserida no Azure string senha = "Ruqu0319"; // o locatário também pode ser o ID // exemplo: f1a92ca1-553c-4a1d-a00c-f7ab3c1445c7 string locatario = "seudominio.onmicrosoft.com"; // ID do aplicativo (cliente) => post-ConsoleApp string idCliente = "2b2ce9d4-b4a1-4cee-a0c1-46305f5e0a14"; // Fluxo do usuário para a autenticaçãp string policySignUpSignIn = "B2C_1_post_ropc"; // Interpolação de strings para utilização na autenticação string authorityBase = $"https://seudominio.b2clogin.com/tfp/{locatario}/"; string authority = $"{authorityBase}{policySignUpSignIn}"; // O escopo é referente a API exposta no aplicativo post-ApiWeb // pois é quem efetivamente iremos acessar string[] scopes = new string[] { // aqui é utilizado o ID do aplicativo (cliente) => post-ApiWeb "https://seudominio.onmicrosoft.com/e97f0bde-d845-4683-9717-cfc234c82659/post.sample" }; var application = PublicClientApplicationBuilder.Create(idCliente) .WithB2CAuthority(authority) .Build(); IEnumerable <IAccount> accounts = await application.GetAccountsAsync(); string authorizationHeader = string.Empty; AuthenticationResult authenticationResult = null; if (accounts.Any()) { authenticationResult = await application.AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(); } else { try { // cria uma forma segura de transmitir a senha // com o objeto do tipo SecureString var senhaSegura = new SecureString(); foreach (char c in senha) { senhaSegura.AppendChar(c); } // esse próximo passo eu não consegui executar com o await // na execução ele parava e saia do console sem acusar // nenhum tipo de erro. // por isso utilizo o .Wait() e depois pego o resultado var taskAcquire = application.AcquireTokenByUsernamePassword( scopes, usuario, senhaSegura).ExecuteAsync(); // não determinei nenhum timeout para o .Wait() taskAcquire.Wait(); authenticationResult = taskAcquire.Result; // o comando abaixo recupera o access token // e insere o "Bearer" no início, já deixando // pronto para utilização nas chamadas de API authorizationHeader = authenticationResult.CreateAuthorizationHeader(); } catch (MsalException mex) { // Caso ocorra algum erro na autenticação // deve ser tratado aqui Console.WriteLine(mex); } catch (Exception ex) { // Qualquer outro tipo de erro Console.WriteLine(ex); } } // capturas possíveis (algumas) // -------------------------------------------------- // caso queira recuperar apenas o access token string accessToken = authenticationResult.AccessToken; // caso queira recuperar apenas o ID token string idToken = authenticationResult.IdToken; // caso queira recuperar a hora em que o token expira DateTimeOffset expiresOn = authenticationResult.ExpiresOn; // -------------------------------------------------- // retorna o header com o Bearer return(authorizationHeader); }