Search in sources :

Example 11 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class CurrentUserResourceTest method shouldBeAbleToGetCurrentUser.

@Test
public void shouldBeAbleToGetCurrentUser() {
    Mockito.reset(userService);
    final UserDetails userDetails = new UserDetails(USER_NAME, "PASSWORD", Collections.emptyList());
    assertThat(userDetails.getPassword()).isNotNull();
    setCurrentUserDetails(userDetails);
    final Response response = orgTarget().request().get();
    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(HttpStatusCode.OK_200);
    assertThat(response.readEntity(HashMap.class)).isNotNull().containsKeys("created_at", "updated_at", "last_connection_at");
}
Also used : Response(javax.ws.rs.core.Response) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 12 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class CurrentUserResourceTest method shouldBeAbleToDeleteCurrentUser.

@Test
public void shouldBeAbleToDeleteCurrentUser() {
    Mockito.reset(userService);
    final Authentication authentication = mock(Authentication.class);
    final UserDetails userDetails = new UserDetails(USER_NAME, "PASSWORD", Collections.emptyList());
    when(authentication.getPrincipal()).thenReturn(userDetails);
    SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
    final Response response = orgTarget().request().delete();
    verify(userService, times(1)).delete(USER_NAME);
    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(HttpStatusCode.NO_CONTENT_204);
}
Also used : Response(javax.ws.rs.core.Response) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) Test(org.junit.Test)

Example 13 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class CurrentUserResourceTest method shouldBeAbleToGetCurrentUserEvenIfItsPasswordIsErased.

@Test
public void shouldBeAbleToGetCurrentUserEvenIfItsPasswordIsErased() {
    Mockito.reset(userService);
    final UserDetails userDetails = new UserDetails(USER_NAME, "PASSWORD", Collections.emptyList());
    userDetails.eraseCredentials();
    assertThat(userDetails.getPassword()).isNull();
    setCurrentUserDetails(userDetails);
    final Response response = orgTarget().request().get();
    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(HttpStatusCode.OK_200);
}
Also used : Response(javax.ws.rs.core.Response) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Test(org.junit.Test)

Example 14 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails 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 15 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class CurrentUserResource method getCurrentUser.

