Пример #1
0
 public UserInfoClientFixture(ITestOutputHelper outputHelper)
 {
     _server         = new TestOauthServerFixture(outputHelper);
     _userInfoClient = new TokenClient(
         TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
         _server.Client, new Uri(BaseUrl + WellKnownOpenidConfiguration));
 }
Пример #2
0
        public void InvalidRedirectUri()
        {
            TokenClient client = null !;

            Option <Uri> .Error result = null !;

            "and an improperly configured authorization client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials(string.Empty, string.Empty),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting authorization".x(
                async() =>
            {
                var pkce = CodeChallengeMethods.S256.BuildPkce();
                result   = await client.GetAuthorization(
                    new AuthorizationRequest(
                        new[] { "api1" },
                        new[] { ResponseTypeNames.Code },
                        "authcode_client",
                        new Uri("http://localhost:1000/callback"),
                        pkce.CodeChallenge,
                        CodeChallengeMethods.S256,
                        "abc"))
                           .ConfigureAwait(false) as Option <Uri> .Error;
            });

            "then has expected error message".x(
                () => { Assert.Equal(ErrorCodes.InvalidRequest, result.Details.Title); });
        }
Пример #3
0
        public void SuccessfulAuthorizationCodeGrant()
        {
            TokenClient client = null !;
            Uri         result = null !;

            "and a properly configured auth client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials(string.Empty, string.Empty),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting authorization".x(
                async() =>
            {
                var pkce     = CodeChallengeMethods.S256.BuildPkce();
                var response = await client.GetAuthorization(
                    new AuthorizationRequest(
                        new[] { "api1" },
                        new[] { ResponseTypeNames.Code },
                        "authcode_client",
                        new Uri("http://localhost:5000/callback"),
                        pkce.CodeChallenge,
                        CodeChallengeMethods.S256,
                        "abc"))
                               .ConfigureAwait(false) as Option <Uri> .Result;

                Assert.NotNull(response);

                result = response !.Item;
            });

            "then has authorization uri".x(() => { Assert.NotNull(result); });
        }
Пример #4
0
 private TokenClient CreateTokenClient()
 {
     return(new(
                TokenCredentials.FromClientCredentials("client", "client"),
                _server.Client,
                new Uri(BaseUrl + "/.well-known/openid-configuration")));
 }
Пример #5
0
        public void CanGetUserInfoFromPatToken()
        {
            TokenClient client = null !;
            string      token  = null !;

            "Given a token client".x(
                () =>
            {
                client = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));
            });

            "When getting a PAT token".x(
                async() =>
            {
                var response = await client.GetToken(
                    TokenRequest.FromPassword("administrator", "password", new[] { "uma_protection" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                token = response.Item.AccessToken;

                Assert.NotNull(token);
            });

            "Then can get user information".x(
                async() =>
            {
                var userInfo = await client.GetUserInfo(token).ConfigureAwait(false)
                               as Option <JwtPayload> .Result;

                Assert.NotNull(userInfo);
                Assert.NotNull(userInfo.Item.Sub);
            });
        }
Пример #6
0
        public async Task When_Registering_A_Client_Then_No_Exception_Is_Thrown()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("stateless_client", "stateless_client"),
                _server.Client,
                new Uri($"{BaseUrl}/.well-known/openid-configuration"));
            var grantedToken =
                await tokenClient.GetToken(TokenRequest.FromScopes("manager")).ConfigureAwait(false) as
                Option <GrantedTokenResponse> .Result;

            var registrationClient = await ManagementClient.Create(
                _server.Client,
                new Uri($"{BaseUrl}/.well-known/openid-configuration"))
                                     .ConfigureAwait(false);

            var client = await registrationClient.Register(
                new Client
            {
                JsonWebKeys     = TestKeys.SecretKey.CreateSignatureJwk().ToSet(),
                AllowedScopes   = new[] { "openid" },
                ClientName      = "Test",
                ClientId        = "id",
                RedirectionUrls = new[] { new Uri("https://localhost"), },
                RequestUris     = new[] { new Uri("https://localhost") },
            },
                grantedToken.Item.AccessToken)
                         .ConfigureAwait(false) as Option <Client> .Result;

            Assert.NotNull(client);
        }
