Пример #1
0
        public async Task When_No_Client_Secret_Is_Passed_Then_Not_Authorized_Is_Returned()
        {
            // ARRANGE
            var introspectionResponse = new IntrospectionResponse
            {
                Active = true,
                Scope  = new List <string> {
                    "GetMethod"
                }
            };
            var options = new Oauth2IntrospectionOptions
            {
                InstrospectionEndPoint = "http://localhost:5000/introspect",
                ClientId = "client_id"
            };
            var createServer       = CreateServer(options);
            var client             = createServer.CreateClient();
            var httpRequestMessage = new HttpRequestMessage();

            httpRequestMessage.Headers.Add("Authorization", "Bearer accessToken");
            httpRequestMessage.Method     = HttpMethod.Get;
            httpRequestMessage.RequestUri = new Uri("http://localhost/protectedoperation");

            // ACT
            var result = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);

            // ASSERT
            Assert.NotNull(result);
            Assert.True(result.StatusCode == HttpStatusCode.Unauthorized);
        }
Пример #2
0
        public async Task ValidateToken_InvalidToken_ActiveFalse()
        {
            // Arrrange
            string accessToken = "invalidRandomToken";

            EFormidlingAccessValidator sut = new EFormidlingAccessValidator(GetMockObjectWithResponse(false), _loggerMock.Object);

            // Act
            IntrospectionResponse actual = await sut.ValidateToken(accessToken);

            // Assert
            Assert.False(actual.Active);
        }
Пример #3
0
        public async Task ValidateToken_ValidToken_ActiveTrue()
        {
            // Arrrange
            string expectedIssuer = "studio";

            string accessToken = JwtTokenMock.GenerateAccessToken("studio", "studio.designer", TimeSpan.FromMinutes(2));

            EFormidlingAccessValidator sut = new EFormidlingAccessValidator(GetMockObjectWithResponse(true), _loggerMock.Object);

            // Act
            IntrospectionResponse actual = await sut.ValidateToken(accessToken);

            // Assert
            Assert.True(actual.Active);
            Assert.Equal(expectedIssuer, actual.Iss);
        }
Пример #4
0
        public async Task ValidateToken_TokenHintEFormidling_EFormidlingServiceCalled()
        {
            // Arrange
            IntrospectionResponse expected = new()
            {
                Active = true,
                Iss    = "digdir"
            };

            _eformidlingValidatorService.Setup(efvs => efvs.ValidateToken(It.IsAny <string>())).ReturnsAsync(new IntrospectionResponse
            {
                Active = true,
                Iss    = "digdir"
            });

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, _baseUrl)
            {
                Content = new FormUrlEncodedContent(new Dictionary <string, string>()
                {
                    { "token", "thisIsMyRandomToken" },
                    { "token_type_hint", "eFormidlingAccessToken" }
                }),
            };

            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            HttpClient client = GetTestClient(_eformidlingValidatorService.Object);

            string token = JwtTokenMock.GenerateToken(_testPrincipal, TimeSpan.FromMinutes(2));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Act
            HttpResponseMessage res = await client.SendAsync(requestMessage);

            string responseString = await res.Content.ReadAsStringAsync();

            IntrospectionResponse actual = JsonSerializer.Deserialize <IntrospectionResponse>(responseString, _options);

            // Assert
            Assert.Equal(HttpStatusCode.OK, res.StatusCode);
            AdvancedAsserts.Equal(expected, actual);
            _eformidlingValidatorService.Verify(efvs => efvs.ValidateToken(It.IsAny <string>()), Times.Once());
        }
