Search in sources :

Example 71 with JWT

use of com.auth0.jwt.JWT 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 72 with JWT

use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method finalizeResetPassword.

@Override
public UserEntity finalizeResetPassword(ResetPasswordUserEntity registerUserEntity) {
    try {
        DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken());
        final String action = jwt.getClaim(Claims.ACTION).asString();
        if (!RESET_PASSWORD.name().equals(action)) {
            throw new UserStateConflictException("Invalid action on reset password resource");
        }
        final Object subject = jwt.getSubject();
        User user;
        if (subject == null) {
            throw new UserNotFoundException("Subject missing from JWT token");
        } else {
            final String username = subject.toString();
            LOGGER.debug("Find user {} to update password", username);
            Optional<User> checkUser = userRepository.findById(username);
            user = checkUser.orElseThrow(() -> new UserNotFoundException(username));
        }
        // Set date fields
        user.setUpdatedAt(new Date());
        // Encrypt password if internal user
        encryptPassword(user, registerUserEntity.getPassword());
        user = userRepository.update(user);
        auditService.createOrganizationAuditLog(Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_CHANGED, user.getUpdatedAt(), null, null);
        // Do not send back the password
        user.setPassword(null);
        return convert(user, true);
    } catch (AbstractManagementException ex) {
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("An error occurs while trying to change password of an internal user with the token {}", registerUserEntity.getToken(), ex);
        throw new TechnicalManagementException(ex.getMessage(), ex);
    }
}
Also used : User(io.gravitee.repository.management.model.User) UuidString(io.gravitee.rest.api.service.common.UuidString) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) TechnicalException(io.gravitee.repository.exceptions.TechnicalException)

Example 73 with JWT

use of com.auth0.jwt.JWT in project java-rest-api by messagebird.

the class RequestValidator method validateSignature.

/**
 * Returns raw signature payload after validating a signature successfully,
 * otherwise throws {@code RequestValidationException}.
 * <p>
 * This JWT is signed with a MessageBird account unique secret key, ensuring the request is from MessageBird and
 * a specific account.
 * The JWT contains the following claims:
 * </p>
 * <ul>
 *   <li>"url_hash" - the raw URL hashed with SHA256 ensuring the URL wasn't altered.</li>
 *   <li> "payload_hash" - the raw payload hashed with SHA256 ensuring the payload wasn't altered.</li>
 *   <li> "jti" - a unique token ID to implement an optional non-replay check (NOT validated by default).</li>
 *   <li> "nbf" - the not before timestamp.</li>
 *   <li> "exp" - the expiration timestamp is ensuring that a request isn't captured and used at a later time.</li>
 *   <li> "iss" - the issuer name, always MessageBird.</li>
 * </ul>
 *
 * @param clock       custom {@link Clock} instance to validate timestamp claims.
 * @param signature   the actual signature.
 * @param url         the raw url including the protocol, hostname and query string,
 *                    {@code https://example.com/?example=42}.
 * @param requestBody the raw request body.
 * @return raw signature payload as {@link DecodedJWT} object.
 * @throws RequestValidationException when the signature is invalid.
 * @see <a href="https://developers.messagebird.com/docs/verify-http-requests">Verify HTTP Requests</a>
 */