Пример #7
0
        public void SuccessfulResourceOwnerRevocation()
        {
            TokenClient          client = null !;
            GrantedTokenResponse result = null !;

            "and a properly token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting auth token".x(
                async() =>
            {
                var response =
                    await client.GetToken(TokenRequest.FromScopes("api1", "offline")).ConfigureAwait(false) as
                    Option <GrantedTokenResponse> .Result;

                Assert.NotNull(response);

                result = response.Item;
            });

            "then can revoke token".x(
                async() =>
            {
                var response = await client.RevokeToken(RevokeTokenRequest.Create(result)).ConfigureAwait(false);
                Assert.IsType <Option.Success>(response);
            });
        }
Пример #8
0
        public async Task When_Empty_Json_Request_Is_Passed_To_Registration_Api_Then_Error_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("stateless_client", "stateless_client"),
                _server.Client,
                new Uri($"{BaseUrl}/.well-known/openid-configuration"));
            var grantedToken = await tokenClient.GetToken(TokenRequest.FromScopes("register_client"))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var obj      = new { fake = "fake" };
            var fakeJson = JsonConvert.SerializeObject(
                obj,
                new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            var httpRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"{BaseUrl}/clients"),
                Content    = new StringContent(fakeJson)
            };

            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpRequest.Headers.Authorization       = new AuthenticationHeaderValue("Bearer", grantedToken.Item.AccessToken);

            var httpResult = await _server.Client().SendAsync(httpRequest).ConfigureAwait(false);

            Assert.Equal(HttpStatusCode.BadRequest, httpResult.StatusCode);
        }
Пример #9
0
        public void SuccessfulMultiplePermissionsCreation()
        {
            GrantedTokenResponse grantedToken = null !;
            UmaClient            client       = null !;
            string resourceId = null !;
            string ticketId   = null !;

            "and a valid UMA token".x(
                async() =>
            {
                var tokenClient = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    Fixture.Client,
                    new Uri(WellKnownUmaConfiguration));
                var token = await tokenClient.GetToken(TokenRequest.FromScopes("uma_protection"))
                            .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                grantedToken = token !.Item;

                Assert.NotNull(grantedToken);
            });

            "and a properly configured uma client".x(
                () => client = new UmaClient(Fixture.Client, new Uri(WellKnownUmaConfiguration)));

            "when registering resource".x(
                async() =>
            {
                var resource = await client.AddResource(
                    new ResourceSet {
                    Name = "picture", Scopes = new[] { "read", "write" }
                },
                    grantedToken.AccessToken)
                               .ConfigureAwait(false) as Option <AddResourceSetResponse> .Result;
                resourceId = resource !.Item.Id;

                Assert.NotNull(resourceId);
            });

            "and adding permission".x(
                async() =>
            {
                var response = await client.RequestPermission(
                    grantedToken.AccessToken,
                    CancellationToken.None,
                    new PermissionRequest {
                    ResourceSetId = resourceId, Scopes = new[] { "write" }
                },
                    new PermissionRequest {
                    ResourceSetId = resourceId, Scopes = new[] { "read" }
                })
                               .ConfigureAwait(false) as Option <TicketResponse> .Result;

                ticketId = response !.Item.TicketId;

                Assert.NotNull(ticketId);
            });

            "then returns ticket id".x(() => { Assert.NotNull(ticketId); });
        }
