Search in sources :

Example 6 with UserInfo

use of com.auth0.json.auth.UserInfo in project ddf by codice.

the class TestOidc method processCredentialFlow.

/**
 * Processes a credential flow request/response
 *
 * <ul>
 *   <li>Sets up a userinfo endpoint that responds with the given {@param userInfoResponse} when
 *       given {@param accessToken}
 *   <li>Sends a request to Intrigue with the {@param accessToken} as a parameter
 *   <li>Asserts that the response is teh expected response
 *   <li>Verifies if the userinfo endpoint is hit or not
 * </ul>
 *
 * @return the response for additional verification
 */
private Response processCredentialFlow(String accessToken, String userInfoResponse, boolean isSigned, int expectedStatusCode, boolean userInfoShouldBeHit) {
    // Host the user info endpoint with the access token in the auth header
    String basicAuthHeader = "Bearer " + accessToken;
    String contentType = isSigned ? "application/jwt" : APPLICATION_JSON;
    whenHttp(server).match(get(USER_INFO_ENDPOINT_PATH), withHeader(AUTHORIZATION, basicAuthHeader)).then(ok(), contentType(contentType), bytesContent(userInfoResponse.getBytes()));
    // Send a request to DDF with the access token
    Response response = given().redirects().follow(false).expect().statusCode(expectedStatusCode).when().get(ROOT_URL.getUrl() + "?access_token=" + accessToken);
    List<Call> endpointCalls = server.getCalls().stream().filter(call -> call.getMethod().getMethodString().equals(GET)).filter(call -> call.getUrl().equals(URL_START + USER_INFO_ENDPOINT_PATH)).collect(Collectors.toList());
    if (userInfoShouldBeHit) {
        assertThat(endpointCalls.size(), is(greaterThanOrEqualTo(1)));
    } else {
        assertThat(endpointCalls.size(), is(0));
    }
    return response;
}
Also used : Response(io.restassured.response.Response) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) StubServer(com.xebialabs.restito.server.StubServer) GET(javax.ws.rs.HttpMethod.GET) Enumeration(java.util.Enumeration) Date(java.util.Date) PREFERRED_USERNAME(org.pac4j.oidc.profile.OidcProfileDefinition.PREFERRED_USERNAME) HttpStatus(org.apache.http.HttpStatus) GsonBuilder(com.google.gson.GsonBuilder) Algorithm(com.auth0.jwt.algorithms.Algorithm) NONCE(org.pac4j.oidc.profile.OidcProfileDefinition.NONCE) RSAPublicKey(java.security.interfaces.RSAPublicKey) Gson(com.google.gson.Gson) Duration(java.time.Duration) Map(java.util.Map) Base64URL(com.nimbusds.jose.util.Base64URL) AbstractIntegrationTest(org.codice.ddf.itests.common.AbstractIntegrationTest) URI(java.net.URI) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) KeyPairGenerator(java.security.KeyPairGenerator) Awaitility.await(org.awaitility.Awaitility.await) ImmutableMap(com.google.common.collect.ImmutableMap) JWTCreator(com.auth0.jwt.JWTCreator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Condition.parameter(com.xebialabs.restito.semantics.Condition.parameter) UUID(java.util.UUID) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) JWK(com.nimbusds.jose.jwk.JWK) StandardCharsets(java.nio.charset.StandardCharsets) HOST(javax.ws.rs.core.HttpHeaders.HOST) PerSuite(org.ops4j.pax.exam.spi.reactors.PerSuite) List(java.util.List) JSONObject(org.json.simple.JSONObject) Action.bytesContent(com.xebialabs.restito.semantics.Action.bytesContent) KeyUse(com.nimbusds.jose.jwk.KeyUse) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) SECURE_ROOT(org.codice.ddf.itests.common.AbstractIntegrationTest.DynamicUrl.SECURE_ROOT) Action.ok(com.xebialabs.restito.semantics.Action.ok) RestAssured.given(io.restassured.RestAssured.given) Matchers.is(org.hamcrest.Matchers.is) Condition.withHeader(com.xebialabs.restito.semantics.Condition.withHeader) AfterExam(org.codice.ddf.test.common.annotations.AfterExam) NameValuePair(org.apache.http.NameValuePair) Dictionary(java.util.Dictionary) StubHttp.whenHttp(com.xebialabs.restito.builder.stub.StubHttp.whenHttp) PaxExam(org.ops4j.pax.exam.junit.PaxExam) JWT(com.auth0.jwt.JWT) Call(com.xebialabs.restito.semantics.Call) MessageDigest(java.security.MessageDigest) RunWith(org.junit.runner.RunWith) BeforeExam(org.codice.ddf.test.common.annotations.BeforeExam) AZP(org.pac4j.oidc.profile.OidcProfileDefinition.AZP) REFRESH_TOKEN(org.pac4j.oidc.profile.OidcProfileDefinition.REFRESH_TOKEN) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) Condition.post(com.xebialabs.restito.semantics.Condition.post) ImmutableList(com.google.common.collect.ImmutableList) Configuration(org.osgi.service.cm.Configuration) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Condition.get(com.xebialabs.restito.semantics.Condition.get) AUTHORIZATION(javax.ws.rs.core.HttpHeaders.AUTHORIZATION) GsonTypeAdapters(org.codice.gsonsupport.GsonTypeAdapters) Hashtable(java.util.Hashtable) Before(org.junit.Before) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) PublicClaims(com.auth0.jwt.impl.PublicClaims) Assert.assertTrue(org.junit.Assert.assertTrue) AUTH_TIME(org.pac4j.oidc.profile.OidcProfileDefinition.AUTH_TIME) Test(org.junit.Test) USER_AGENT(javax.ws.rs.core.HttpHeaders.USER_AGENT) EMAIL_VERIFIED(org.pac4j.oidc.profile.OidcProfileDefinition.EMAIL_VERIFIED) TimeUnit(java.util.concurrent.TimeUnit) ExamReactorStrategy(org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy) RSAKey(com.nimbusds.jose.jwk.RSAKey) Response(io.restassured.response.Response) Action.contentType(com.xebialabs.restito.semantics.Action.contentType) ACCESS_TOKEN(org.pac4j.oidc.profile.OidcProfileDefinition.ACCESS_TOKEN) LoggingUtils(org.codice.ddf.test.common.LoggingUtils) Call(com.xebialabs.restito.semantics.Call)

