Search in sources :

Example 6 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails 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);
    String userId = user.getId();
    final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId());
    // set user to Authentication Context
    UserDetails userDetails = new UserDetails(userId, "", authorities);
    userDetails.setEmail(user.getEmail());
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
    return connectUser(userId, 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 7 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 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 8 with UserDetails

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

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

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

the class AuthenticationSuccessListener method onApplicationEvent.

@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    final UserDetails details = (UserDetails) event.getAuthentication().getPrincipal();
    try {
        UserEntity registeredUser = userService.findBySource(details.getSource(), details.getSourceId(), false);
        updateRegisteredUser(registeredUser, details);
        // Principal username is the technical identifier of the user
        // Dirty hack because spring security is requiring a username...
        details.setUsername(registeredUser.getId());
        // Allows to override email of in memory users
        if ("memory".equals(details.getSource()) && registeredUser.getEmail() != null) {
            details.setEmail(registeredUser.getEmail());
            SecurityContextHolder.getContext().setAuthentication(event.getAuthentication());
        }
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setSource(details.getSource());
        newUser.setSourceId(details.getSourceId());
        newUser.setFirstname(details.getFirstname());
        newUser.setLastname(details.getLastname());
        newUser.setEmail(details.getEmail());
        byte[] pictureData = details.getPicture();
        if (pictureData != null && pictureData.length > 0) {
            String picture = computePicture(pictureData);
            newUser.setPicture(picture);
        }
        boolean addDefaultRole = false;
        if (event.getAuthentication().getAuthorities() == null || event.getAuthentication().getAuthorities().isEmpty()) {
            addDefaultRole = true;
        }
        UserEntity createdUser = userService.create(newUser, addDefaultRole);
        // Principal username is the technical identifier of the user
        details.setUsername(createdUser.getId());
        if (!addDefaultRole) {
            addRole(RoleScope.ENVIRONMENT, createdUser.getId(), event.getAuthentication().getAuthorities());
            addRole(RoleScope.ORGANIZATION, createdUser.getId(), event.getAuthentication().getAuthorities());
        }
    }
    userService.connect(details.getUsername());
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails)

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