Пример #10
0
        public void SuccessfulPermissionCreation()
        {
            GrantedTokenResponse grantedToken = null !;
            UmaClient            client       = null !;
            JsonWebKeySet        jwks         = null !;
            string resourceId = null !;
            string ticketId   = null !;

            "and the server's signing key".x(
                async() =>
            {
                var json = await _fixture.Client().GetStringAsync(BaseUrl + "/jwks").ConfigureAwait(false);
                jwks     = new JsonWebKeySet(json);

                Assert.NotEmpty(jwks.Keys);
            });

            "and a valid UMA token".x(
                async() =>
            {
                var tokenClient = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    _fixture.Client,
                    new Uri(WellKnownUmaConfiguration));
                var token = await tokenClient.GetToken(TokenRequest.FromScopes("uma_protection"))
                            .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                grantedToken = token !.Item;
            });

            "and a properly configured uma client".x(
                () => client = new UmaClient(_fixture.Client, new Uri(WellKnownUmaConfiguration)));

            "when registering resource".x(
                async() =>
            {
                var resource = await client.AddResource(
                    new ResourceSet {
                    Name = "picture", Scopes = new[] { "read" }
                },
                    grantedToken.AccessToken)
                               .ConfigureAwait(false) as Option <AddResourceSetResponse> .Result;
                resourceId = resource.Item.Id;
            });

            "and adding permission".x(
                async() =>
            {
                var response = await client.RequestPermission(
                    grantedToken.AccessToken,
                    requests: new PermissionRequest {
                    ResourceSetId = resourceId, Scopes = new[] { "read" }
                })
                               .ConfigureAwait(false) as Option <TicketResponse> .Result;

                ticketId = response !.Item.TicketId;
            });

            "then returns ticket id".x(() => { Assert.NotNull(ticketId); });
        }
Пример #11
0
        public async Task When_Using_ClientCredentials_Grant_Type_Then_AccessToken_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("resource_server", "resource_server"),
                _server.Client,
                new Uri(BaseUrl + WellKnownUma2Configuration));
            var result = await tokenClient.GetToken(TokenRequest.FromScopes("uma_protection", "uma_authorization"))
                         .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            Assert.NotEmpty(result.Item.AccessToken);
        }
Пример #12
0
        public async Task WhenPassingClientAccessTokenToUserInfoThenClientClaimsAreReturned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("stateless_client", "stateless_client"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var result = await tokenClient.GetToken(TokenRequest.FromScopes("openid")).ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var getUserInfoResult = await _userInfoClient.GetUserInfo(result.Item.AccessToken).ConfigureAwait(false);

            Assert.IsType <Option <JwtPayload> .Result>(getUserInfoResult);
        }
Пример #13
0
        public async Task When_Revoke_Token_And_Client_Cannot_Be_Authenticated_Then_Error_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("invalid_client", "invalid_client"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var ex = await tokenClient.RevokeToken(RevokeTokenRequest.Create("access_token", TokenTypes.AccessToken))
                     .ConfigureAwait(false) as Option.Error;

            Assert.Equal("invalid_client", ex.Details.Title);
            Assert.Equal(SharedStrings.TheClientDoesntExist, ex.Details.Detail);
        }
Пример #14
0
        public async Task WhenIntrospectingAndTokenDoesNotExistThenResponseShowsInactiveToken()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("client", "client"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var introspection = await tokenClient.Introspect(
                IntrospectionRequest.Create("invalid_token", TokenTypes.AccessToken, "pat"))
                                .ConfigureAwait(false) as Option <OauthIntrospectionResponse> .Result;

            Assert.False(introspection.Item.Active);
        }
Пример #15
0
        public async Task When_Ticket_Id_Does_Not_Exist_Then_Error_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("resource_server", "resource_server"),
                _server.Client,
                new Uri(BaseUrl + WellKnownUma2Configuration));
            // Try to get the access token via "ticket_id" grant-type.
            var token =
                await tokenClient.GetToken(TokenRequest.FromTicketId("ticket_id", "")).ConfigureAwait(false) as
                Option <GrantedTokenResponse> .Error;

            Assert.Equal(ErrorCodes.InvalidGrant, token.Details.Title);
            Assert.Equal(string.Format(Strings.TheTicketDoesntExist, "ticket_id"), token.Details.Detail);
        }
