Search in sources :

Example 26 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project spring-security by spring-projects.

the class NimbusJwtDecoder method createJwt.

private Jwt createJwt(String token, JWT parsedJwt) {
    try {
        // Verify the signature
        JWTClaimsSet jwtClaimsSet = this.jwtProcessor.process(parsedJwt, null);
        Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
        Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
        // @formatter:off
        return Jwt.withTokenValue(token).headers((h) -> h.putAll(headers)).claims((c) -> c.putAll(claims)).build();
    // @formatter:on
    } catch (RemoteKeySourceException ex) {
        this.logger.trace("Failed to retrieve JWK set", ex);
        if (ex.getCause() instanceof ParseException) {
            throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed Jwk set"), ex);
        }
        throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
    } catch (JOSEException ex) {
        this.logger.trace("Failed to process JWT", ex);
        throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
    } catch (Exception ex) {
        this.logger.trace("Failed to process JWT", ex);
        if (ex.getCause() instanceof ParseException) {
            throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed payload"), ex);
        }
        throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
    }
}
Also used : Arrays(java.util.Arrays) URL(java.net.URL) JOSEException(com.nimbusds.jose.JOSEException) JWKSet(com.nimbusds.jose.jwk.JWKSet) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) JWTParser(com.nimbusds.jwt.JWTParser) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) JWKSetCache(com.nimbusds.jose.jwk.source.JWKSetCache) PlainJWT(com.nimbusds.jwt.PlainJWT) RSAPublicKey(java.security.interfaces.RSAPublicKey) Map(java.util.Map) JWT(com.nimbusds.jwt.JWT) ParseException(java.text.ParseException) RestTemplate(org.springframework.web.client.RestTemplate) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) HttpHeaders(org.springframework.http.HttpHeaders) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) SecretKey(javax.crypto.SecretKey) LogFactory(org.apache.commons.logging.LogFactory) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) SecurityContext(com.nimbusds.jose.proc.SecurityContext) Resource(com.nimbusds.jose.util.Resource) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) Cache(org.springframework.cache.Cache) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWTProcessor(com.nimbusds.jwt.proc.JWTProcessor) RemoteJWKSet(com.nimbusds.jose.jwk.source.RemoteJWKSet) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) RemoteKeySourceException(com.nimbusds.jose.RemoteKeySourceException) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) Converter(org.springframework.core.convert.converter.Converter) RequestEntity(org.springframework.http.RequestEntity) ConfigurableJWTProcessor(com.nimbusds.jwt.proc.ConfigurableJWTProcessor) MalformedURLException(java.net.MalformedURLException) HttpMethod(org.springframework.http.HttpMethod) IOException(java.io.IOException) RestOperations(org.springframework.web.client.RestOperations) SingleKeyJWSKeySelector(com.nimbusds.jose.proc.SingleKeyJWSKeySelector) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) Consumer(java.util.function.Consumer) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Log(org.apache.commons.logging.Log) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RemoteKeySourceException(com.nimbusds.jose.RemoteKeySourceException) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) JOSEException(com.nimbusds.jose.JOSEException) ParseException(java.text.ParseException) RemoteKeySourceException(com.nimbusds.jose.RemoteKeySourceException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 27 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project spring-security by spring-projects.

the class NimbusJwtEncoder method convert.

private static JWTClaimsSet convert(JwtClaimsSet claims) {
    JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
    // NOTE: The value of the 'iss' claim is a String or URL (StringOrURI).
    Object issuer = claims.getClaim(JwtClaimNames.ISS);
    if (issuer != null) {
        builder.issuer(issuer.toString());
    }
    String subject = claims.getSubject();
    if (StringUtils.hasText(subject)) {
        builder.subject(subject);
    }
    List<String> audience = claims.getAudience();
    if (!CollectionUtils.isEmpty(audience)) {
        builder.audience(audience);
    }
    Instant expiresAt = claims.getExpiresAt();
    if (expiresAt != null) {
        builder.expirationTime(Date.from(expiresAt));
    }
    Instant notBefore = claims.getNotBefore();
    if (notBefore != null) {
        builder.notBeforeTime(Date.from(notBefore));
    }
    Instant issuedAt = claims.getIssuedAt();
    if (issuedAt != null) {
        builder.issueTime(Date.from(issuedAt));
    }
    String jwtId = claims.getId();
    if (StringUtils.hasText(jwtId)) {
        builder.jwtID(jwtId);
    }
    Map<String, Object> customClaims = new HashMap<>();
    claims.getClaims().forEach((name, value) -> {
        if (!JWTClaimsSet.getRegisteredNames().contains(name)) {
            customClaims.put(name, value);
        }
    });
    if (!customClaims.isEmpty()) {
        customClaims.forEach(builder::claim);
    }
    return builder.build();
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Instant(java.time.Instant)

Example 28 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project tomee by apache.

the class Tokens method asToken.

public static String asToken(final String claims) throws Exception {
    final PrivateKey pk = readPrivateKey("/testkey.pem");
    try {
        final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);
        final SignedJWT jwt = new SignedJWT(header, claimsSet);
        jwt.sign(new RSASSASigner(pk));
        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 29 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method createEmptyJWTwithPublicKey.

/**
 * creates an empty JSON Web Token
 *
 * @param webAppBaseURL - the base url of the application
 *
 * @return the JSON WebToken
 */
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {
    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString()).issueTime(Date.from(currentTime.toInstant())).build();
    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        LOGGER.error(e);
    }
    return signedJWT;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 30 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method createJWT.

/**
 * creates a JSON Web Token with user id, roles and client public key
 *
 * @param user - the user that should be returned
 * @param roles - the roles that should be returned
 * @param webAppBaseURL - the base url of the application
 * @param clientPublicKey -  the client public key as JSON Web Key
 *
 * @return the JSON WebToken
 */
public static SignedJWT createJWT(String user, List<String> roles, String webAppBaseURL, JWK clientPublicKey) {
    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString()).expirationTime(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).issueTime(Date.from(currentTime.toInstant())).notBeforeTime(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).subject(user).claim("roles", roles).claim("sub_jwk", clientPublicKey).build();
    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        // TODO Auto-generated catch block
        LOGGER.error(e);
    }
    System.out.println("JWT: " + signedJWT.serialize());
    return signedJWT;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Aggregations

JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)69 SignedJWT (com.nimbusds.jwt.SignedJWT)44 JWSHeader (com.nimbusds.jose.JWSHeader)23 Date (java.util.Date)19 Test (org.junit.Test)16 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)14 Test (org.junit.jupiter.api.Test)11 JOSEException (com.nimbusds.jose.JOSEException)9 ParseException (java.text.ParseException)9 SecretKey (javax.crypto.SecretKey)8 JWSSigner (com.nimbusds.jose.JWSSigner)7 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)7 Instant (java.time.Instant)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)6 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)5 MACSigner (com.nimbusds.jose.crypto.MACSigner)5 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)5 JWT (com.nimbusds.jwt.JWT)5