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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
public async Task AuthenticateStudioToken_InvalidToken_ReturnsUnauthorized() { // Arrange string accessToken = JwtTokenMock.GenerateAccessToken("studio", "studio.designer", TimeSpan.FromMinutes(2)); HttpClient client = GetTestClient(_cookieDecryptionService.Object, _userProfileService.Object); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Substring(3)); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "/authentication/api/v1/exchange/altinnstudio"); // Act HttpResponseMessage response = await client.SendAsync(requestMessage); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); }
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()); }
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); }
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); }
public void TokenMock_VerifyEncryptedAndSignedToken() { // 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.GenerateEncryptedAndSignedToken(externalPrincipal, TimeSpan.FromMinutes(2)); ClaimsPrincipal claimsPrincipal = JwtTokenMock.ValidateEncryptedAndSignedToken(externalToken); Assert.Equal(externalPrincipal.Identity.Name, claimsPrincipal.Identity.Name); }
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); }
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); }
public async Task AuthenticateStudioToken_ValidToken_ReturnsNewToken() { // Arrange string accessToken = JwtTokenMock.GenerateAccessToken("studio", "studio.designer", TimeSpan.FromMinutes(2)); HttpClient client = GetTestClient(_cookieDecryptionService.Object, _userProfileService.Object); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "/authentication/api/v1/exchange/altinnstudio"); // 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:app")); }
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); }
public async Task AuthenticateUser_RequestTokenWithValidAltinnCookie_ReturnsNewToken() { // Arrange UserAuthenticationModel userAuthenticationModel = new UserAuthenticationModel { IsAuthenticated = true, AuthenticationLevel = SecurityLevel.QuiteSensitive, AuthenticationMethod = AuthenticationMethod.AltinnPIN, PartyID = 23, UserID = 434, Username = "******" }; Mock <ISblCookieDecryptionService> cookieDecryptionService = new Mock <ISblCookieDecryptionService>(); cookieDecryptionService.Setup(s => s.DecryptTicket(It.IsAny <string>())).ReturnsAsync(userAuthenticationModel); HttpClient client = GetTestClient(cookieDecryptionService.Object); string url = "/authentication/api/v1/authentication?goto=http%3A%2F%2Flocalhost"; HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", ".ASPXAUTH=asdasdasd"); // Act HttpResponseMessage response = await client.SendAsync(requestMessage); // Assert Assert.Equal(HttpStatusCode.Found, response.StatusCode); string token = null; string sameSite = null; bool httpOnly = false; bool sessionCookie = true; response.Headers.TryGetValues(HeaderNames.SetCookie, out IEnumerable <string> cookies); foreach (string cookie in cookies) { string[] cookieParts = cookie.Split("; "); foreach (string cookiePart in cookieParts) { string[] cookieKeyValue = cookiePart.Split('='); switch (cookieKeyValue[0]) { case "AltinnStudioRuntime": token = cookieKeyValue[1]; break; case "httponly": httpOnly = true; break; case "expires": // Cookies WITHOUT 'expires' are session cookies. They are gone when the browser is closed. sessionCookie = false; break; case "samesite": sameSite = cookieKeyValue[1]; break; } } } Assert.NotNull(token); ClaimsPrincipal principal = JwtTokenMock.ValidateToken(token); Assert.NotNull(principal); Assert.NotNull(sameSite); Assert.Equal("lax", sameSite); Assert.True(httpOnly); Assert.True(sessionCookie); }