Пример #16
0
        public async Task When_Pass_Access_Token_Then_Jwe_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("client_userinfo_enc_rsa15", "client_userinfo_enc_rsa15"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var result = await tokenClient
                         .GetToken(TokenRequest.FromPassword("administrator", "password", new[] { "scim" }))
                         .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var getUserInfoResult = await _userInfoClient.GetUserInfo(result.Item.AccessToken).ConfigureAwait(false);

            Assert.IsType <Option <JwtPayload> .Result>(getUserInfoResult);
        }
Пример #17
0
        public async Task When_Pass_Redirect_Uri_With_Fragment_Then_Error_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("stateless_client", "stateless_client"),
                _server.Client,
                new Uri($"{BaseUrl}/.well-known/openid-configuration"));
            var grantedToken = await tokenClient.GetToken(TokenRequest.FromScopes("register_client"))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var obj = new
            {
                JsonWebKeys     = TestKeys.SecretKey.CreateSignatureJwk().ToSet(),
                AllowedScopes   = new[] { "openid" },
                RequestUris     = new[] { new Uri("https://localhost") },
                RedirectionUrls = new[] { new Uri("http://localhost#fragment") },
                //LogoUri = "http://google.com",
                ClientUri = new Uri("https://valid")
            };
            var fakeJson = JsonConvert.SerializeObject(
                obj,
                new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            var httpRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"{BaseUrl}/registration"),
                Content    = new StringContent(fakeJson)
            };

            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(ApplicationJson);
            httpRequest.Headers.Authorization       = new AuthenticationHeaderValue(
                grantedToken.Item.TokenType,
                grantedToken.Item.AccessToken);

            var httpResult = await _server.SharedCtx.Client().SendAsync(httpRequest).ConfigureAwait(false);

            //Assert.Equal(HttpStatusCode.OK, httpResult.StatusCode);

            var json = await httpResult.Content.ReadAsStringAsync().ConfigureAwait(false);

            var error = JsonConvert.DeserializeObject <ErrorDetails>(json);

            Assert.Equal("invalid_redirect_uri", error !.Title);
            Assert.Equal(
                string.Format(Strings.TheRedirectUrlCannotContainsFragment, "http://localhost/#fragment"),
                error.Detail);
        }
Пример #18
0
        public void SuccessfulTokenValidationFromMetadata()
        {
            GrantedTokenResponse tokenResponse = null !;
            JsonWebKeySet        jwks          = null !;

            "And a valid token".x(
                async() =>
            {
                var tokenClient = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    Fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));
                var response =
                    await tokenClient.GetToken(TokenRequest.FromScopes("api1")).ConfigureAwait(false) as
                    Option <GrantedTokenResponse> .Result;

                Assert.NotNull(response);

                tokenResponse = response.Item;
            });

            "then can download json web key set".x(
                async() =>
            {
                var jwksJson = await Fixture.Client().GetStringAsync(BaseUrl + "/jwks").ConfigureAwait(false);

                Assert.NotNull(jwksJson);

                jwks = JsonWebKeySet.Create(jwksJson);
            });

            "Then can create token validation parameters from service metadata".x(
                () =>
            {
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = jwks.Keys,
                    ValidIssuer       = "https://localhost",
                    ValidAudience     = "clientCredentials"
                };

                var handler = new JwtSecurityTokenHandler();

                handler.ValidateToken(tokenResponse.AccessToken, validationParameters, out var securityToken);

                Assert.NotNull(securityToken);
            });
        }
        public void InvalidClientCredentials()
        {
            TokenClient client = null !;
            Option <GrantedTokenResponse> result = null !;

            "and a token client with invalid client credentials".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("xxx", "xxx"),
                    Fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting auth token".x(
                async() => { result = await client.GetToken(TokenRequest.FromScopes("pwd")).ConfigureAwait(false); });

            "then does not have token".x(() => { Assert.IsType <Option <GrantedTokenResponse> .Error>(result); });
        }
