Search in sources :

Example 41 with UserEntity

use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.

the class AbstractAuthenticationResource method connectUser.

protected Response connectUser(String userId, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    UserEntity user = userService.connect(userId);
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    // Manage authorities, initialize it with dynamic permissions from the IDP
    List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
    // We must also load permissions from repository for configured environment role
    Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
    }
    // JWT signer
    Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
    Date issueAt = new Date();
    Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
    final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
    final Token tokenEntity = new Token();
    tokenEntity.setTokenType(TokenTypeEnum.BEARER);
    tokenEntity.setToken(sign);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) UserService(io.gravitee.rest.api.service.UserService) Duration(java.time.Duration) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) MembershipService(io.gravitee.rest.api.service.MembershipService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Token(io.gravitee.rest.api.portal.rest.model.Token) TokenTypeEnum(io.gravitee.rest.api.portal.rest.model.Token.TokenTypeEnum) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) Response(javax.ws.rs.core.Response) Environment(org.springframework.core.env.Environment) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) UserEntity(io.gravitee.rest.api.model.UserEntity) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 42 with UserEntity

use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.

the class UserMapperTest method testConvertUserEntityWithPermissions.

@Test
public void testConvertUserEntityWithPermissions() throws Exception {
    Instant now = Instant.now();
    Date nowDate = Date.from(now);
    // init
    UserEntity userEntity = new UserEntity();
    UserRoleEntity userRoleEntityOrganization = new UserRoleEntity();
    userRoleEntityOrganization.setId("org-id");
    userRoleEntityOrganization.setScope(RoleScope.ORGANIZATION);
    HashMap<String, char[]> organizationPermissions = new HashMap<>();
    organizationPermissions.put("USER", new char[] { 'C', 'R', 'U', 'D' });
    organizationPermissions.put("ENVIRONMENT", new char[] { 'C', 'R', 'U', 'D' });
    userRoleEntityOrganization.setPermissions(organizationPermissions);
    UserRoleEntity userRoleEntityEnvironment = new UserRoleEntity();
    userRoleEntityEnvironment.setScope(RoleScope.ENVIRONMENT);
    userRoleEntityEnvironment.setId("env-id");
    HashMap<String, char[]> environmentPermissions = new HashMap<>();
    environmentPermissions.put("APPLICATION", new char[] { 'C' });
    userRoleEntityEnvironment.setPermissions(environmentPermissions);
    userEntity.setCreatedAt(nowDate);
    userEntity.setEmail(USER_EMAIL);
    userEntity.setFirstname(USER_FIRSTNAME);
    userEntity.setId(USER_ID);
    userEntity.setLastConnectionAt(nowDate);
    userEntity.setLastname(USER_LASTNAME);
    userEntity.setPassword(USER_PASSWORD);
    userEntity.setPicture(USER_PICTURE);
    userEntity.setRoles(new HashSet<>(Arrays.asList(userRoleEntityOrganization, userRoleEntityEnvironment)));
    userEntity.setSource(USER_SOURCE);
    userEntity.setSourceId(USER_SOURCE_ID);
    userEntity.setStatus(USER_STATUS);
    userEntity.setUpdatedAt(nowDate);
    // Test
    User responseUser = userMapper.convert(userEntity);
    assertNotNull(responseUser);
    assertEquals(USER_ID, responseUser.getId());
    assertEquals(USER_EMAIL, responseUser.getEmail());
    assertEquals(USER_FIRSTNAME, responseUser.getFirstName());
    assertEquals(USER_LASTNAME, responseUser.getLastName());
    assertEquals(USER_FIRSTNAME + ' ' + USER_LASTNAME, responseUser.getDisplayName());
    assertTrue(responseUser.getPermissions().getAPPLICATION().containsAll(Arrays.asList("C")));
}
Also used : UserRoleEntity(io.gravitee.rest.api.model.UserRoleEntity) SearchableUser(io.gravitee.rest.api.idp.api.identity.SearchableUser) User(io.gravitee.rest.api.portal.rest.model.User) HashMap(java.util.HashMap) Instant(java.time.Instant) Date(java.util.Date) RegisterUserEntity(io.gravitee.rest.api.model.RegisterUserEntity) NewExternalUserEntity(io.gravitee.rest.api.model.NewExternalUserEntity) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Example 43 with UserEntity