Example 7 with UserInfo

use of com.auth0.json.auth.UserInfo in project engine by Lumeer.

the class Auth0Filter method getUserInfo.

private User getUserInfo(final String accessToken) throws Auth0Exception {
    final AuthAPI auth0 = new AuthAPI(domain, clientId, clientSecret);
    final Request<UserInfo> info = auth0.userInfo(accessToken);
    final Map<String, Object> values = info.execute().getValues();
    final String nickname = (String) values.get("nickname");
    final String sub = (String) values.get("sub");
    final String name = (String) values.get("name");
    final String email = (String) values.get("email");
    final Boolean emailVerified = (Boolean) values.get("email_verified");
    final User user = new User(email == null ? (sub.startsWith("google-oauth2") ? nickname + "@gmail.com" : name) : email);
    user.setAuthIds(new HashSet<>(Arrays.asList(sub)));
    user.setName(name);
    user.setEmailVerified(emailVerified != null && emailVerified);
    return user;
}
Also used : User(io.lumeer.api.model.User) UserInfo(com.auth0.json.auth.UserInfo) AuthAPI(com.auth0.client.auth.AuthAPI)

Example 8 with UserInfo

use of com.auth0.json.auth.UserInfo in project gravitee-management-rest-api by gravitee-io.

the class UserServiceTest method shouldUpdateUserWithGroupMappingWithoutOverridingIfGroupDefined.