Пример #20
0
        public async Task CanGetToken()
        {
            var client = new TokenClient(
                TokenCredentials.FromClientCredentials("client", "secret"),
                () => new HttpClient(),
                new Uri("http://localhost:8080/.well-known/openid-configuration"));
            await _fixture.GetUser().ConfigureAwait(false);

            for (var i = 0; i < 100; i++)
            {
                var token = await client.GetToken(TokenRequest.FromPassword("user", "password", new[] { "read" }))
                            .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

                Assert.NotNull(token.Item);
            }
        }
Пример #21
0
        public async Task When_Introspecting_AccessToken_Then_Information_Are_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("client", "client"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var result =
                await tokenClient.GetToken(TokenRequest.FromPassword("administrator", "password", new[] { "scim" }))
                .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var introspection = await tokenClient.Introspect(
                IntrospectionRequest.Create(result.Item.AccessToken, TokenTypes.AccessToken, "pat"))
                                .ConfigureAwait(false) as Option <OauthIntrospectionResponse> .Result;

            Assert.Single(introspection.Item.Scope);
            Assert.Equal("scim", introspection.Item.Scope.First());
        }
        public void SuccessfulClientCredentialsAuthentication()
        {
            TokenClient          client = null !;
            GrantedTokenResponse result = null !;

            "and a properly configured token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting token".x(
                async() =>
            {
                var response =
                    await client.GetToken(TokenRequest.FromScopes("api1")).ConfigureAwait(false) as
                    Option <GrantedTokenResponse> .Result;

                Assert.NotNull(response);

                result = response.Item;
            });

            "then has valid access token".x(
                () =>
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = _jwks.GetSigningKeys(),
                    ValidAudience     = "clientCredentials",
                    ValidIssuer       = "https://localhost"
                };
                tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token);
            });

            "and can get user info".x(
                async() =>
            {
                var userinfo = await client.GetUserInfo(result.AccessToken).ConfigureAwait(false) as Option <JwtPayload> .Result;

                Assert.NotNull(userinfo);
                Assert.NotNull(userinfo.Item);
            });
        }
Пример #23
0
        public async Task WhenPassInvalidRedirectUrisThenErrorIsReturned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("stateless_client", "stateless_client"),
                _server.Client,
                new Uri($"{BaseUrl}/.well-known/openid-configuration"));
            var grantedToken =
                await tokenClient.GetToken(TokenRequest.FromScopes("manager")).ConfigureAwait(false) as
                Option <GrantedTokenResponse> .Result;

            var obj = new
            {
                allowed_scopes = new[] { "openid" },
                request_uris   = new[] { new Uri("https://localhost") },
                redirect_uris  = new[] { "localhost" },
                client_uri     = new Uri("http://google.com"),
                tos_uri        = new Uri("http://google.com"),
                jwks           = TestKeys.SecretKey.CreateSignatureJwk().ToSet()
            };
            var fakeJson = JsonConvert.SerializeObject(
                obj,
                new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            var httpRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"{BaseUrl}/clients"),
                Content    = new StringContent(fakeJson)
            };

            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpRequest.Headers.Authorization       = new AuthenticationHeaderValue("Bearer", grantedToken.Item.AccessToken);

            var httpResult = await _server.Client().SendAsync(httpRequest).ConfigureAwait(false);

            Assert.Equal(HttpStatusCode.BadRequest, httpResult.StatusCode);
            var json = await httpResult.Content.ReadAsStringAsync().ConfigureAwait(false);

            var error = JsonConvert.DeserializeObject <ErrorDetails>(json);

            Assert.Equal(ErrorCodes.InvalidRedirectUri, error !.Title);
        }