public DecodedJWT validateSignature(Clock clock, String signature, String url, byte[] requestBody) throws RequestValidationException {
    if (signature == null || signature.length() == 0)
        throw new RequestValidationException("The signature can not be empty.");
    if (!skipURLValidation && (url == null || url.length() == 0))
        throw new RequestValidationException("The url can not be empty.");
    DecodedJWT jwt = JWT.decode(signature);
    Algorithm algorithm;
    switch(jwt.getAlgorithm()) {
        case "HS256":
            algorithm = HMAC256;
            break;
        case "HS384":
            algorithm = HMAC384;
            break;
        case "HS512":
            algorithm = HMAC512;
            break;
        default:
            throw new RequestValidationException(String.format("The signing method '%s' is invalid.", jwt.getAlgorithm()));
    }
    BaseVerification builder = (BaseVerification) JWT.require(algorithm).withIssuer("MessageBird").ignoreIssuedAt().acceptLeeway(1);
    if (!skipURLValidation)
        builder.withClaim("url_hash", calculateSha256(url.getBytes()));
    boolean payloadHashClaimExist = !jwt.getClaim("payload_hash").isNull();
    if (requestBody != null && requestBody.length > 0) {
        if (!payloadHashClaimExist) {
            throw new RequestValidationException("The Claim 'payload_hash' is not set but payload is present.");
        }
        builder.withClaim("payload_hash", calculateSha256(requestBody));
    } else if (payloadHashClaimExist) {
        throw new RequestValidationException("The Claim 'payload_hash' is set but actual payload is missing.");
    }
    JWTVerifier verifier = clock == null ? builder.build() : builder.build(clock);
    try {
        return verifier.verify(jwt);
    } catch (SignatureVerificationException e) {
        throw new RequestValidationException("Signature is invalid.", e);
    } catch (JWTVerificationException e) {
        throw new RequestValidationException(e.getMessage(), e.getCause());
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) RequestValidationException(com.messagebird.exceptions.RequestValidationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) BaseVerification(com.auth0.jwt.JWTVerifier.BaseVerification)

Example 74 with JWT

use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.

the class AbstractAuthenticationResource method connectUser.

protected Response connectUser(String userId) {
    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
    Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
    // We must also load permissions from repository for configured management or portal role
    RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
    if (role != null) {
        authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
    }
    role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
    if (role != null) {
        authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
    }
    // JWT signer
    final Map<String, Object> claims = new HashMap<>();
    claims.put(JWTHelper.Claims.ISSUER, environment.getProperty("jwt.issuer", JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER));
    claims.put(JWTHelper.Claims.SUBJECT, user.getId());
    claims.put(JWTHelper.Claims.PERMISSIONS, authorities);
    claims.put(JWTHelper.Claims.EMAIL, user.getEmail());
    claims.put(JWTHelper.Claims.FIRSTNAME, user.getFirstname());
    claims.put(JWTHelper.Claims.LASTNAME, user.getLastname());
    final JWTSigner.Options options = new JWTSigner.Options();
    options.setExpirySeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER));
    options.setIssuedAt(true);
    options.setJwtId(true);
    return Response.ok().entity(user).cookie(new NewCookie(HttpHeaders.AUTHORIZATION, "Bearer " + new JWTSigner(environment.getProperty("jwt.secret")).sign(claims, options), environment.getProperty("jwt.cookie-path", "/"), environment.getProperty("jwt.cookie-domain"), "", environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER), environment.getProperty("jwt.cookie-secure", Boolean.class, false), true)).build();
}
Also used : HashMap(java.util.HashMap) JWTSigner(com.auth0.jwt.JWTSigner) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserEntity(io.gravitee.management.model.UserEntity) RoleEntity(io.gravitee.management.model.RoleEntity) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) HashSet(java.util.HashSet) NewCookie(javax.ws.rs.core.NewCookie)

Example 75 with JWT

use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.

the class OAuth2AuthenticationResourceTest method verifyJwtToken.

private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerifyException {
    String cookieContent = response.getCookies().get(HttpHeaders.AUTHORIZATION).getValue();
    assertThat(cookieContent, StringStartsWith.startsWith("Bearer "));
    String jwt = cookieContent.substring(7);
    JWTVerifier jwtVerifier = new JWTVerifier("myJWT4Gr4v1t33_S3cr3t");
    Map<String, Object> mapJwt = jwtVerifier.verify(jwt);
    assertEquals(mapJwt.get("sub"), "janedoe@example.com");
    assertEquals(mapJwt.get("firstname"), "Jane");
    assertEquals(mapJwt.get("iss"), "gravitee-management-auth");
    assertEquals(mapJwt.get("sub"), "janedoe@example.com");
    assertEquals(mapJwt.get("email"), "janedoe@example.com");
    assertEquals(mapJwt.get("lastname"), "Doe");
}
Also used : Matchers.anyString(org.mockito.Matchers.anyString) JWTVerifier(com.auth0.jwt.JWTVerifier)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)99 Test (org.junit.jupiter.api.Test)80 GrantedAuthority (org.springframework.security.core.GrantedAuthority)51 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)23 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 Arrays (java.util.Arrays)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 List (java.util.List)17 Algorithm (com.auth0.jwt.algorithms.Algorithm)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Authentication (org.springframework.security.core.Authentication)16 Test (org.junit.Test)14 HashMap (java.util.HashMap)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Instant (java.time.Instant)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 JWTVerifier (com.auth0.jwt.JWTVerifier)10