Ejemplo n.º 1
0
        public async Task AuthenticateEndUser_ServiceThrowsException_ReturnsNewToken()
        {
            // Arrange
            List <Claim> claims = new List <Claim>();

            string pid = "19108000239";
            string amr = "MinId-PIN";

            claims.Add(new Claim("pid", pid));
            claims.Add(new Claim("amr", amr));

            ClaimsIdentity identity = new ClaimsIdentity();

            identity.AddClaims(claims);
            ClaimsPrincipal externalPrincipal = new ClaimsPrincipal(identity);

            string externalToken = JwtTokenMock.GenerateToken(externalPrincipal, TimeSpan.FromMinutes(2));

            _userProfileService.Setup(u => u.GetUser(It.IsAny <string>())).Throws(new Exception());

            string     url    = "/authentication/api/v1/exchange/id-porten";
            HttpClient client = GetTestClient(_cookieDecryptionService.Object, _userProfileService.Object);

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

            // Act
            HttpResponseMessage response = await client.GetAsync(url);

            // Assert
            Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
        }
Ejemplo n.º 2
0
        public async Task AuthenticateExternalSystemToken_InvalidTokenProvider_NotAuthorized()
        {
            // Arrange
            List <Claim> claims = new List <Claim>
            {
                new Claim("testClaim1", "testClaim1"),
                new Claim("testClaim2", "testClaim2")
            };

            ClaimsIdentity identity = new ClaimsIdentity(OrganisationIdentity);

            identity.AddClaims(claims);
            ClaimsPrincipal externalPrincipal = new ClaimsPrincipal(identity);
            string          token             = JwtTokenMock.GenerateToken(externalPrincipal, TimeSpan.FromMinutes(2));

            HttpClient client = GetTestClient(_cookieDecryptionService.Object, _userProfileService.Object);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            string tokenProvider = "google";
            string url           = $"/authentication/api/v1/exchange/{tokenProvider}";

            string expectedMessage = $"Invalid token provider: {tokenProvider}. Trusted token providers are 'Maskinporten', 'Id-porten' and 'AltinnStudio'.";

            // Act
            HttpResponseMessage response = await client.GetAsync(url);

            string message = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.Equal(expectedMessage, message);
        }
Ejemplo n.º 3
0
        public static string GetToken(int userId, List <Claim> claims, int authenticationLevel = 2)
        {
            ClaimsPrincipal principal = GetUserPrincipal(userId, claims, authenticationLevel);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1));

            return(token);
        }
        public async Task AuthenticateOrganisation_RequestTestTokenWithValidExternalToken_ReturnsNewToken()
        {
            // Arrange
            List <Claim> claims = new List <Claim>();

            string orgNr    = "974760223";
            string brgOrgNr = "974760673";

            object iso6523Consumer = new
            {
                authority = "iso6523-actorid-upis",
                ID        = $"9908:{orgNr}"
            };

            object brgConsumer = new
            {
                authority = "iso6523-actorid-upis",
                ID        = $"9908:{brgOrgNr}"
            };

            claims.Add(new Claim("consumer", JsonConvert.SerializeObject(iso6523Consumer)));
            claims.Add(new Claim("client_orgno", orgNr));
            claims.Add(new Claim("scope", "altinn:instances.write altinn:instances.read"));

            ClaimsIdentity identity = new ClaimsIdentity(OrganisationIdentity);

            identity.AddClaims(claims);
            ClaimsPrincipal externalPrincipal = new ClaimsPrincipal(identity);

            string externalToken = JwtTokenMock.GenerateToken(externalPrincipal, TimeSpan.FromMinutes(2));

            Mock <ISblCookieDecryptionService> cookieDecryptionService = new Mock <ISblCookieDecryptionService>();

            HttpClient client = GetTestClient(cookieDecryptionService.Object);

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

            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "/authentication/api/v1/convert?test=true");

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

            // Assert
            string token = await response.Content.ReadAsStringAsync();

            ClaimsPrincipal principal = JwtTokenMock.ValidateToken(token);

            Assert.NotNull(principal);

            Assert.True(principal.HasClaim(c => c.Type == "urn:altinn:org"));

            Assert.Equal("ttd", principal.FindFirst(c => c.Type == "urn:altinn:org").Value);
        }