Пример #24
0
        public async Task When_Pass_Invalid_Tos_Uri_Then_Error_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("stateless_client", "stateless_client"),
                _server.Client,
                new Uri($"{BaseUrl}/.well-known/openid-configuration"));
            var grantedToken = await tokenClient.GetToken(TokenRequest.FromScopes("register_client"))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var obj = new
            {
                AllowedScopes   = new[] { "openid" },
                RequestUris     = new[] { new Uri("https://localhost") },
                RedirectionUrls = new[] { new Uri("http://localhost") },
                LogoUri         = new Uri("http://google.com"),
                ClientUri       = new Uri("https://valid_client_uri"),
                TosUri          = "invalid"
            };
            var fakeJson = JsonConvert.SerializeObject(
                obj,
                new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            var httpRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"{BaseUrl}/registration"),
                Content    = new StringContent(fakeJson)
            };

            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpRequest.Headers.Authorization       = new AuthenticationHeaderValue("Bearer", grantedToken.Item.AccessToken);

            var httpResult = await _server.Client().SendAsync(httpRequest).ConfigureAwait(false);

            var json = await httpResult.Content.ReadAsStringAsync().ConfigureAwait(false);

            var error = JsonConvert.DeserializeObject <ErrorDetails>(json);

            Assert.Equal("invalid_client_metadata", error !.Title);
            Assert.Equal("the parameter tos_uri is not correct", error.Detail);
        }
