コード例 #1
0
        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 = "";
        }
コード例 #2
0
        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"));
        }
コード例 #3
0
        public async Task <GrantedTokenResponse> GetOfficeDocumentAccessTokenViaUmaGrantType(string umaResourceId)
        {
            var token = _tokens.FirstOrDefault(t => t.UmaResourceId == umaResourceId);

            if (token != null)
            {
                if (DateTime.UtcNow < token.ExpirationDateTime)
                {
                    return(token.GrantedToken);
                }

                _tokens.Remove(token);
            }

            var tokenResponse = await _accessTokenStore.GetToken(Constants.UmaWellKnownConfiguration, Constants.ClientId, Constants.ClientSecret, new[] { "uma_protection" }).ConfigureAwait(false);

            if (tokenResponse == null)
            {
                return(null);
            }

            var permissionResponse = await _identityServerUmaClientFactory.GetPermissionClient().AddByResolution(new PostPermission
            {
                ResourceSetId = umaResourceId,
                Scopes        = new[] { "read" }
            }, Constants.UmaWellKnownConfiguration, tokenResponse.AccessToken).ConfigureAwait(false);

            if (permissionResponse.ContainsError)
            {
                return(null);
            }

            var grantedToken = await _identityServerClientFactory.CreateAuthSelector().UseClientSecretPostAuth(Constants.ClientId, Constants.ClientSecret).UseTicketId(permissionResponse.Content.TicketId, _authenticationStore.IdentityToken)
                               .ResolveAsync(Constants.UmaWellKnownConfiguration)
                               .ConfigureAwait(false);

            if (grantedToken.ContainsError)
            {
                return(null);
            }

            var result = new StoredUmaAccessToken
            {
                ExpirationDateTime = DateTime.UtcNow.AddSeconds(grantedToken.Content.ExpiresIn),
                GrantedToken       = grantedToken.Content,
                UmaResourceId      = umaResourceId
            };

            _tokens.Add(result);
            return(grantedToken.Content);
        }
コード例 #4
0
        [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);
        }
コード例 #5
0
        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 = "";
        }
コード例 #6
0
        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 = "";
        }
コード例 #7
0
        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 = "";
        }
コード例 #8
0
        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());
            }
        }