@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get the authenticated user")
@ApiResponses({ @ApiResponse(code = 200, message = "Authenticated user", response = UserDetails.class), @ApiResponse(code = 401, message = "Unauthorized user"), @ApiResponse(code = 500, message = "Internal server error") })
public Response getCurrentUser() {
    if (isAuthenticated()) {
        final UserDetails details = getAuthenticatedUserDetails();
        final String userId = details.getUsername();
        final String password = details.getPassword() != null ? details.getPassword() : "";
        UserEntity userEntity;
        try {
            userEntity = userService.findByIdWithRoles(userId);
        } catch (final UserNotFoundException unfe) {
            final String unfeMessage = "User '{}' does not exist.";
            if (LOG.isDebugEnabled()) {
                LOG.info(unfeMessage, userId, unfe);
            } else {
                LOG.info(unfeMessage, userId);
            }
            response.addCookie(cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, null));
            return status(Response.Status.UNAUTHORIZED).build();
        }
        List<GrantedAuthority> authorities = new ArrayList<>(details.getAuthorities());
        UserDetails userDetails = new UserDetails(userEntity.getId(), password, authorities);
        userDetails.setId(userEntity.getId());
        // in case of memory user, look at the repository layer to get value updated by the user through the MyAccount page
        userDetails.setFirstname(IDP_SOURCE_MEMORY.equals(userEntity.getSource()) && userEntity.getFirstname() != null ? userEntity.getFirstname() : details.getFirstname());
        userDetails.setLastname(IDP_SOURCE_MEMORY.equals(userEntity.getSource()) && userEntity.getLastname() != null ? userEntity.getLastname() : details.getLastname());
        userDetails.setSource(userEntity.getSource());
        userDetails.setSourceId(userEntity.getSourceId());
        userDetails.setPrimaryOwner(userEntity.isPrimaryOwner());
        userDetails.setCreatedAt(userEntity.getCreatedAt());
        userDetails.setUpdatedAt(userEntity.getUpdatedAt());
        userDetails.setLastConnectionAt(userEntity.getLastConnectionAt());
        if (details.getEmail() == null && IDP_SOURCE_MEMORY.equals(userEntity.getSource()) && userEntity.getEmail() != null) {
            userDetails.setEmail(userEntity.getEmail());
        } else {
            userDetails.setEmail(details.getEmail());
        }
        boolean newsletterEnabled = environment.getProperty("newsletter.enabled", boolean.class, true);
        if (newsletterEnabled && userEntity.getNewsletterSubscribed() == null && userEntity.getFirstConnectionAt() != null) {
            long diffInMs = Math.abs(new Date().getTime() - userEntity.getFirstConnectionAt().getTime());
            long diff = TimeUnit.DAYS.convert(diffInMs, TimeUnit.MILLISECONDS);
            userDetails.setDisplayNewsletterSubscription(diff >= 7);
        } else {
            userDetails.setDisplayNewsletterSubscription(false);
        }
        // convert UserEntityRoles to UserDetailsRoles
        userDetails.setRoles(userEntity.getRoles().stream().map(userEntityRole -> {
            UserDetailRole userDetailRole = new UserDetailRole();
            userDetailRole.setScope(userEntityRole.getScope().name());
            userDetailRole.setName(userEntityRole.getName());
            userDetailRole.setPermissions(userEntityRole.getPermissions());
            return userDetailRole;
        }).collect(Collectors.toList()));
        final Set<MembershipEntity> memberships = membershipService.getMembershipsByMemberAndReference(MembershipMemberType.USER, userId, MembershipReferenceType.GROUP);
        if (!memberships.isEmpty()) {
            final Map<String, Set<String>> userGroups = new HashMap<>();
            environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()).forEach(environment -> {
                try {
                    final Set<Group> groups = groupRepository.findAllByEnvironment(environment.getId());
                    userGroups.put(environment.getId(), new HashSet<>());
                    memberships.stream().map(MembershipEntity::getReferenceId).forEach(groupId -> {
                        final Optional<Group> optionalGroup = groups.stream().filter(group -> groupId.equals(group.getId())).findFirst();
                        optionalGroup.ifPresent(entity -> userGroups.get(environment.getId()).add(entity.getName()));
                    });
                    userDetails.setGroupsByEnvironment(userGroups);
                } catch (TechnicalException e) {
                    LOG.error("Error while trying to get groups of the user " + userId, e);
                }
            });
        }
        userDetails.setFirstLogin(1 == userEntity.getLoginCount());
        if (userEntity.getCustomFields() != null) {
            userDetails.setCustomFields(userEntity.getCustomFields());
        }
        return ok(userDetails, MediaType.APPLICATION_JSON).build();
    } else {
        return ok().build();
    }
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) PagedResult(io.gravitee.rest.api.management.rest.model.PagedResult) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) Duration(java.time.Duration) Response.status(javax.ws.rs.core.Response.status) AbstractResource(io.gravitee.rest.api.management.rest.resource.AbstractResource) URI(java.net.URI) UserDetailRole(io.gravitee.rest.api.idp.api.authentication.UserDetailRole) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Context(javax.ws.rs.core.Context) GroupRepository(io.gravitee.repository.management.api.GroupRepository) Instant(java.time.Instant) NotNull(javax.validation.constraints.NotNull) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) GrantedAuthority(org.springframework.security.core.GrantedAuthority) MediaType(io.gravitee.common.http.MediaType) InvalidImageException(io.gravitee.rest.api.exception.InvalidImageException) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Request(javax.ws.rs.core.Request) Authentication(org.springframework.security.core.Authentication) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) ApiResponses(io.swagger.annotations.ApiResponses) Inject(javax.inject.Inject) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) io.gravitee.rest.api.model(io.gravitee.rest.api.model) TokensResource(io.gravitee.rest.api.management.rest.resource.TokensResource) Api(io.swagger.annotations.Api) Cookie(javax.servlet.http.Cookie) Logger(org.slf4j.Logger) ImageUtils(io.gravitee.rest.api.security.utils.ImageUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) Group(io.gravitee.repository.management.model.Group) EntityTag(javax.ws.rs.core.EntityTag) Maps(io.gravitee.common.util.Maps) TimeUnit(java.util.concurrent.TimeUnit) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) ApiResponse(io.swagger.annotations.ApiResponse) ResourceContext(javax.ws.rs.container.ResourceContext) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) Group(io.gravitee.repository.management.model.Group) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserDetailRole(io.gravitee.rest.api.idp.api.authentication.UserDetailRole) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)21 Authentication (org.springframework.security.core.Authentication)11 Response (javax.ws.rs.core.Response)9 Cookie (javax.servlet.http.Cookie)7 GrantedAuthority (org.springframework.security.core.GrantedAuthority)7 JWT (com.auth0.jwt.JWT)6 Algorithm (com.auth0.jwt.algorithms.Algorithm)6 UserEntity (io.gravitee.rest.api.model.UserEntity)6 CookieGenerator (io.gravitee.rest.api.security.cookies.CookieGenerator)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 SecurityContextHolder (org.springframework.security.core.context.SecurityContextHolder)6 Maps (io.gravitee.common.util.Maps)5 GraviteeContext (io.gravitee.rest.api.service.common.GraviteeContext)5 DEFAULT_JWT_EXPIRE_AFTER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER)5 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)5 Duration (java.time.Duration)5 Instant (java.time.Instant)5 java.util (java.util)5 Collectors (java.util.stream.Collectors)5 Claims (io.gravitee.rest.api.service.common.JWTHelper.Claims)4