@Test
public void shouldUpdateUserWithGroupMappingWithoutOverridingIfGroupDefined() throws IOException, TechnicalException {
    reset(identityProvider, userRepository, groupService, roleService, membershipService);
    mockDefaultEnvironment();
    mockGroupsMapping();
    mockRolesMapping();
    User createdUser = mockUser();
    when(userRepository.create(any(User.class))).thenReturn(createdUser);
    when(identityProvider.getId()).thenReturn("oauth2");
    when(userRepository.findBySource("oauth2", "janedoe@example.com", ORGANIZATION)).thenReturn(Optional.empty());
    // mock group search and association
    when(groupService.findById("Example group")).thenReturn(mockGroupEntity("group_id_1", "Example group"));
    when(groupService.findById("soft user")).thenReturn(mockGroupEntity("group_id_2", "soft user"));
    when(groupService.findById("Api consumer")).thenReturn(mockGroupEntity("group_id_4", "Api consumer"));
    // mock role search
    RoleEntity roleOrganizationAdmin = mockRoleEntity(RoleScope.ORGANIZATION, "ADMIN");
    RoleEntity roleOrganizationUser = mockRoleEntity(RoleScope.ORGANIZATION, "USER");
    RoleEntity roleEnvironmentAdmin = mockRoleEntity(RoleScope.ENVIRONMENT, "ADMIN");
    RoleEntity roleApiUser = mockRoleEntity(RoleScope.API, "USER");
    RoleEntity roleApplicationAdmin = mockRoleEntity(RoleScope.APPLICATION, "ADMIN");
    when(roleService.findByScopeAndName(RoleScope.ORGANIZATION, "ADMIN")).thenReturn(Optional.of(roleOrganizationAdmin));
    when(roleService.findByScopeAndName(RoleScope.ORGANIZATION, "USER")).thenReturn(Optional.of(roleOrganizationUser));
    when(roleService.findDefaultRoleByScopes(RoleScope.API, RoleScope.APPLICATION)).thenReturn(Arrays.asList(roleApiUser, roleApplicationAdmin));
    Membership membership = new Membership();
    membership.setSource("oauth2");
    membership.setReferenceId("membershipId");
    membership.setReferenceType(io.gravitee.repository.management.model.MembershipReferenceType.GROUP);
    final HashSet<Membership> memberships = new HashSet<>();
    memberships.add(membership);
    when(membershipRepository.findByMemberIdAndMemberTypeAndReferenceType("janedoe@example.com", io.gravitee.repository.management.model.MembershipMemberType.USER, io.gravitee.repository.management.model.MembershipReferenceType.GROUP)).thenReturn(memberships);
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.ORGANIZATION, "DEFAULT")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "ADMIN")) && roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "USER"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    String userInfo = IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset());
    userService.createOrUpdateUserFromSocialIdentityProvider(identityProvider, userInfo);
    // verify group creations
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(0)).updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_3")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(new MembershipService.MembershipReference(MembershipReferenceType.ORGANIZATION, "DEFAULT")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "ADMIN")) && roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "USER"))), eq("oauth2"));
    verify(membershipService, times(1)).deleteReferenceMemberBySource(eq(MembershipReferenceType.GROUP), eq("membershipId"), eq(MembershipMemberType.USER), eq("janedoe@example.com"), eq("oauth2"));
}
Also used : ArgumentMatchers(org.mockito.ArgumentMatchers) Optional.of(java.util.Optional.of) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) ArgumentMatcher(org.mockito.ArgumentMatcher) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) ExpressionEvaluationException(io.gravitee.el.exceptions.ExpressionEvaluationException) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) Instant(java.time.Instant) RESET_PASSWORD(io.gravitee.rest.api.service.common.JWTHelper.ACTION.RESET_PASSWORD) UserServiceImpl(io.gravitee.rest.api.service.impl.UserServiceImpl) AdditionalAnswers.returnsFirstArg(org.mockito.AdditionalAnswers.returnsFirstArg) Key(io.gravitee.rest.api.model.parameters.Key) IOUtils(org.apache.commons.io.IOUtils) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) Optional.empty(java.util.Optional.empty) JWT(com.auth0.jwt.JWT) java.util(java.util) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Charset(java.nio.charset.Charset) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) InjectMocks(org.mockito.InjectMocks) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) ApplicationType(io.gravitee.repository.management.model.ApplicationType) IOException(java.io.IOException) Test(org.junit.Test) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) Mockito(org.mockito.Mockito) MetadataPage(io.gravitee.common.data.domain.MetadataPage) ReflectionTestUtils.setField(org.springframework.test.util.ReflectionTestUtils.setField) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) User(io.gravitee.repository.management.model.User) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) Assert(org.junit.Assert) USER_REGISTRATION(io.gravitee.rest.api.service.common.JWTHelper.ACTION.USER_REGISTRATION) InputStream(java.io.InputStream) User(io.gravitee.repository.management.model.User) Membership(io.gravitee.repository.management.model.Membership) Test(org.junit.Test)