Пример #5
0
        public async Task ValidateToken_ValidationThrowsException_ActiveFalse()
        {
            // Arrrange
            string accessToken = "validTokenInvalidIssuer";

            EFormidlingAccessValidator sut = new EFormidlingAccessValidator(GetMockObjectWithResponse(false, true), _loggerMock.Object);

            // Act
            IntrospectionResponse actual = await sut.ValidateToken(accessToken);

            // Assert
            _loggerMock.Verify(
                x => x.Log(
                    LogLevel.Information,
                    It.IsAny <EventId>(),
                    It.IsAny <It.IsAnyType>(),
                    It.IsAny <Exception>(),
                    (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                Times.Once);

            Assert.False(actual.Active);
        }
Пример #6
0
        public async Task When_Passing_NotWellFormed_TokenIntrospectionEndPoint_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            var introspectionResponse = new IntrospectionResponse
            {
                Active = true,
                Scope  = new List <string> {
                    "GetMethod"
                }
            };
            var json = JsonConvert.SerializeObject(introspectionResponse);
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json)
            };
            var fakeHttpHandler = new FakeHttpMessageHandler(httpResponseMessage);
            var options         = new Oauth2IntrospectionOptions
            {
                InstrospectionEndPoint = "invalid_url",
                ClientId               = "MyBlog",
                ClientSecret           = "MyBlog",
                BackChannelHttpHandler = fakeHttpHandler
            };
            var createServer       = CreateServer(options);
            var client             = createServer.CreateClient();
            var httpRequestMessage = new HttpRequestMessage();

            httpRequestMessage.Headers.Add("Authorization", "Bearer accessToken");
            httpRequestMessage.Method     = HttpMethod.Get;
            httpRequestMessage.RequestUri = new Uri("http://localhost/protectedoperation");

            // ACT
            var result = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);

            // ASSERTS
            Assert.NotNull(result);
            Assert.True(result.StatusCode == HttpStatusCode.Unauthorized);
        }
        public async Task <IEnumerable <IntrospectionResponse> > Execute(IEnumerable <string> rpts)
        {
            if (rpts == null || !rpts.Any())
            {
                throw new ArgumentNullException(nameof(rpts));
            }

            var concatenatedRpts = string.Join(",", rpts);

            _umaServerEventSource.StartToIntrospect(concatenatedRpts);
            var rptsInformation = await _rptRepository.Get(rpts);

            if (rptsInformation == null || !rptsInformation.Any())
            {
                throw new BaseUmaException(ErrorCodes.InvalidRpt,
                                           string.Format(ErrorDescriptions.TheRptsDontExist, concatenatedRpts));
            }

            var tickets = await _ticketRepository.Get(rptsInformation.Select(r => r.TicketId));

            if (tickets == null || !tickets.Any() || tickets.Count() != rptsInformation.Count())
            {
                throw new BaseUmaException(ErrorCodes.InternalError,
                                           ErrorDescriptions.AtLeastOneTicketDoesntExist);
            }

            var result = new List <IntrospectionResponse>();

            foreach (var rptInformation in rptsInformation)
            {
                var record = new IntrospectionResponse
                {
                    Expiration = rptInformation.ExpirationDateTime.ConvertToUnixTimestamp(),
                    IssuedAt   = rptInformation.CreateDateTime.ConvertToUnixTimestamp()
                };

                var ticket = tickets.First(t => t.Id == rptInformation.TicketId);
                if (rptInformation.ExpirationDateTime < DateTime.UtcNow ||
                    ticket.ExpirationDateTime < DateTime.UtcNow)
                {
                    _umaServerEventSource.RptHasExpired(rptInformation.Value);
                    record.IsActive = false;
                }
                else
                {
                    record.Permissions = new List <PermissionResponse>
                    {
                        new PermissionResponse
                        {
                            ResourceSetId = rptInformation.ResourceSetId,
                            Scopes        = ticket.Scopes,
                            Expiration    = ticket.ExpirationDateTime.ConvertToUnixTimestamp()
                        }
                    };

                    record.IsActive = true;
                }

                result.Add(record);
            }

            _umaServerEventSource.EndIntrospection(JsonConvert.SerializeObject(result));
            return(result);
        }
Пример #8
0
        public async Task When_Permissions_Are_Returned_Then_Claims_Are_Added()
        {
            // ARRANGE
            var introspectionResponse = new IntrospectionResponse
            {
                IsActive    = true,
                Permissions = new List <PermissionResponse>
                {
                    new PermissionResponse
                    {
                        ResourceSetId = "resource_set_id",
                        Scopes        = new List <string>
                        {
                            "execute"
                        }
                    }
                }
            };
            var searchOperationResponse = new List <ResourceResponse>
            {
                new ResourceResponse
                {
                    ResourceSetId = "resource_set_id"
                }
                // ApplicationName = "application_name",
                // OperationName = "operation_name"
            };
            var stubIdentityServerUmaClientFactory = new Mock <IIdentityServerUmaClientFactory>();
            var stubIntrospectionClient            = new Mock <IIntrospectionClient>();

            stubIntrospectionClient
            .Setup(s => s.GetByResolution(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(introspectionResponse);
            stubIdentityServerUmaClientFactory
            .Setup(s => s.GetIntrospectionClient())
            .Returns(() => stubIntrospectionClient.Object);
            var stubIdentityServerUmaManagerClientFactory = new Mock <IIdentityServerUmaManagerClientFactory>();
            var stubOperationClient = new Mock <IResourceClient>();

            stubOperationClient.Setup(s => s.SearchResources(It.IsAny <SearchResourceRequest>(), It.IsAny <Uri>(), It.IsAny <string>()))
            .ReturnsAsync(searchOperationResponse);
            stubIdentityServerUmaManagerClientFactory.Setup(s => s.GetResourceClient())
            .Returns(stubOperationClient.Object);
            var umaIntrospectionOptions = new UmaIntrospectionOptions
            {
                UmaConfigurationUrl = "http://localhost/uma",
                ResourcesUrl        = "http://localhost/resources",
                IdentityServerUmaManagerClientFactory = stubIdentityServerUmaManagerClientFactory.Object,
                IdentityServerUmaClientFactory        = stubIdentityServerUmaClientFactory.Object
            };
            var createServer       = CreateServer(umaIntrospectionOptions);
            var httpRequestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri("http://localhost/operation")
            };

            httpRequestMessage.Headers.Add("Authorization", "Bearer RPT");
            var client = createServer.CreateClient();

            // ACT
            var result = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);

            // ASSERT
            Assert.True(result.StatusCode == HttpStatusCode.OK);
        }
Пример #9
0
 /// <summary>
 /// Asserts that two introspection responses as equal
 /// </summary>
 public static void Equal(IntrospectionResponse expected, IntrospectionResponse actual)
 {
     Assert.Equal(expected.Active, actual.Active);
     Assert.Equal(expected.Iss, actual.Iss);
 }