Search in sources :

Example 1 with UserEntity

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

the class AbstractAuthenticationResource method connectUserInternal.

protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    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 management or portal role
    Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), 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 token = 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 TokenEntity tokenEntity = new TokenEntity();
    tokenEntity.setType(BEARER);
    tokenEntity.setToken(token);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) NotBlank(javax.validation.constraints.NotBlank) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) 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) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) 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) 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) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) 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) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity)

Example 2 with UserEntity

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

the class OAuth2AuthenticationResource method processUser.

private Response processUser(final SocialIdentityProviderEntity socialProvider, final HttpServletResponse servletResponse, final String userInfo, final String state, final String accessToken, final String idToken) {
    UserEntity user = userService.createOrUpdateUserFromSocialIdentityProvider(socialProvider, userInfo);
    final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId());
    // set user to Authentication Context
    UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
    userDetails.setEmail(user.getEmail());
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
    return connectUser(user.getId(), state, servletResponse, accessToken, idToken);
}
Also used : UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserEntity(io.gravitee.rest.api.model.UserEntity)

Example 3 with UserEntity

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

the class TokenAuthenticationFilter method doFilter.

@Override
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String stringToken = req.getHeader(HttpHeaders.AUTHORIZATION);
    if (isEmpty(stringToken) && req.getCookies() != null) {
        final Optional<Cookie> optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> AUTH_COOKIE_NAME.equals(cookie.getName())).findAny();
        if (optionalStringToken.isPresent()) {
            stringToken = decode(optionalStringToken.get().getValue(), defaultCharset().name());
        }
    }
    if (isEmpty(stringToken)) {
        LOGGER.debug("Authorization header/cookie not found");
    } else {
        try {
            if (stringToken.toLowerCase().contains(TOKEN_AUTH_SCHEMA)) {
                final String tokenValue = stringToken.substring(TOKEN_AUTH_SCHEMA.length()).trim();
                if (tokenValue.contains(".")) {
                    final DecodedJWT jwt = jwtVerifier.verify(tokenValue);
                    final Set<GrantedAuthority> authorities = this.authoritiesProvider.retrieveAuthorities(jwt.getClaim(Claims.SUBJECT).asString());
                    final UserDetails userDetails = new UserDetails(getStringValue(jwt.getSubject()), "", authorities);
                    userDetails.setEmail(jwt.getClaim(Claims.EMAIL).asString());
                    userDetails.setFirstname(jwt.getClaim(Claims.FIRSTNAME).asString());
                    userDetails.setLastname(jwt.getClaim(Claims.LASTNAME).asString());
                    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
                } else if (tokenService != null && userService != null) {
                    final Token token = tokenService.findByToken(tokenValue);
                    final UserEntity user = userService.findById(token.getReferenceId());
                    final Set<GrantedAuthority> authorities = this.authoritiesProvider.retrieveAuthorities(user.getId());
                    final UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
                    userDetails.setFirstname(user.getFirstname());
                    userDetails.setLastname(user.getLastname());
                    userDetails.setEmail(user.getEmail());
                    userDetails.setSource("token");
                    userDetails.setSourceId(token.getName());
                    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
                }
            } else {
                LOGGER.debug("Authorization schema not found");
            }
        } catch (final Exception e) {
            final String errorMessage = "Invalid token";
            if (LOGGER.isDebugEnabled()) {
                LOGGER.error(errorMessage, e);
            } else {
                if (e instanceof JWTVerificationException) {
                    LOGGER.warn(errorMessage);
                } else {
                    LOGGER.error(errorMessage);
                }
            }
            res.addCookie(cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, null));
            res.sendError(HttpStatusCode.UNAUTHORIZED_401);
            return;
        }
    }
    chain.doFilter(request, response);
}
Also used : Cookie(javax.servlet.http.Cookie) TokenService(io.gravitee.rest.api.service.TokenService) JWT(com.auth0.jwt.JWT) Charset.defaultCharset(java.nio.charset.Charset.defaultCharset) Arrays(java.util.Arrays) FilterChain(javax.servlet.FilterChain) HttpHeaders(io.gravitee.common.http.HttpHeaders) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServletException(javax.servlet.ServletException) LoggerFactory(org.slf4j.LoggerFactory) AuthoritiesProvider(io.gravitee.rest.api.security.utils.AuthoritiesProvider) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) JWTVerifier(com.auth0.jwt.JWTVerifier) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserService(io.gravitee.rest.api.service.UserService) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ServletRequest(javax.servlet.ServletRequest) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) Set(java.util.Set) IOException(java.io.IOException) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) URLDecoder.decode(java.net.URLDecoder.decode) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Token(io.gravitee.repository.management.model.Token) ServletResponse(javax.servlet.ServletResponse) Optional(java.util.Optional) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserEntity(io.gravitee.rest.api.model.UserEntity) Set(java.util.Set) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Token(io.gravitee.repository.management.model.Token) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserEntity(io.gravitee.rest.api.model.UserEntity) ServletException(javax.servlet.ServletException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 4 with UserEntity

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

the class TokenAuthenticationFilterTest method shouldGenerateAuthorities.

@Test
public void shouldGenerateAuthorities() throws Exception {
    final String USER_ID = "userid1";
    final String TOKEN = "b4c6102e-6c95-464f-8610-2e6c95064f02";
    final String BEARER = "Bearer " + TOKEN;
    TokenAuthenticationFilter filter = new TokenAuthenticationFilter("JWT_SECRET_TOEKN_TEST", cookieGenerator, userService, tokenService, authoritiesProvider);
    when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(BEARER);
    final Token token = mock(Token.class);
    when(token.getReferenceId()).thenReturn(USER_ID);
    when(tokenService.findByToken(TOKEN)).thenReturn(token);
    UserEntity user = mock(UserEntity.class);
    when(user.getId()).thenReturn(USER_ID);
    when(userService.findById(USER_ID)).thenReturn(user);
    filter.doFilter(request, response, filterChain);
    verify(authoritiesProvider).retrieveAuthorities(USER_ID);
}
Also used : Token(io.gravitee.repository.management.model.Token) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Example 5 with UserEntity

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

the class MembershipCommandHandler method handle.

@Override
public Single<MembershipReply> handle(MembershipCommand command) {
    MembershipPayload membershipPayload = command.getPayload();
    GraviteeContext.setCurrentOrganization(membershipPayload.getOrganizationId());
    try {
        RoleScope roleScope;
        MembershipReferenceType membershipReferenceType;
        try {
            roleScope = RoleScope.valueOf(membershipPayload.getReferenceType());
            membershipReferenceType = MembershipReferenceType.valueOf(membershipPayload.getReferenceType());
        } catch (Exception e) {
            logger.error("Invalid referenceType [{}].", membershipPayload.getReferenceType());
            return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
        }
        final UserEntity userEntity = userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false);
        final RoleEntity roleEntity = findRole(roleScope, membershipPayload.getRole());
        final MembershipService.MembershipReference membershipReference = new MembershipService.MembershipReference(membershipReferenceType, membershipPayload.getReferenceId());
        final MembershipService.MembershipMember membershipMember = new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER);
        final MembershipService.MembershipRole membershipRole = new MembershipService.MembershipRole(roleEntity.getScope(), roleEntity.getName());
        membershipService.updateRolesToMemberOnReference(membershipReference, membershipMember, Collections.singletonList(membershipRole), COCKPIT_SOURCE, false);
        logger.info("Role [{}] assigned on {} [{}] for user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), userEntity.getId(), membershipPayload.getOrganizationId());
        return Single.just(new MembershipReply(command.getId(), CommandStatus.SUCCEEDED));
    } catch (Exception e) {
        logger.error("Error occurred when trying to assign role [{}] on {} [{}] for cockpit user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), membershipPayload.getUserId(), membershipPayload.getOrganizationId(), e);
        return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
    } finally {
        GraviteeContext.cleanContext();
    }
}
Also used : MembershipReply(io.gravitee.cockpit.api.command.membership.MembershipReply) RoleNotFoundException(io.gravitee.rest.api.service.exceptions.RoleNotFoundException) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) MembershipService(io.gravitee.rest.api.service.MembershipService) MembershipPayload(io.gravitee.cockpit.api.command.membership.MembershipPayload) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType)

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