Example 9 with UserInfo

use of com.auth0.json.auth.UserInfo in project nextprot-api by calipho-sib.

the class JWTCodecImpl method decodeJWT.

@Override
public Map<String, Object> decodeJWT(String token) {
    try {
        File publicKeyFile = new File(this.getClass().getClassLoader().getResource("keys/pubkey").toURI());
        RSAPublicKey publicKey = (RSAPublicKey) PemUtils.readPublicKeyFromFile(publicKeyFile.toString(), "RSA");
        Algorithm algorithm = Algorithm.RSA256(publicKey);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer("https://nextprot.auth0.com/").withAudience("https://nextprot.auth0.com/api/v2/").withAudience("https://nextprot.auth0.com/userinfo").build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Object> map = new HashMap<>();
        map.put(EMAIL, jwt.getClaim("https://www.nextprot.org/userinfo/email").asString());
        return map;
    } catch (IOException e) {
        throw new NextprotSecurityException(e);
    } catch (URISyntaxException e) {
        throw new NextprotSecurityException(e);
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) HashMap(java.util.HashMap) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) File(java.io.File) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) NextprotSecurityException(org.nextprot.api.security.service.exception.NextprotSecurityException)

Example 10 with UserInfo

use of com.auth0.json.auth.UserInfo in project gravitee-api-management by gravitee-io.

the class UserServiceTest method shouldCreateNewUserWithGroupsMappingFromUserInfo.

