Search in sources :

Example 1 with Token

use of io.gravitee.repository.management.model.Token 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 2 with Token

use of io.gravitee.repository.management.model.Token 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 3 with Token

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

the class TokenServiceImpl method revoke.

@Override
public void revoke(String tokenId) {
    try {
        Optional<Token> tokenOptional = tokenRepository.findById(tokenId);
        if (tokenOptional.isPresent()) {
            tokenRepository.delete(tokenId);
            auditService.createEnvironmentAuditLog(Collections.singletonMap(TOKEN, tokenId), TOKEN_DELETED, new Date(), null, tokenOptional.get());
        }
    } catch (TechnicalException ex) {
        final String error = "An error occurs while trying to delete token " + tokenId;
        LOGGER.error(error, ex);
        throw new TechnicalManagementException(error, ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Token(io.gravitee.repository.management.model.Token) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 4 with Token

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

the class TokenServiceImpl method findByToken.

@Override
public Token findByToken(String token) {
    try {
        LOGGER.debug("Find token entity by token value");
        final Optional<Token> optionalToken = tokenRepository.findAll().stream().filter(t -> passwordEncoder.matches(token, t.getToken())).findAny();
        if (optionalToken.isPresent()) {
            final Token t = optionalToken.get();
            t.setLastUseAt(new Date());
            return tokenRepository.update(t);
        }
        throw new IllegalStateException("Token not found");
    } catch (TechnicalException ex) {
        final String error = "An error occurs while trying to find token entity for a given token value";
        LOGGER.error(error, ex);
        throw new TechnicalManagementException(error, ex);
    }
}
Also used : TokenService(io.gravitee.rest.api.service.TokenService) java.util(java.util) Logger(org.slf4j.Logger) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) TokenEntity(io.gravitee.rest.api.model.TokenEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) TokenReferenceType(io.gravitee.rest.api.model.TokenReferenceType) AuditService(io.gravitee.rest.api.service.AuditService) TOKEN(io.gravitee.repository.management.model.Audit.AuditProperties.TOKEN) NewTokenEntity(io.gravitee.rest.api.model.NewTokenEntity) TokenNameAlreadyExistsException(io.gravitee.rest.api.service.exceptions.TokenNameAlreadyExistsException) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) UUID(io.gravitee.common.utils.UUID) Token(io.gravitee.repository.management.model.Token) AuditEvent(io.gravitee.repository.management.model.Token.AuditEvent) TokenRepository(io.gravitee.repository.management.api.TokenRepository) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Token(io.gravitee.repository.management.model.Token) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 5 with Token

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

the class TokenServiceImpl method convert.

private Token convert(final NewTokenEntity tokenEntity, final TokenReferenceType referenceType, final String referenceId, final String encodedToken) {
    final Token token = new Token();
    token.setId(UUID.toString(UUID.random()));
    token.setToken(encodedToken);
    token.setName(tokenEntity.getName());
    token.setCreatedAt(new Date());
    token.setReferenceType(referenceType.name());
    token.setReferenceId(referenceId);
    return token;
}
Also used : Token(io.gravitee.repository.management.model.Token)

Aggregations

Token (io.gravitee.repository.management.model.Token)9 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)3 NewTokenEntity (io.gravitee.rest.api.model.NewTokenEntity)3 TokenEntity (io.gravitee.rest.api.model.TokenEntity)3 TechnicalManagementException (io.gravitee.rest.api.service.exceptions.TechnicalManagementException)3 Test (org.junit.Test)3 UserEntity (io.gravitee.rest.api.model.UserEntity)2 TokenService (io.gravitee.rest.api.service.TokenService)2 TokenNameAlreadyExistsException (io.gravitee.rest.api.service.exceptions.TokenNameAlreadyExistsException)2 Date (java.util.Date)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 JWT (com.auth0.jwt.JWT)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 Algorithm (com.auth0.jwt.algorithms.Algorithm)1 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)1 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 HttpStatusCode (io.gravitee.common.http.HttpStatusCode)1 UUID (io.gravitee.common.utils.UUID)1