use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.

the class CockpitAuthenticationResource method tokenExchange.

@GET
public Response tokenExchange(@QueryParam(value = "token") final String token, @Context final HttpServletResponse httpResponse) {
    if (!enabled) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    try {
        // Verify and get claims from token.
        final JWTClaimsSet jwtClaimsSet = jwtProcessor.process(token, null);
        // Current organization must be set to those coming from cockpit token.
        final String organizationId = jwtClaimsSet.getStringClaim(ORG_CLAIM);
        GraviteeContext.setCurrentOrganization(organizationId);
        // Retrieve the user.
        final UserEntity user = userService.findBySource(COCKPIT_SOURCE, jwtClaimsSet.getSubject(), true);
        // set user to Authentication Context
        final String environmentId = jwtClaimsSet.getStringClaim(ENVIRONMENT_CLAIM);
        final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId(), organizationId, environmentId);
        UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
        userDetails.setEmail(user.getEmail());
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
        // Cockpit user is authenticated, connect user (ie: generate cookie).
        super.connectUser(user, httpResponse);
        // Redirect the user.
        return Response.temporaryRedirect(new URI(jwtClaimsSet.getStringClaim(REDIRECT_URI_CLAIM) + "?organization=" + jwtClaimsSet.getStringClaim(ORG_CLAIM) + "/#!/environments/" + jwtClaimsSet.getStringClaim(ENVIRONMENT_CLAIM))).build();
    } catch (Exception e) {
        LOGGER.error("Error occurred when trying to log user using cockpit.", e);
        return Response.serverError().build();
    } finally {
        GraviteeContext.cleanContext();
    }
}
Also used : UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) URI(java.net.URI) UserEntity(io.gravitee.rest.api.model.UserEntity) GET(javax.ws.rs.GET)

Example 44 with UserEntity

use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.

the class UserResourceTest method shouldGetCurrentUserWithoutConfig.

@Test
public void shouldGetCurrentUserWithoutConfig() {
    when(userService.findByIdWithRoles(USER_NAME)).thenReturn(new UserEntity());
    when(permissionService.hasManagementRights(USER_NAME)).thenReturn(Boolean.FALSE);
    final Response response = target().request().get();
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    ArgumentCaptor<String> userId = ArgumentCaptor.forClass(String.class);
    Mockito.verify(userService).findByIdWithRoles(userId.capture());
    assertEquals(USER_NAME, userId.getValue());
    User user = response.readEntity(User.class);
    assertNotNull(user);
    assertNull(user.getConfig());
    assertNotNull(user.getLinks());
}
Also used : Response(javax.ws.rs.core.Response) User(io.gravitee.rest.api.portal.rest.model.User) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Example 45 with UserEntity

use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.

the class UserResourceTest method shouldGetNoContent.

@Test
public void shouldGetNoContent() throws IOException {
    doReturn(new UserEntity()).when(userService).findById(any());
    doReturn(null).when(userService).getPicture(any());
    final Response response = target().path("avatar").request().get();
    assertEquals(OK_200, response.getStatus());
}
Also used : Response(javax.ws.rs.core.Response) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Aggregations

UserEntity (io.gravitee.rest.api.model.UserEntity)57 Test (org.junit.Test)36 User (io.gravitee.rest.api.portal.rest.model.User)14 Response (javax.ws.rs.core.Response)14 RoleEntity (io.gravitee.rest.api.model.RoleEntity)13 UpdateUserEntity (io.gravitee.rest.api.model.UpdateUserEntity)12 ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)12 Date (java.util.Date)10 PrimaryOwnerEntity (io.gravitee.rest.api.model.PrimaryOwnerEntity)9 UserService (io.gravitee.rest.api.service.UserService)9 NewExternalUserEntity (io.gravitee.rest.api.model.NewExternalUserEntity)8 List (java.util.List)8 Instant (java.time.Instant)7 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)6 ApplicationEntity (io.gravitee.rest.api.model.ApplicationEntity)6 MembershipService (io.gravitee.rest.api.service.MembershipService)6 HashMap (java.util.HashMap)6 Collectors (java.util.stream.Collectors)6 MembershipPayload (io.gravitee.cockpit.api.command.membership.MembershipPayload)5 MembershipReply (io.gravitee.cockpit.api.command.membership.MembershipReply)5