Ejemplo n.º 5
0
        public static string GetAccessToken(string issuer, string app)
        {
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(AccessTokenClaimTypes.App, app, ClaimValueTypes.String, issuer));
            ClaimsIdentity identity = new ClaimsIdentity("mock");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(0, 1, 5), issuer);

            return(token);
        }
Ejemplo n.º 6
0
        public async Task AuthenticateEndUser_RequestTokenWithValidExternalToken_ReturnsNewToken()
        {
            // Arrange
            string expectedAuthLevel = "4";

            List <Claim> claims = new List <Claim>();

            string pid = "19108000239";
            string amr = "MinId-PIN";
            string acr = "Level4";

            claims.Add(new Claim("pid", pid));
            claims.Add(new Claim("amr", amr));
            claims.Add(new Claim("acr", acr));

            ClaimsIdentity identity = new ClaimsIdentity();

            identity.AddClaims(claims);
            ClaimsPrincipal externalPrincipal = new ClaimsPrincipal(identity);

            UserProfile userProfile = new UserProfile {
                UserId = 20000, PartyId = 50001, UserName = "******"
            };

            _userProfileService.Setup(u => u.GetUser(It.IsAny <string>())).ReturnsAsync(userProfile);

            HttpClient client = GetTestClient(_cookieDecryptionService.Object, _userProfileService.Object);

            string externalToken = JwtTokenMock.GenerateToken(externalPrincipal, TimeSpan.FromMinutes(2));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", externalToken);
            string url = "/authentication/api/v1/exchange/id-porten";

            // Act
            HttpResponseMessage response = await client.GetAsync(url);

            // Assert
            string token = await response.Content.ReadAsStringAsync();

            ClaimsPrincipal principal             = JwtTokenMock.ValidateToken(token);
            SecurityToken   securityToken         = JwtTokenMock.GetSecurityToken(token);
            SecurityToken   securityTokenExternal = JwtTokenMock.GetSecurityToken(externalToken);

            Assert.NotNull(principal);

            Assert.True(principal.HasClaim(c => c.Type == "urn:altinn:userid"));
            Assert.True(principal.HasClaim(c => c.Type == "pid"));
            Assert.Equal(expectedAuthLevel, principal.FindFirstValue("urn:altinn:authlevel"));
            Assert.Equal(securityTokenExternal.ValidTo, securityToken.ValidTo);
        }
Ejemplo n.º 7
0
        public static string GetOrgToken(string org, int authenticationLevel = 3)
        {
            List <Claim> claims = new List <Claim>();
            string       issuer = "www.altinn.no";

            claims.Add(new Claim(AltinnCoreClaimTypes.Org, org, ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, "Mock", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, authenticationLevel.ToString(), ClaimValueTypes.Integer32, issuer));

            ClaimsIdentity identity = new ClaimsIdentity("mock");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1));

            return(token);
        }
Ejemplo n.º 8
0
        public static string GetAccessToken(string appId)
        {
            List <Claim> claims = new List <Claim>();
            string       issuer = "www.altinn.no";

            if (!string.IsNullOrEmpty(appId))
            {
                claims.Add(new Claim("urn:altinn:app", appId, ClaimValueTypes.String, issuer));
            }
            ClaimsIdentity identity = new ClaimsIdentity("mock-org");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1), issuer);

            return(token);
        }
Ejemplo n.º 9
0
        public static string GetOrgToken(string org, int orgNumber = 111111111, string scope = "altinn:appdeploy")
        {
            List <Claim> claims = new List <Claim>();
            string       issuer = "www.altinn.no";

            claims.Add(new Claim(AltinnCoreClaimTypesOrg, org, ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypesOrgNumber, orgNumber.ToString(), ClaimValueTypes.Integer32, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, "Mock", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, "3", ClaimValueTypes.Integer32, issuer));
            claims.Add(new Claim("urn:altinn:scope", scope, ClaimValueTypes.String, "maskinporten"));

            ClaimsIdentity identity = new ClaimsIdentity("mock-org");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1));

            return(token);
        }