Пример #25
0
        public void WhenClientHasNoSigningKeysThenUsesServerKey()
        {
            TokenClient          client = null !;
            GrantedTokenResponse token  = null !;

            "Given a token client".x(
                () =>
            {
                client = new TokenClient(
                    TokenCredentials.FromClientCredentials("no_key", "no_key"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));
            });

            "When getting token".x(
                async() =>
            {
                var response = await client
                               .GetToken(TokenRequest.FromPassword("administrator", "password", new[] { "api" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                token = response.Item;

                Assert.NotNull(token);
            });

            "Then token is signed with server key".x(
                () =>
            {
                var key = _jwks.GetSignKeys().First();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey    = key,
                    ValidateAudience    = false,
                    ValidateActor       = false,
                    ValidateIssuer      = false,
                    ValidateLifetime    = false,
                    ValidateTokenReplay = false
                };
                var handler = new JwtSecurityTokenHandler();
                handler.ValidateToken(token.IdToken, validationParameters, out _);
            });
        }
Пример #26
0
        public async Task When_Revoke_Token_And_Client_Is_Different_Then_Error_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("client_userinfo_enc_rsa15", "client_userinfo_enc_rsa15"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var result = await tokenClient
                         .GetToken(TokenRequest.FromPassword("administrator", "password", new[] { "scim" }))
                         .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var revokeClient = new TokenClient(
                TokenCredentials.FromClientCredentials("client", "client"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var ex = await revokeClient
                     .RevokeToken(RevokeTokenRequest.Create(result.Item.AccessToken, TokenTypes.AccessToken))
                     .ConfigureAwait(false) as Option.Error;

            Assert.Equal("invalid_token", ex.Details.Title);
            Assert.Equal("The token has not been issued for the given client id 'client'", ex.Details.Detail);
        }
Пример #27
0
        public async Task When_Revoking_RefreshToken_Then_True_Is_Returned()
        {
            var tokenClient = new TokenClient(
                TokenCredentials.FromClientCredentials("client", "client"),
                _server.Client,
                new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var result = await tokenClient
                         .GetToken(TokenRequest.FromPassword("administrator", "password", new[] { "scim", "offline" }))
                         .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

            var revoke = await tokenClient
                         .RevokeToken(RevokeTokenRequest.Create(result.Item.RefreshToken, TokenTypes.RefreshToken))
                         .ConfigureAwait(false);

            var introspectClient = new UmaClient(_server.Client, new Uri(BaseUrl + WellKnownOpenidConfiguration));
            var ex = await introspectClient.Introspect(
                IntrospectionRequest.Create(result.Item.RefreshToken, TokenTypes.RefreshToken, "pat"))
                     .ConfigureAwait(false);

            Assert.IsType <Option.Success>(revoke);
            Assert.IsType <Option <UmaIntrospectionResponse> .Error>(ex);
        }
Пример #28
0
        public void SuccessfulTicketAuthentication()
        {
            GrantedTokenResponse   umaToken            = null !;
            AddResourceSetResponse resourceSetResponse = null !;
            UmaClient            umaClient             = null !;
            TokenClient          client = null !;
            GrantedTokenResponse result = null !;
            string ticketId             = null !;

            "and a properly configured token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("post_client", "post_client"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting token".x(
                async() =>
            {
                var response = await client
                               .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection", "offline" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                result = response.Item;
            });

            "then has valid access token".x(
                () =>
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = _jwks.GetSigningKeys(),
                    ValidAudience     = "post_client",
                    ValidIssuer       = "https://localhost"
                };
                tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token);

                Assert.NotEmpty(((JwtSecurityToken)token).Claims);
            });

            "given a uma client".x(
                () =>
            {
                umaClient = new UmaClient(
                    _fixture.Client,
                    new Uri("https://localhost/.well-known/uma2-configuration"));
            });

            "when creating resource set".x(
                async() =>
            {
                var resourceSet = new ResourceSet {
                    Name = "Local", Scopes = new[] { "api1" }, Type = "url",
                };

                var resourceResponse =
                    await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as
                    Option <AddResourceSetResponse> .Result;
                resourceSetResponse = resourceResponse.Item;

                Assert.NotNull(resourceResponse);
            });

            "and setting access policy".x(
                async() =>
            {
                var resourceSet = new ResourceSet
                {
                    Id     = resourceSetResponse.Id,
                    Name   = "Local",
                    Scopes = new[] { "api1" },
                    Type   = "url",
                    AuthorizationPolicies = new[]
                    {
                        new PolicyRule
                        {
                            Scopes = new[] { "api1" },
                            Claims = new[]
                            {
                                new ClaimData {
                                    Type = ClaimTypes.NameIdentifier, Value = "user"
                                }
                            },
                            ClientIdsAllowed             = new[] { "post_client" },
                            IsResourceOwnerConsentNeeded = false
                        }
                    }
                };
                var resourceResponse =
                    await umaClient.UpdateResource(resourceSet, result.AccessToken).ConfigureAwait(false) as
                    Option <UpdateResourceSetResponse> .Result;

                Assert.NotNull(resourceResponse);
            });

            "then can get redirection".x(
                async() =>
            {
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id)
                };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                var httpHeaderValueCollection = response.Headers.WwwAuthenticate;
                Assert.True(httpHeaderValueCollection != null);

                var match = Regex.Match(
                    httpHeaderValueCollection.First().Parameter,
                    ".+ticket=\"(.+)\".*",
                    RegexOptions.Compiled);
                ticketId = match.Groups[1].Value;
            });

            "when requesting token".x(
                async() =>
            {
                var response = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                umaToken = response.Item;

                Assert.NotNull(umaToken.AccessToken);
            });

            "then can get resource with token".x(
                async() =>
            {
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id)
                };
                request.Headers.Authorization = new AuthenticationHeaderValue(
                    umaToken.TokenType,
                    umaToken.AccessToken);
                var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false);
                var content  = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal("\"Hello\"", content);
            });
        }
