Search in sources :

Example 1 with UserService

use of io.gravitee.rest.api.service.UserService 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)

Aggregations

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 Token (io.gravitee.repository.management.model.Token)1 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)1 UserEntity (io.gravitee.rest.api.model.UserEntity)1 CookieGenerator (io.gravitee.rest.api.security.cookies.CookieGenerator)1 AuthoritiesProvider (io.gravitee.rest.api.security.utils.AuthoritiesProvider)1 TokenService (io.gravitee.rest.api.service.TokenService)1 UserService (io.gravitee.rest.api.service.UserService)1 Claims (io.gravitee.rest.api.service.common.JWTHelper.Claims)1 IOException (java.io.IOException)1 URLDecoder.decode (java.net.URLDecoder.decode)1 Charset.defaultCharset (java.nio.charset.Charset.defaultCharset)1 Arrays (java.util.Arrays)1 Optional (java.util.Optional)1