@Test
public void shouldCreateNewUserWithGroupsMappingFromUserInfo() throws IOException, TechnicalException {
    reset(identityProvider, userRepository, groupService, roleService, membershipService);
    mockDefaultEnvironment();
    mockGroupsMapping();
    mockRolesMapping();
    User createdUser = mockUser();
    when(userRepository.create(any(User.class))).thenReturn(createdUser);
    when(identityProvider.getId()).thenReturn("oauth2");
    when(userRepository.findBySource("oauth2", "janedoe@example.com", ORGANIZATION)).thenReturn(Optional.empty());
    // mock group search and association
    when(groupService.findById(GraviteeContext.getCurrentEnvironment(), "Example group")).thenReturn(mockGroupEntity("group_id_1", "Example group"));
    when(groupService.findById(GraviteeContext.getCurrentEnvironment(), "soft user")).thenReturn(mockGroupEntity("group_id_2", "soft user"));
    when(groupService.findById(GraviteeContext.getCurrentEnvironment(), "Api consumer")).thenReturn(mockGroupEntity("group_id_4", "Api consumer"));
    // mock role search
    RoleEntity roleOrganizationAdmin = mockRoleEntity(RoleScope.ORGANIZATION, "ADMIN");
    RoleEntity roleOrganizationUser = mockRoleEntity(RoleScope.ORGANIZATION, "USER");
    RoleEntity roleEnvironmentAdmin = mockRoleEntity(RoleScope.ENVIRONMENT, "ADMIN");
    RoleEntity roleApiUser = mockRoleEntity(RoleScope.API, "USER");
    RoleEntity roleApplicationAdmin = mockRoleEntity(RoleScope.APPLICATION, "ADMIN");
    when(roleService.findByScopeAndName(RoleScope.ORGANIZATION, "ADMIN")).thenReturn(Optional.of(roleOrganizationAdmin));
    when(roleService.findByScopeAndName(RoleScope.ORGANIZATION, "USER")).thenReturn(Optional.of(roleOrganizationUser));
    when(roleService.findDefaultRoleByScopes(RoleScope.API, RoleScope.APPLICATION)).thenReturn(Arrays.asList(roleApiUser, roleApplicationAdmin));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    when(membershipService.updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.ORGANIZATION, "DEFAULT")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "ADMIN")) && roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "USER"))), eq("oauth2"))).thenReturn(Collections.singletonList(mockMemberEntity()));
    String userInfo = IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset());
    userService.createOrUpdateUserFromSocialIdentityProvider(identityProvider, userInfo);
    // verify group creations
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(0)).updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_3")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.API, "USER")) && roles.contains(new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))), eq("oauth2"));
    verify(membershipService, times(1)).updateRolesToMemberOnReferenceBySource(eq(GraviteeContext.getCurrentOrganization()), eq(GraviteeContext.getCurrentEnvironment()), eq(new MembershipService.MembershipReference(MembershipReferenceType.ORGANIZATION, "DEFAULT")), eq(new MembershipService.MembershipMember("janedoe@example.com", null, MembershipMemberType.USER)), argThat(roles -> roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "ADMIN")) && roles.contains(new MembershipService.MembershipRole(RoleScope.ORGANIZATION, "USER"))), eq("oauth2"));
}
Also used : ArgumentMatchers(org.mockito.ArgumentMatchers) Optional.of(java.util.Optional.of) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) ArgumentMatcher(org.mockito.ArgumentMatcher) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) PortalHook(io.gravitee.rest.api.service.notification.PortalHook) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) ExpressionEvaluationException(io.gravitee.el.exceptions.ExpressionEvaluationException) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) Instant(java.time.Instant) RESET_PASSWORD(io.gravitee.rest.api.service.common.JWTHelper.ACTION.RESET_PASSWORD) UserServiceImpl(io.gravitee.rest.api.service.impl.UserServiceImpl) AdditionalAnswers.returnsFirstArg(org.mockito.AdditionalAnswers.returnsFirstArg) Key(io.gravitee.rest.api.model.parameters.Key) IOUtils(org.apache.commons.io.IOUtils) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) Optional.empty(java.util.Optional.empty) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Charset(java.nio.charset.Charset) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) InjectMocks(org.mockito.InjectMocks) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) ApplicationType(io.gravitee.repository.management.model.ApplicationType) IOException(java.io.IOException) Test(org.junit.Test) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) Mockito(org.mockito.Mockito) MetadataPage(io.gravitee.common.data.domain.MetadataPage) ReflectionTestUtils.setField(org.springframework.test.util.ReflectionTestUtils.setField) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) User(io.gravitee.repository.management.model.User) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) Assert(org.junit.Assert) USER_REGISTRATION(io.gravitee.rest.api.service.common.JWTHelper.ACTION.USER_REGISTRATION) InputStream(java.io.InputStream) User(io.gravitee.repository.management.model.User) Test(org.junit.Test)

Aggregations

IOException (java.io.IOException)7 Test (org.junit.Test)7 Algorithm (com.auth0.jwt.algorithms.Algorithm)6 JWT (com.auth0.jwt.JWT)5 Duration (java.time.Duration)5 Instant (java.time.Instant)5 MetadataPage (io.gravitee.common.data.domain.MetadataPage)4 Maps (io.gravitee.common.util.Maps)4 ExpressionEvaluationException (io.gravitee.el.exceptions.ExpressionEvaluationException)4 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)4 UserRepository (io.gravitee.repository.management.api.UserRepository)4 ApplicationType (io.gravitee.repository.management.model.ApplicationType)4 Membership (io.gravitee.repository.management.model.Membership)4 User (io.gravitee.repository.management.model.User)4 UserStatus (io.gravitee.repository.management.model.UserStatus)4 io.gravitee.rest.api.model (io.gravitee.rest.api.model)4 ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)4 ApplicationListItem (io.gravitee.rest.api.model.application.ApplicationListItem)4 AuditEntity (io.gravitee.rest.api.model.audit.AuditEntity)4