internal static async Task <AuthenticateResult> HandleAuthenticate(IHttpClientFactory httpClientFactory, string wellKnownConfiguration, string token) { var factory = new IdentityServerClientFactory(httpClientFactory); try { var introspectionResult = await factory.CreateUserInfoClient() .Resolve(wellKnownConfiguration, token) .ConfigureAwait(false); if (introspectionResult == null || introspectionResult.ContainsError) { return(AuthenticateResult.NoResult()); } var claims = new List <Claim>(); var values = introspectionResult.Content.ToObject <Dictionary <string, object> >(); foreach (var kvp in values) { claims.AddRange(Convert(kvp)); } var claimsIdentity = new ClaimsIdentity(claims, UserInfoIntrospectionOptions.AuthenticationScheme); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authenticationTicket = new AuthenticationTicket(claimsPrincipal, new AuthenticationProperties(), UserInfoIntrospectionOptions.AuthenticationScheme); return(AuthenticateResult.Success(authenticationTicket)); } catch (Exception) { return(AuthenticateResult.NoResult()); } }
public async Task <IActionResult> Callback(string code, string state) { if (!Request.Cookies.ContainsKey(COOKIE_NAME)) { return(new UnauthorizedResult()); } var cookieContent = JsonConvert.DeserializeObject <CookieContent>(Request.Cookies[COOKIE_NAME]); if (cookieContent.State != state) { return(new UnauthorizedResult()); } var issuerName = Request.GetAbsoluteUriWithVirtualPath(); var wellKnownConfiguration = $"{issuerName}/.well-known/openid-configuration"; var identityServerClientFactory = new IdentityServerClientFactory(); var grantedToken = await identityServerClientFactory.CreateAuthSelector().UseClientSecretPostAuth(_shellModuleOptions.ClientId, _shellModuleOptions.ClientSecret) .UseAuthorizationCode(code, issuerName + Url.Action("Callback")) .ResolveAsync(wellKnownConfiguration).ConfigureAwait(false); if (grantedToken.ContainsError) { return(new UnauthorizedResult()); } if (!await AddCookie(grantedToken.Content.IdToken, cookieContent.Nonce).ConfigureAwait(false)) { return(new UnauthorizedResult()); } return(RedirectToAction("Index")); }
public IServiceProvider ConfigureServices(IServiceCollection services) { var factory = new IdentityServerClientFactory(_context.HttpClientFactory); services.AddSingleton <IIdentityServerClientFactory>(factory); services.AddSingleton <IAccessTokenStore>(_context.AccessTokenStore.Object); services.AddSingleton <IIdentityServerUmaClientFactory>(_context.IdentityServerUmaClientFactory.Object); services.AddDocumentManagementEFInMemory(); services.AddSimpleIdentityServerJwt(); services.AddDocumentManagementInMemoryStore(); services.AddDocumentManagementHost(new DocumentManagementApiOptions("wellknown") { OAuth = new OAuthOptions { ClientId = "clientid", ClientSecret = "clientsecret", WellKnownConfiguration = "wellknown" } }); services.AddAuthentication("UserInfoIntrospection") .AddFakeUserInfoIntrospection(opts => { }); services.AddAuthorization(opts => { opts.AddPolicy("connected", policy => policy.RequireAssertion((h) => true)); }); var mvc = services.AddMvc(); var parts = mvc.PartManager.ApplicationParts; parts.Clear(); parts.Add(new AssemblyPart(typeof(ConfigurationController).GetTypeInfo().Assembly)); return(services.BuildServiceProvider()); }
private static async Task GetProtectedResource() { var httpClient = new HttpClient(); var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("http://localhost:5000/Informations/Get/1") }; var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false); // 1. Try to retrieve protected resource without RPT token. var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var jObj = JObject.Parse(content); var ticketId = jObj["ticket_id"].ToString(); var factory = new IdentityServerClientFactory(); var grantedToken = await factory.CreateAuthSelector() // 2. Retrieve the identity token. .UseClientSecretPostAuth("MedicalWebsite", "MedicalWebsite") .UsePassword("administrator", "password", "openid", "profile") .ResolveAsync("https://localhost:5443/.well-known/openid-configuration"); var rptToken = await factory.CreateAuthSelector() // 3. Retrieve the RPT token. .UseClientSecretPostAuth("client", "client") .UseTicketId(ticketId, grantedToken.IdToken) .ResolveAsync("https://localhost:5445/.well-known/uma2-configuration"); httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("http://localhost:5000/Informations/Get/1") }; httpRequestMessage.Headers.Add("Authorization", "Bearer " + rptToken.AccessToken); response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false); string s = ""; }
private string DecryptOfficeDocument(string sidDocumentIdValue, string identityToken, string content) { var splittedContent = content.Split('.'); if (splittedContent.Length != 3) { return(null); } var encryptionHelper = new EncryptionHelper(); var kid = splittedContent[0]; var credentials = splittedContent[1]; var encryptedContent = splittedContent[2]; var officeDocumentStore = OfficeDocumentStore.Instance(); var decryptionResponse = officeDocumentStore.RestoreDecryption(sidDocumentIdValue); if (decryptionResponse != null) { try { var result = encryptionHelper.Decrypt(encryptedContent, decryptionResponse); return(result); } catch (Exception) { } } var identityServerClientFactory = new IdentityServerClientFactory(); var identityServerUmaClientFactory = new IdentityServerUmaClientFactory(); var documentManagementFactory = new DocumentManagementFactory(); var umaResourceId = officeDocumentStore.GetUmaResourceId(sidDocumentIdValue).Result; if (string.IsNullOrWhiteSpace(umaResourceId)) { return(null); } var grantedToken = officeDocumentStore.GetOfficeDocumentAccessTokenViaUmaGrantType(umaResourceId).Result; if (grantedToken == null) { return(null); } var decryptedResult = documentManagementFactory.GetOfficeDocumentClient().DecryptResolve(new DecryptDocumentRequest { DocumentId = sidDocumentIdValue, Credentials = credentials, Kid = kid }, Constants.DocumentApiConfiguration, grantedToken.AccessToken).Result; if (decryptedResult.ContainsError) { return(null); } return(encryptionHelper.Decrypt(encryptedContent, decryptedResult.Content)); }
private OfficeDocumentStore() { _identityServerUmaClientFactory = new IdentityServerUmaClientFactory(); _identityServerClientFactory = new IdentityServerClientFactory(); _documentManagementFactory = new DocumentManagementFactory(); _accessTokenStore = AccessTokenStore.Instance(); _authenticationStore = AuthenticationStore.Instance(); _tokens = new List <StoredUmaAccessToken>(); _documents = new List <StoredOfficeDocument>(); }
public GenerateProxyWindowControl() { _isInitialized = false; var factory = new IdentityServerUmaManagerClientFactory(); var identityServerClientFactory = new IdentityServerClientFactory(); _clientAuthSelector = identityServerClientFactory.CreateTokenClient(); _resourceClient = factory.GetResourceClient(); InitializeComponent(); Loaded += Load; }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string authorization = Request.Headers["Authorization"]; if (string.IsNullOrWhiteSpace(authorization)) { return(AuthenticateResult.NoResult()); } string token = null; if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { token = authorization.Substring("Bearer ".Length).Trim(); } if (string.IsNullOrEmpty(token)) { return(AuthenticateResult.NoResult()); } var factory = new IdentityServerClientFactory(); try { var introspectionResult = await factory.CreateUserInfoClient() .Resolve(Options.WellKnownConfigurationUrl, token) .ConfigureAwait(false); if (introspectionResult == null) { return(AuthenticateResult.NoResult()); } var claims = new List <Claim>(); var values = introspectionResult.ToObject <Dictionary <string, object> >(); foreach (var kvp in values) { claims.Add(new Claim(kvp.Key, kvp.Value.ToString())); } var claimsIdentity = new ClaimsIdentity(claims, UserInfoIntrospectionOptions.AuthenticationScheme); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authenticationTicket = new AuthenticationTicket( claimsPrincipal, new AuthenticationProperties(), UserInfoIntrospectionOptions.AuthenticationScheme); return(AuthenticateResult.Success(authenticationTicket)); } catch (Exception) { return(AuthenticateResult.NoResult()); } }
public ProtectUserController(Window window) { _window = window; _documentManagementFactory = new DocumentManagementFactory(); _identityServerUmaClientFactory = new IdentityServerUmaClientFactory(); _identityServerClientFactory = new IdentityServerClientFactory(); _authenticationStore = AuthenticationStore.Instance(); _officeDocumentStore = OfficeDocumentStore.Instance(); ViewModel = new ProtectUserViewModel(); Init(); ViewModel.DocumentProtected += HandleProtectDocument; ViewModel.SharedLinkAdded += HandleAddSharedLink; ViewModel.SelectedSharedLinkRemoved += HandleRemoveSharedLink; }
[HttpPost(Constants.RouteNames.CreditCard)] // Update the credit card information. public async Task <IActionResult> UpdateCreditCard([FromBody] JObject jObj) { if (jObj == null) { throw new ArgumentNullException(nameof(jObj)); } // 1. Get the subject. var subjectResult = await GetSubject(); if (!subjectResult.IsValid) { return(subjectResult.Error); } // 2. Check the user exists. var user = await _resourceOwnerRepository.GetAsync(subjectResult.Subject); if (user == null) { return(this.BuildError(ErrorCodes.InvalidRequestCode, ErrorDescriptions.TheRoDoesntExist, HttpStatusCode.NotFound)); } // 3. Fetch the customer_id && update the user. var factory = new IdentityServerClientFactory(); var tokenResult = await factory.CreateAuthSelector() .UseClientSecretBasicAuth(Constants.SumUpClientId, Constants.SumUpClientSecret) .UseClientCredentials("user.subaccounts") .ExecuteAsync(Constants.BaseSumupApi + "/token"); var sumUpClient = await _sumUpClient.GetClientPayments(subjectResult.Subject, tokenResult.AccessToken); if (sumUpClient == null) { var result = await _sumUpClient.AddClient(new AddClientParameter { Id = subjectResult.Subject, AccessToken = tokenResult.AccessToken, Name = TryGetValue(user.Claims, SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Name), Phone = TryGetValue(user.Claims, SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.PhoneNumber) }); } return(null); }
public async Task When_Add_Mapping_Then_Attributes_Are_Correctly_Returned() { const string scimBaseUrl = "http://localhost:60001"; var identityServerClientFactory = new IdentityServerClientFactory(); var adMappingClientFactory = new AdMappingClientFactory(); var scimClientFactory = new ScimClientFactory(); var adConfigurationClient = adMappingClientFactory.GetAdConfigurationClient(); var adMappingClient = adMappingClientFactory.GetAdMappingClient(); var tokenResponse = await identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth("ResourceServer", "LW46am54neU/[=Su") .UseClientCredentials("scim_manage", "scim_read") .ResolveAsync("http://localhost:60004/.well-known/uma2-configuration"); var r = await adConfigurationClient.UpdateConfiguration(new UpdateAdConfigurationRequest { IpAdr = "127.0.0.1", Port = 10389, Schemas = new List <UpdateAdConfigurationSchemaRequest> { new UpdateAdConfigurationSchemaRequest { Filter = "(uid=${externalId})", FilterClass = "(objectClass=person)", SchemaId = "urn:ietf:params:scim:schemas:core:2.0:User" } }, DistinguishedName = "ou=system", Username = "******", Password = "******", IsEnabled = true }, scimBaseUrl, tokenResponse.Content.AccessToken); await adMappingClient.AddMapping(new AddMappingRequest { AdPropertyName = "cn", AttributeId = "8c5f01ca-cd5a-4a87-b503-9c9977074947", SchemaId = "urn:ietf:params:scim:schemas:core:2.0:User" }, scimBaseUrl, tokenResponse.Content.AccessToken); var user = await scimClientFactory.GetUserClient().GetUser(scimBaseUrl, "7d79392f-8a02-494c-949e-723a4db8ed16", tokenResponse.Content.AccessToken); string s = ""; }
private async Task <AuthorizationResponse> BuildAuthorizationUrl() { var issuerName = Request.GetAbsoluteUriWithVirtualPath(); var wellKnownConfiguration = $"{issuerName}/.well-known/openid-configuration"; var identityServerClientFactory = new IdentityServerClientFactory(); var discoveryInformation = await identityServerClientFactory.CreateDiscoveryClient().GetDiscoveryInformationAsync(wellKnownConfiguration).ConfigureAwait(false); var state = Guid.NewGuid().ToString(); var nonce = Guid.NewGuid().ToString(); var url = $"{discoveryInformation.AuthorizationEndPoint}?scope=openid profile&state={state}&redirect_uri={issuerName + Url.Action("Callback")}&response_type=code&client_id={_shellModuleOptions.ClientId}&nonce={nonce}&response_mode=query"; return(new AuthorizationResponse { AuthorizationUrl = url, CookieContent = new CookieContent { State = state, Nonce = nonce } }); }
public async Task When_Update_Configuration_And_Get_Properties_Then_List_Is_Returned() { const string scimBaseUrl = "http://localhost:60001"; var identityServerClientFactory = new IdentityServerClientFactory(); var adMappingClientFactory = new AdMappingClientFactory(); var scimClientFactory = new ScimClientFactory(); var adConfigurationClient = adMappingClientFactory.GetAdConfigurationClient(); var adMappingClient = adMappingClientFactory.GetAdMappingClient(); var tokenResponse = await identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth("ResourceServer", "LW46am54neU/[=Su") .UseClientCredentials("scim_manage", "scim_read") .ResolveAsync("http://localhost:60004/.well-known/uma2-configuration"); var r = await adConfigurationClient.UpdateConfiguration(new UpdateAdConfigurationRequest { IpAdr = "127.0.0.1", Port = 10389, IsEnabled = true, Schemas = new List <UpdateAdConfigurationSchemaRequest> { new UpdateAdConfigurationSchemaRequest { Filter = "(uid=${externalId})", FilterClass = "(objectClass=person)", SchemaId = "urn:ietf:params:scim:schemas:core:2.0:User" } }, DistinguishedName = "ou=system", Username = "******", Password = "******" }, scimBaseUrl, tokenResponse.Content.AccessToken); var result = await adMappingClient.GetAllProperties("urn:ietf:params:scim:schemas:core:2.0:User", scimBaseUrl, tokenResponse.Content.AccessToken); string s = ""; }
public async Task AddClient() { var factory = new IdentityServerClientFactory(); var result = await factory.CreateAuthSelector() .UseClientSecretBasicAuth("WmHaR9DdeX83Vs3ULFd8UPtB4fDP", "ddbd6de1beb66337604569a3572084e9513301430812fa605cd8e4e037c6b63a") .UseClientCredentials("user.subaccounts", "user.payout-settings") .ExecuteAsync("https://api.sumup.com/token"); var sumUpClient = new SumupClient(new HttpClientFactory()); var r = await sumUpClient.AddClient(new AddClientParameter { AccessToken = result.AccessToken, Id = Guid.NewGuid().ToString(), Name = "Thierry Habart", Phone = "0485350536" }); var res = await sumUpClient.AddClientPayment(r.CustomerId, new AddClientPaymentParameter { AccessToken = result.AccessToken }); string s = ""; }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string authorization = Request.Headers["Authorization"]; if (string.IsNullOrWhiteSpace(authorization)) { return(AuthenticateResult.NoResult()); } string token = null; if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { token = authorization.Substring("Bearer ".Length).Trim(); } if (string.IsNullOrEmpty(token)) { return(AuthenticateResult.NoResult()); } var factory = new IdentityServerClientFactory(); try { var introspectionResult = await factory.CreateAuthSelector() .UseClientSecretPostAuth(Options.ClientId, Options.ClientSecret) .Introspect(token, TokenType.AccessToken) .ResolveAsync(Options.WellKnownConfigurationUrl); if (introspectionResult.ContainsError || !introspectionResult.Content.Active) { return(AuthenticateResult.NoResult()); } var claims = new List <Claim> { new Claim(StandardClaimNames.ExpirationTime, introspectionResult.Content.Expiration.ToString()), new Claim(StandardClaimNames.Iat, introspectionResult.Content.IssuedAt.ToString()) }; if (!string.IsNullOrWhiteSpace(introspectionResult.Content.Subject)) { claims.Add(new Claim(Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject, introspectionResult.Content.Subject)); } if (!string.IsNullOrWhiteSpace(introspectionResult.Content.ClientId)) { claims.Add(new Claim(StandardClaimNames.ClientId, introspectionResult.Content.ClientId)); } if (!string.IsNullOrWhiteSpace(introspectionResult.Content.Issuer)) { claims.Add(new Claim(StandardClaimNames.Issuer, introspectionResult.Content.Issuer)); } if (introspectionResult.Content.Scope != null) { foreach (var scope in introspectionResult.Content.Scope) { claims.Add(new Claim(StandardClaimNames.Scopes, scope)); } } var claimsIdentity = new ClaimsIdentity(claims, OAuth2IntrospectionOptions.AuthenticationScheme); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authenticationTicket = new AuthenticationTicket( claimsPrincipal, new AuthenticationProperties(), OAuth2IntrospectionOptions.AuthenticationScheme); return(AuthenticateResult.Success(authenticationTicket)); } catch (Exception) { return(AuthenticateResult.NoResult()); } }
public FakeOAuth2IntrospectionOptions() { IdentityServerClientFactory = new IdentityServerClientFactory(); }