private static void SetupApiClient() { var signingKey = AuthenticationUtils.LoadSigningKey(SigningKeyPkcs12FilePath, SigningKeyAlias, SigningKeyPassword); var encryptionCertificate = EncryptionUtils.LoadEncryptionCertificate(EncryptionCertificateFilePath); var decryptionKey = EncryptionUtils.LoadDecryptionKey(DecryptionKeyFilePath); var fieldLevelEncryptionConfig = FieldLevelEncryptionConfigBuilder.AFieldLevelEncryptionConfig() .WithEncryptionPath("$.cardInfo.encryptedData", "$.cardInfo") .WithEncryptionPath("$.encryptedPayload.encryptedData", "$.encryptedPayload") .WithDecryptionPath("$.tokenDetail", "$.tokenDetail.encryptedData") .WithDecryptionPath("$.encryptedPayload", "$.encryptedPayload.encryptedData") .WithEncryptionCertificate(encryptionCertificate) .WithDecryptionKey(decryptionKey) .WithOaepPaddingDigestAlgorithm("SHA-512") .WithEncryptedValueFieldName("encryptedData") .WithEncryptedKeyFieldName("encryptedKey") .WithIvFieldName("iv") .WithOaepPaddingDigestAlgorithmFieldName("oaepHashingAlgorithm") .WithEncryptionCertificateFingerprintFieldName("publicKeyFingerprint") .WithEncryptionCertificateFingerprint(EncryptionCertificateFingerprint) .WithValueEncoding(FieldLevelEncryptionConfig.FieldValueEncoding.Hex) .Build(); var config = Configuration.Default; config.BasePath = "https://sandbox.api.mastercard.com/mdes/"; config.ApiClient.RestClient.Authenticator = new RestSharpOAuth1Authenticator(ConsumerKey, signingKey, new Uri(config.BasePath)); config.ApiClient.EncryptionInterceptor = new RestSharpFieldLevelEncryptionInterceptor(fieldLevelEncryptionConfig); }
/// <summary> /// Verify the authentication header. /// </summary> /// <param name="header">Authentication header.</param> /// <param name="initial">Flag to indicate whether this is the initial verification call.</param> /// <param name="sessionToken">Session token associated with the authentication header.</param> /// <returns>True if the initial authentication header is valid; false otherwise.</returns> protected bool VerifyAuthenticationHeader(AuthenticationHeaderValue header, bool initial, out string sessionToken) { bool verified = false; string sessionTokenChecked = null; if (header != null) { AuthenticationUtils.GetSharedSecret sharedSecret; if (initial) { sharedSecret = InitialSharedSecret; } else { sharedSecret = SharedSecret; } if ("Basic".Equals(header.Scheme)) { verified = AuthenticationUtils.VerifyBasicAuthorisationToken(header.ToString(), sharedSecret, out sessionTokenChecked); } else if ("SIF_HMACSHA256".Equals(header.Scheme)) { verified = true; } } sessionToken = sessionTokenChecked; return(verified); }
private void BrowseDataDictionary_Load(object sender, EventArgs e) { AuthenticationUtils.startSession("admin", "sametsis"); try { ClassDefinition[] classDefinitions = WebServiceFactory.getDictionaryService().getClasses(null, null); foreach (ClassDefinition classDefinition in classDefinitions) { string displayLabel = classDefinition.title; if (displayLabel != null && displayLabel.Trim().Length != 0) { ListViewItem item = new ListViewItem(classDefinition.title); item.Tag = classDefinition; listBoxClasses.Items.Add(item); listBoxClasses.DisplayMember = "Text"; listBoxClasses.ValueMember = "Tag"; } } } finally { AuthenticationUtils.endSession(); } }
//********************************************************** // Function: OpenScript() // Scope: internal // Overview: Script initialization point. Perform any // necessary initialization such as logging // in to a remote data source, allocated any // necessary resources, etc. // Params: none // Returns: One of the following: // KFX_REL_SUCCESS, KFX_REL_ERROR // Called By: The Batch Release Manager. Called once // when the script object is loaded. //********************************************************** public AscentRelease.KfxReturnValue OpenScript() { // Start the Alfresco session try { string repository = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_REPOSITORY); WebServiceFactory.setEndpointAddress(repository); string userName = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_USERNAME); string password = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_PASSWORD); AuthenticationUtils.startSession(userName, password); this.repoService = WebServiceFactory.getRepositoryService(); // the uuid of the location to be saved this.locationUuid = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_LOCATION_UUID); this.contentType = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_CONTENT_TYPE); this.imageContentProp = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_IMAGE); this.ocrContentProp = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_OCR); this.pdfContentProp = ReleaseUtils.getCustomProperty(this.releaseData.CustomProperties, ReleaseConstants.CUSTOM_PDF); // Initialise the reference to the spaces store this.spacesStore = new Alfresco.RepositoryWebService.Store(); spacesStore.scheme = Alfresco.RepositoryWebService.StoreEnum.workspace; spacesStore.address = "SpacesStore"; return(AscentRelease.KfxReturnValue.KFX_REL_SUCCESS); } catch (Exception) { return(AscentRelease.KfxReturnValue.KFX_REL_ERROR); } }
public async Task <Patient> GetPatient(int patientId) { var uri = $"{ApiConfiguration.GetBaseUrl()}/Patient/{patientId}"; _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationUtils.GetUserToken(_httpContextAccessor.HttpContext)); HttpResponseMessage response; try { Log.Debug($"GET request, URI = {uri}"); response = await _httpClient.GetAsync(uri); } catch (Exception ex) { Log.Error(ex, "GET Patient failed"); return(null); } Patient patient = null; if (response.IsSuccessStatusCode) { Log.Debug("GET Patient succeeded"); patient = JsonUtils.Deserialize <Patient>(await response.Content.ReadAsStringAsync()); } else { Log.Error($"GET Patient failed, status code = {response.StatusCode}"); } return(patient); }
public static void RedirectRequests(RewriteContext context) { var request = context.HttpContext.Request; var path = request.Path.Value; var publicRoutes = new List <string> { "Index", "Authentication/Login", "Authentication/Register" }; var isUserLoggedIn = AuthenticationUtils.IsUserLoggedIn(context.HttpContext); bool isRoutePublic = false; publicRoutes.ForEach(route => { if (path.Contains(route)) { isRoutePublic = true; } }); if (!isUserLoggedIn && !isRoutePublic) { context.HttpContext.Response.Redirect(CurentCultureUtils.GetCurrentCultureLink("Authentication/Login")); } }
/// <summary> /// <see cref="SifService{UI, DB}.Create(UI, string, string)"/> /// </summary> public override Guid Create(environmentType item, string zoneId = null, string contextId = null) { EnvironmentRegister environmentRegister = (new EnvironmentRegisterService()).RetrieveByUniqueIdentifiers (item.applicationInfo.applicationKey, item.instanceId, item.userToken, item.solutionId); if (environmentRegister == null) { string errorMessage = string.Format("Environment with application key of {0}, solution ID of {1}, instance ID of {2} and user token of {3} does NOT exist.", item.applicationInfo.applicationKey, (item.solutionId == null ? "[null]" : item.solutionId), (item.instanceId == null ? "[null]" : item.instanceId), (item.userToken == null ? "[null]" : item.userToken)); throw new AlreadyExistsException(errorMessage); } string sessionToken = AuthenticationUtils.GenerateSessionToken(item.applicationInfo.applicationKey, item.instanceId, item.userToken, item.solutionId); environmentType environmentType = RetrieveBySessionToken(sessionToken); if (environmentType != null) { string errorMessage = string.Format("A session token already exists for environment with application key of {0}, solution ID of {1}, instance ID of {2} and user token of {3}.", item.applicationInfo.applicationKey, (item.solutionId == null ? "[null]" : item.solutionId), (item.instanceId == null ? "[null]" : item.instanceId), (item.userToken == null ? "[null]" : item.userToken)); throw new AlreadyExistsException(errorMessage); } IDictionary <InfrastructureServiceNames, InfrastructureService> infrastructureServices = CopyInfrastructureServices(environmentRegister.InfrastructureServices); IDictionary <string, ProvisionedZone> provisionedZones = CopyProvisionedZones(environmentRegister.ProvisionedZones); Environment repoItem = MapperFactory.CreateInstance <environmentType, Environment>(item); if (environmentRegister.DefaultZone != null) { repoItem.DefaultZone = CopyDefaultZone(environmentRegister.DefaultZone); } if (infrastructureServices.Count > 0) { repoItem.InfrastructureServices = CopyInfrastructureServices(environmentRegister.InfrastructureServices); } if (provisionedZones.Count > 0) { repoItem.ProvisionedZones = CopyProvisionedZones(environmentRegister.ProvisionedZones); } repoItem.SessionToken = sessionToken; Guid environmentId = repository.Save(repoItem); if (repoItem.InfrastructureServices.Count > 0) { InfrastructureService infrastructureService = repoItem.InfrastructureServices[InfrastructureServiceNames.environment]; if (infrastructureService != null) { infrastructureService.Value = infrastructureService.Value + "/" + environmentId; repository.Save(repoItem); } } return(environmentId); }
public void CanDeleteNodes() { AuthenticationUtils.startSession("admin", "admin"); Store spacesStore = new Store(StoreEnum.workspace, "SpacesStore"); String name = "AWS Book " + DateTime.Now.Ticks; String description = "This is a content created with a sample of the book"; //custom value object CreateSampleVO createSampleVo = Builder.BuildCreateSampleVO(name, name, description); try { ParentReference parent = new ParentReference( spacesStore, null, "/app:company_home", Constants.ASSOC_CONTAINS, "{" + Constants.NAMESPACE_CONTENT_MODEL + "}" + name ); //build properties NamedValue[] properties = Builder.BuildCustomProperties(createSampleVo); //create operation CMLCreate create = new CMLCreate(); create.id = "1"; create.parent = parent; create.type = Constants.TYPE_CONTENT; create.property = properties; //build the CML object CML cmlAdd = new CML(); cmlAdd.create = new CMLCreate[] { create }; //perform a CML update to create the node UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cmlAdd); String expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_"; Assert.IsTrue(result[0].destination.path.StartsWith(expectedPath)); //create a predicate Reference reference = result[0].destination; Predicate predicate = new Predicate(new Reference[] { reference }, spacesStore, null); //delete content CMLDelete delete = new CMLDelete(); delete.where = predicate; CML cmlRemove = new CML(); cmlRemove.delete = new CMLDelete[] { delete }; //perform a CML update to remove the node WebServiceFactory.getRepositoryService().update(cmlRemove); expectedPath = "/app:company_home/cm:AWS_x0020_Book_x0020_"; Assert.IsTrue(reference.path.StartsWith(expectedPath)); } finally { AuthenticationUtils.endSession(); } }
public ImageUploadExample() { InitializeComponent(); AuthenticationUtils.startSession("admin", "sametsis"); // Create the repo service and set the authentication credentials this.repoService = WebServiceFactory.getRepositoryService(); }
public UploadExample() { InitializeComponent(); AuthenticationUtils.startSession("admin", "sametsis"); // Get the repository service this.repoService = WebServiceFactory.getRepositoryService(); }
/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { AuthenticationUtils.endSession(); components.Dispose(); } base.Dispose(disposing); }
public Services(string consumerKey, string fullCertificatePath, string signingKeyAlias, string signingKeyPassword, string baseURL) { _consumerKey = consumerKey; _baseUri = new Uri(baseURL + "/mastercom/v6/queues/names"); _signingKey = AuthenticationUtils.LoadSigningKey( fullCertificatePath, signingKeyAlias, signingKeyPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); }
public async Task <IActionResult> OnPostAsync(int selectedDoctorId, int[] selectedReasonsIds, DateTime pickedDate) { if (ModelState.IsValid) { if (pickedDate < DateTime.UtcNow) { ModelState.AddModelError("Date", _cultureLocalizer.Text("Date must be from the future")); } else { Appointment.Doctor = new Doctor() { UserId = selectedDoctorId }; if (selectedReasonsIds.Length > 0) { Appointment.AppointmentReasons = new List <Appointment2Reason>(); Array.ForEach(selectedReasonsIds, (reasonId) => { Appointment.AppointmentReasons.Add(new Appointment2Reason() { ReasonId = reasonId }); }); } var patientId = AuthenticationUtils.GetPatientId(HttpContext); if (patientId.HasValue) { Appointment.Patient = new Patient() { UserId = patientId.Value }; } Appointment.AppointmentDate = pickedDate; appointmentsSetResponse = await _appointmentsService.SetAppointment(Appointment); if (appointmentsSetResponse == AppointmentSetResponse.CORRECT) { HttpContext.Response.Redirect(CurentCultureUtils.GetCurrentCultureLink("Appointments/AppointmentMade")); return(null); } } } await OnGetAsync(); SelectedDoctor = selectedDoctorId; SelectedResons = selectedReasonsIds; Date = pickedDate; return(Page()); }
public async Task OnGetAsync() { if (Patient == null) { var patientId = AuthenticationUtils.GetPatientId(HttpContext); if (patientId.HasValue) { Patient = await patientsProfileService.GetPatient(patientId.Value); } } }
public async Task OnGetAsync() { if (Doctor == null) { var doctorId = AuthenticationUtils.GetPatientId(HttpContext); if (doctorId.HasValue) { Doctor = await patientsProfileService.GetDoctor(doctorId.Value); } } }
private IAuthenticator Login(string pAuthorizationCode, string pEmail, string pState) { if (!String.IsNullOrEmpty(pAuthorizationCode)) { return(AuthenticationUtils.GetCredentials(pEmail, pAuthorizationCode, pState)); } else { IAuthorizationState authorizationState = AuthenticationUtils.GetStoredCredentials(pEmail); return(AuthenticationUtils.GetAuthenticatorFromState(authorizationState)); } }
//********************************************************** // Function: CloseScript() // Scope: internal // Overview: Script release point. Perform any necessary // cleanup such as logging out of the data // source, release any resources, etc. // Params: none // Returns: One of the following: // KFX_REL_SUCCESS, KFX_REL_ERROR // Called By: The Batch Release Manager. Called once just // before the script object is released. //********************************************************** public AscentRelease.KfxReturnValue CloseScript() { // End the Alfresco session try { AuthenticationUtils.endSession(); return(AscentRelease.KfxReturnValue.KFX_REL_SUCCESS); } catch (Exception) { return(AscentRelease.KfxReturnValue.KFX_REL_ERROR); } }
public async Task <IActionResult> Login([FromBody] LoginDTO model) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (result.Succeeded) { var user = _userManager.Users.SingleOrDefault(r => r.Email == model.Email); var token = await AuthenticationUtils.GenerateJwtToken(model.Email, user, _configuration["JwtKey"], _configuration["JwtExpireDays"], _configuration["JwtIssuer"]); return(Ok(token)); } return(Unauthorized("Incorrect credentials provided")); }
public void CanPerformSearches() { AuthenticationUtils.startSession("admin", "admin"); try { RepositoryService repositoryService = WebServiceFactory.getRepositoryService(); Store spacesStore = new Store(StoreEnum.workspace, "SpacesStore"); String luceneQuery = "PATH:\"/app:company_home\""; Query query = new Query(Constants.QUERY_LANG_LUCENE, luceneQuery); QueryResult queryResult = repositoryService.query(spacesStore, query, false); ResultSet resultSet = queryResult.resultSet; ResultSetRow[] results = resultSet.rows; //your custom list IList <CustomResultVO> customResultList = new List <CustomResultVO>(); //retrieve results from the resultSet foreach (ResultSetRow resultRow in results) { ResultSetRowNode nodeResult = resultRow.node; //create your custom value object CustomResultVO customResultVo = new CustomResultVO(); customResultVo.Id = nodeResult.id; customResultVo.Type = nodeResult.type; //retrieve properties from the current node foreach (NamedValue namedValue in resultRow.columns) { if (Constants.PROP_NAME.Equals(namedValue.name)) { customResultVo.Name = namedValue.value; } else if (Constants.PROP_DESCRIPTION.Equals(namedValue.name)) { customResultVo.Description = namedValue.value; } } //add the current result to your custom list customResultList.Add(customResultVo); } Assert.AreEqual(1, customResultList.Count); CustomResultVO firstResult = customResultList[0]; Assert.IsNotNull(firstResult.Id); Assert.AreEqual("{http://www.alfresco.org/model/content/1.0}folder", firstResult.Type); } finally { AuthenticationUtils.endSession(); } }
private bool Login() { using (CredentialsDialog dlgLogin = new CredentialsDialog()) { dlgLogin.User = Config.Get <string>("LastUser", string.Empty); dlgLogin.Caption = "CCOW Server"; dlgLogin.Message = "Please provide an administrative user to access configuration settings."; while (true) { if (dlgLogin.ShowDialog() == DialogResult.OK) { IntPtr token = IntPtr.Zero; if (AuthenticationUtils.Login(dlgLogin.Domain, dlgLogin.User, dlgLogin.PasswordToString(), out token)) { WindowsPrincipal principal = Thread.CurrentPrincipal as WindowsPrincipal; if (AuthenticationUtils.IsAdmin(principal) || AuthenticationUtils.IsDomainAdmin(principal)) { string saveUser = dlgLogin.User; if (!string.IsNullOrEmpty(dlgLogin.Domain)) { saveUser = dlgLogin.Domain + "\\" + dlgLogin.User; } Config.Set <string>("LastUser", saveUser); return(true); } else { MessageBox.Show(this, "User is not a member of Administrators group.", "Invalid User", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { Win32Exception e = new Win32Exception(Marshal.GetLastWin32Error()); MessageBox.Show(this, e.Message, "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { break; } } } return(false); }
/// <summary> /// Utility method for getting the authenticated who from the header. /// </summary> public static IAuthenticatedWho GetWho(String authorizationHeader) { IAuthenticatedWho authenticatedWho = null; // Check to see if it's null - it can be in some situations if (authorizationHeader != null && authorizationHeader.Trim().Length > 0) { // Deserialize into an object authenticatedWho = AuthenticationUtils.Deserialize(Uri.EscapeDataString(authorizationHeader)); } return(authenticatedWho); }
public void TestLoadSigningKey_ShouldReturnKey() { // GIVEN const string keyContainerPath = "./_Resources/test_key_container.p12"; const string keyAlias = "mykeyalias"; const string keyPassword = "******"; // WHEN const X509KeyStorageFlags flags = X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable; // https://github.com/dotnet/corefx/issues/14745 var privateKey = AuthenticationUtils.LoadSigningKey(keyContainerPath, keyAlias, keyPassword, flags); // THEN Assert.AreEqual(2048, privateKey.KeySize); Assert.AreEqual("RSA", privateKey.KeyExchangeAlgorithm); }
/// <summary> /// Signs User into system. If User is already Signed-In, this will update their /// Authentication cookie. /// </summary> private async Task SignInUser(UserLogin userLogin) { var authenticationProperties = AuthenticationUtils.GetAuthenticationProperties(); var userRolesResult = _userRoleReadConductor.FindAll(e => e.UserId == userLogin.UserId); var roleIds = userRolesResult.ResultObject?.Select(e => e.RoleId); var claims = AuthenticationUtils.GetClaims( roleIds: roleIds, user: userLogin.User, userLogin: userLogin ); var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationUtils.AUTHENTICATION_TYPE)); await _httpContext.SignInAsync(AuthenticationUtils.AUTHENTICATION_SCHEME, userPrincipal, authenticationProperties); }
static void Main(string[] args) { int i = 1; while (i != 0) { Console.WriteLine("Ingrese un numero"); i = Int32.Parse(Console.ReadLine()); if (i == 1) { Console.WriteLine("Ingrese el codigo de autorizacion"); string authCode = Console.ReadLine(); Console.WriteLine("Ingrese su mail"); string email = Console.ReadLine(); Console.WriteLine("Ingrese el texto a enviar"); string texto = Console.ReadLine(); TimelineItem item = new TimelineItem(); item.Text = texto; /* Puse el mail, pero puede ser cualquier cosa. Lo uso solo para identificar al usuario y poder acceder desp * a su correspondiente auth token y refresh token*/ IAuthenticator credentials = AuthenticationUtils.GetCredentials(email, authCode, "Sigo sin enteder pa que sirve esto"); //MirrorService service = BuildService(credentials); //service.Timeline.Insert(item).Fetch(); } else if (i == 2) { Console.WriteLine("Ingrese su mail"); string email = Console.ReadLine(); Console.WriteLine("Ingrese el texto a enviar"); string texto = Console.ReadLine(); Credential credential = GlassContext.Instancia.GetCredential(email); AuthorizationState state = new AuthorizationState() { AccessToken = credential.AccessToken, RefreshToken = credential.RefreshToken }; MirrorService service = BuildService(AuthenticationUtils.GetAuthenticatorFromState(state)); Image image = Image.FromFile("C:\\Users\\Guido\\Desktop\\1405290025332.jpg"); var ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); ms.Position = 0; TimelineItem itemAttachment = InsertTimelineItem(service, "Equipo argentino", "image/jpeg", ms, "DEFAULT"); } } }
/// <summary> /// The form load event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Browse_Load(object sender, EventArgs e) { // Ensure the user has been authenticated if (AuthenticationUtils.IsSessionValid == false) { AuthenticationUtils.startSession("admin", "sametsis"); } // Get a repository and content service from the web service factory this.repoService = WebServiceFactory.getRepositoryService(); this.contentService = WebServiceFactory.getContentService(); this.authoringService = WebServiceFactory.getAuthoringService(); // Populate the list box populateListBox(); }
public async Task <AuthenticationReponse> Login(User user) { var uri = $"{ApiConfiguration.GetBaseUrl()}/User/login"; var userJson = JsonUtils.Serialize(user); HttpResponseMessage response; try { Log.Debug($"POST request, URI = {uri}"); response = await _httpClient.PostAsync(uri, new StringContent(userJson, Encoding.UTF8, "application/json")); } catch (Exception ex) { Log.Error(ex, "POST User/login failed"); return(new AuthenticationReponse() { WasAuthenticationCorrect = false }); } Token token = null; var authenticationResponse = new AuthenticationReponse() { WasAuthenticationCorrect = response.IsSuccessStatusCode }; if (response.IsSuccessStatusCode) { Log.Debug("POST User/login success"); token = JsonUtils.Deserialize <Token>(await response.Content.ReadAsStringAsync()); authenticationResponse.Roles = token?.Roles.ToList(); authenticationResponse.PatientId = token?.UserId; authenticationResponse.Token = token?.TokenString; AuthenticationUtils.SaveUserToSession(_httpContextAccessor.HttpContext, authenticationResponse); } else { Log.Error($"POST User/login failed, status code = {response.StatusCode}"); } return(authenticationResponse); }
private IAuthenticatedWho GetWho() { IAuthenticatedWho authenticatedWho = null; String authorizationHeader = null; // Get the authorization header from this invoke request authorizationHeader = System.Web.HttpContext.Current.Request.Headers[HttpUtils.HEADER_AUTHORIZATION]; if (authorizationHeader == null) { throw new ArgumentNullException("BadRequest", "Not authorized to invoke this service."); } // Check to make sure the authorization header parses OK authenticatedWho = AuthenticationUtils.Deserialize(HttpUtility.UrlDecode(authorizationHeader)); return(authenticatedWho); }
public async Task Logout(IOperation operation, IEnumerable <Claim> claims, string refreshToken) { var claimsList = claims.ToList(); var id = AuthenticationUtils.GetUserId(claimsList) ?? throw CommonExceptions.FailedToReadAuthenticationDataFromClaims(operation); var refreshTokenId = await userDataStore.GetRefreshTokenId(operation, id, refreshToken); if (!refreshTokenId.HasValue) { throw CommonExceptions.RefreshTokensAreDifferent(operation); } var identity = GetIdentity(claimsList); identity?.Claims.ToList().ForEach(claim => identity.RemoveClaim(claim)); await userDataStore.RemoveRefreshToken(operation, refreshTokenId.Value); }
public void AuthenticationTicketMessageFrame(WorldClient client, AuthenticationTicketMessage authenticationTicketMessage) { string ticket = AuthenticationUtils.DecodeTicket(authenticationTicketMessage.ticket); //client.SendPacket(new AuthenticationTicketAcceptedMessage()); var account = AccountRepository.Instance.GetAccountByTicket(ticket); if (account == null) { client.SendPacket(new AuthenticationTicketRefusedMessage()); return; } client.Account = account; Console.WriteLine("'{0}' switched to world with Ticket={1}", client.Account.Login, ticket); client.SendPacket(new AuthenticationTicketAcceptedMessage()); client.SendPacket(new TrustStatusMessage(true, false)); }
/// <summary> /// This method allows you to login as an author of flows. /// </summary> public IAuthenticatedWho Login(INotifier notifier, String tenantId, String manywhoBaseUrl, AuthenticationCredentialsAPI authenticationCredentials) { String authorizationToken = null; IAuthenticatedWho authenticatedWho = null; HttpClient httpClient = null; HttpContent httpContent = null; HttpResponseMessage httpResponseMessage = null; String endpointUrl = null; Policy.Handle <ServiceProblemException>().Retry(HttpUtils.MAXIMUM_RETRIES).Execute(() => { using (httpClient = HttpUtils.CreateHttpClient(null, tenantId, null)) { // Use the JSON formatter to create the content of the request body. httpContent = new StringContent(JsonConvert.SerializeObject(authenticationCredentials)); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // Construct the URL for the describe request endpointUrl = manywhoBaseUrl + DrawSingleton.MANYWHO_DRAW_URI_PART_LOGIN; // Send the describe request over to the remote service httpResponseMessage = httpClient.PostAsync(endpointUrl, httpContent).Result; // Check the status of the response and respond appropriately if (httpResponseMessage.IsSuccessStatusCode) { // Get the describe response object from the response message authorizationToken = httpResponseMessage.Content.ReadAsStringAsync().Result; // Trim the quotes from the JSON response token authorizationToken = authorizationToken.Substring(1, authorizationToken.Length - 2); // Deserialize the token back to an authenticated who object authenticatedWho = AuthenticationUtils.Deserialize(Uri.UnescapeDataString(authorizationToken)); } else { throw new ServiceProblemException(new ServiceProblem(endpointUrl, httpResponseMessage, string.Empty)); } } }); return(authenticatedWho); }