Пример #29
0
        public void SuccessfulPermissionCreation()
        {
            TestServerFixture    fixture      = null !;
            GrantedTokenResponse grantedToken = null !;
            UmaClient            client       = null !;
            string resourceId = null !;
            string ticketId   = null !;

            "Given a running auth server".x(() => fixture = new TestServerFixture(_outputHelper, BaseUrl))
            .Teardown(() => fixture.Dispose());

            "and the server's signing key".x(
                async() =>
            {
                var json = await fixture.Client().GetStringAsync(BaseUrl + "/jwks").ConfigureAwait(false);
                var jwks = new JsonWebKeySet(json);

                Assert.NotEmpty(jwks.Keys);
            });

            "and a valid UMA token".x(
                async() =>
            {
                var tokenClient = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    fixture.Client,
                    new Uri(WellKnownUmaConfiguration));
                var token = await tokenClient.GetToken(TokenRequest.FromScopes("uma_protection"))
                            .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                var handler   = new JwtSecurityTokenHandler();
                var principal = handler.ReadJwtToken(token.Item.AccessToken);
                Assert.NotNull(principal.Issuer);
                grantedToken = token.Item;
            });

            "and a properly configured uma client".x(
                () => client = new UmaClient(fixture.Client, new Uri(WellKnownUmaConfiguration)));

            "when registering resource".x(
                async() =>
            {
                var resource = await client.AddResource(
                    new ResourceSet {
                    Name = "picture", Scopes = new[] { "read" }
                },
                    grantedToken.AccessToken)
                               .ConfigureAwait(false) as Option <AddResourceSetResponse> .Result;
                resourceId = resource.Item.Id;
            });

            "and adding permission".x(
                async() =>
            {
                var response = await client.RequestPermission(
                    grantedToken.AccessToken,
                    requests: new PermissionRequest {
                    IdToken = grantedToken.IdToken, ResourceSetId = resourceId, Scopes = new[] { "read" }
                })
                               .ConfigureAwait(false) as Option <TicketResponse> .Result;

                Assert.NotNull(response);

                ticketId = response.Item.TicketId;
            });

            "then returns ticket id".x(() => { Assert.NotNull(ticketId); });
        }
Пример #30
0
        public void CanRegisterAResourceForUserAndManagePolicies()
        {
            TokenClient            client              = null !;
            UmaClient              umaClient           = null !;
            GrantedTokenResponse   token               = null !;
            AddResourceSetResponse resourceSetResponse = null !;
            EditPolicyResponse     policyRules         = null !;

            "Given a token client".x(
                () =>
            {
                client = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));
            });

            "And a UMA client".x(() => { umaClient = new UmaClient(_fixture.Client, new Uri(BaseUrl)); });

            "When getting a PAT token".x(
                async() =>
            {
                var response = await client.GetToken(
                    TokenRequest.FromPassword("administrator", "password", new[] { "uma_protection" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                token = response.Item;

                Assert.NotNull(token);
            });

            "Then can register a resource".x(
                async() =>
            {
                var resource = new ResourceSet
                {
                    AuthorizationPolicies = new[]
                    {
                        new PolicyRule
                        {
                            ClientIdsAllowed             = new[] { "clientCredentials" },
                            IsResourceOwnerConsentNeeded = true,
                            Scopes = new[] { "read" }
                        }
                    },
                    Name   = "test resource",
                    Scopes = new[] { "read" },
                    Type   = "test"
                };
                var response = await umaClient.AddResource(resource, token.AccessToken).ConfigureAwait(false) as Option <AddResourceSetResponse> .Result;

                Assert.NotNull(response);

                resourceSetResponse = response.Item;
            });

            "And can view resource policies".x(
                async() =>
            {
                var msg = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri(resourceSetResponse.UserAccessPolicyUri)
                };
                msg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

                var policyResponse = await _fixture.Client().SendAsync(msg).ConfigureAwait(false);

                Assert.True(policyResponse.IsSuccessStatusCode);

                var content = await policyResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                policyRules = JsonConvert.DeserializeObject <EditPolicyResponse>(content);

                Assert.Single(policyRules !.Rules);
            });

            "And can update resource policies".x(
                async() =>
            {
                policyRules.Rules[0] = policyRules.Rules[0] with {
                    IsResourceOwnerConsentNeeded = false
                };

                var msg = new HttpRequestMessage
                {
                    Method     = HttpMethod.Put,
                    RequestUri = new Uri(resourceSetResponse.UserAccessPolicyUri),
                    Content    = new StringContent(JsonConvert.SerializeObject(policyRules))
                };
                msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

                var policyResponse = await _fixture.Client().SendAsync(msg).ConfigureAwait(false);

                Assert.True(policyResponse.IsSuccessStatusCode);
            });
        }