Ejemplo n.º 10
0
        public static string GetToken(int userId, int authenticationLevel = 2)
        {
            List <Claim> claims = new List <Claim>();
            string       issuer = "www.altinn.no";

            claims.Add(new Claim(AltinnCoreClaimTypes.UserId, userId.ToString(), ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.UserName, "UserOne", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.PartyID, userId.ToString(), ClaimValueTypes.Integer32, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, "Mock", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, authenticationLevel.ToString(), ClaimValueTypes.Integer32, issuer));

            ClaimsIdentity identity = new ClaimsIdentity("mock");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(0, 1, 5));

            return(token);
        }
Ejemplo n.º 11
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());
        }
Ejemplo n.º 12
0
        public static string GetSelfIdentifiedUserToken(
            string username, string partyId, string userId)
        {
            List <Claim> claims = new List <Claim>();
            string       issuer = "www.altinn.no";

            claims.Add(new Claim(ClaimTypes.NameIdentifier, userId.ToString(), ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.UserId, userId.ToString(), ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.UserName, username, ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.PartyID, partyId.ToString(), ClaimValueTypes.Integer32, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, "Mock", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, "0", ClaimValueTypes.Integer32, issuer));

            ClaimsIdentity identity = new ClaimsIdentity("mock");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1));

            return(token);
        }
Ejemplo n.º 13
0
        public async Task AuthenticateEnterpriseUser_RequestToken_ReturnsTooManyRequests()
        {
            // Arrange
            List <Claim> claims = new List <Claim>();

            string orgNr = "974760223";

            object iso6523Consumer = new
            {
                authority = "iso6523-actorid-upis",
                ID        = $"9908:{orgNr}"
            };

            claims.Add(new Claim("consumer", JsonConvert.SerializeObject(iso6523Consumer)));
            claims.Add(new Claim("client_orgno", orgNr));
            claims.Add(new Claim("scope", "altinn:instances.write altinn:instances.read"));
            claims.Add(new Claim("iss", "https://ver2.maskinporten.no/"));

            ClaimsIdentity identity = new ClaimsIdentity(OrganisationIdentity);

            identity.AddClaims(claims);
            ClaimsPrincipal externalPrincipal = new ClaimsPrincipal(identity);

            string externalToken = JwtTokenMock.GenerateToken(externalPrincipal, TimeSpan.FromMinutes(2));

            HttpClient client = GetTestClient(_cookieDecryptionService.Object, _userProfileService.Object);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", externalToken);
            client.DefaultRequestHeaders.Add("X-Altinn-EnterpriseUser-Authentication", "VGVzdDpUZXN0ZXNlbg==");

            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "/authentication/api/v1/exchange/maskinporten");

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

            // Assert
            Assert.Equal(HttpStatusCode.TooManyRequests, response.StatusCode);
            Assert.NotNull(response.Headers.RetryAfter);
        }
        private string GetUserToken(int userId)
        {
            List <Claim> claims = new List <Claim>();
            string       issuer = "www.altinn.no";

            if (userId != -1)
            {
                claims.Add(new Claim(AltinnCoreClaimTypes.UserId, userId.ToString(), ClaimValueTypes.String, issuer));
            }

            claims.Add(new Claim(AltinnCoreClaimTypes.UserName, "UserOne", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.PartyID, (userId + 5000).ToString(), ClaimValueTypes.Integer32, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, "Mock", ClaimValueTypes.String, issuer));
            claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, "2", ClaimValueTypes.Integer32, issuer));

            ClaimsIdentity identity = new ClaimsIdentity("mock");

            identity.AddClaims(claims);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            string          token     = JwtTokenMock.GenerateToken(principal);

            return(token);
        }