Search in sources :

Example 1 with JwtClaimsSet

use of org.springframework.security.oauth2.jwt.JwtClaimsSet in project spring-security by spring-projects.

the class NimbusJwtClientAuthenticationParametersConverter method convert.

@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
    Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(clientRegistration.getClientAuthenticationMethod())) {
        return null;
    }
    JWK jwk = this.jwkResolver.apply(clientRegistration);
    if (jwk == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE, "Failed to resolve JWK signing key for client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
    if (jwsAlgorithm == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE, "Unable to resolve JWS (signing) algorithm from JWK associated to client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
    // @formatter:off
    JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder().issuer(clientRegistration.getClientId()).subject(clientRegistration.getClientId()).audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri())).id(UUID.randomUUID().toString()).issuedAt(issuedAt).expiresAt(expiresAt);
    // @formatter:on
    JwsHeader jwsHeader = headersBuilder.build();
    JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
    JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(), (clientRegistrationId, currentJwsEncoderHolder) -> {
        if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
            return currentJwsEncoderHolder;
        }
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
    });
    JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
    Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
    return parameters;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwsHeader(org.springframework.security.oauth2.jwt.JwsHeader) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWK(com.nimbusds.jose.jwk.JWK)

Example 2 with JwtClaimsSet

use of org.springframework.security.oauth2.jwt.JwtClaimsSet in project spring-security by spring-projects.

the class NimbusReactiveJwtDecoderTests method decodeWhenSecretKeyAndAlgorithmMismatchThenThrowsJwtException.

@Test
public void decodeWhenSecretKeyAndAlgorithmMismatchThenThrowsJwtException() throws Exception {
    SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
    MacAlgorithm macAlgorithm = MacAlgorithm.HS256;
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
    SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet);
    // @formatter:off
    this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build();
    assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode(signedJWT.serialize()).block());
// @formatter:on
}
Also used : MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) SecretKey(javax.crypto.SecretKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.jupiter.api.Test)

Example 3 with JwtClaimsSet

use of org.springframework.security.oauth2.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 4 with JwtClaimsSet

use of org.springframework.security.oauth2.jwt.JwtClaimsSet in project flow by vaadin.

the class JwtSecurityContextRepository method encodeJwt.

private String encodeJwt(Authentication authentication) throws JOSEException {
    if (authentication == null || trustResolver.isAnonymous(authentication)) {
        return null;
    }
    final Date now = new Date();
    final List<String> roles = authentication.getAuthorities().stream().map(Objects::toString).filter(a -> a.startsWith(ROLE_AUTHORITY_PREFIX)).map(a -> a.substring(ROLE_AUTHORITY_PREFIX.length())).collect(Collectors.toList());
    SignedJWT signedJWT;
    JWSHeader jwsHeader = new JWSHeader(jwsAlgorithm);
    JWKSelector jwkSelector = new JWKSelector(JWKMatcher.forJWSHeader(jwsHeader));
    List<JWK> jwks = jwkSource.get(jwkSelector, null);
    JWK jwk = jwks.get(0);
    JWSSigner signer = new DefaultJWSSignerFactory().createJWSSigner(jwk, jwsAlgorithm);
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(authentication.getName()).issuer(issuer).issueTime(now).expirationTime(new Date(now.getTime() + expiresIn * 1000)).claim(ROLES_CLAIM, roles).build();
    signedJWT = new SignedJWT(jwsHeader, claimsSet);
    signedJWT.sign(signer);
    return signedJWT.serialize();
}
Also used : JwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) JWKSelector(com.nimbusds.jose.jwk.JWKSelector) HttpRequestResponseHolder(org.springframework.security.web.context.HttpRequestResponseHolder) Date(java.util.Date) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JOSEException(com.nimbusds.jose.JOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SaveContextOnUpdateOrErrorResponseWrapper(org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtGrantedAuthoritiesConverter(org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) JwtValidators(org.springframework.security.oauth2.jwt.JwtValidators) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Collectors(java.util.stream.Collectors) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) JWK(com.nimbusds.jose.jwk.JWK) Objects(java.util.Objects) List(java.util.List) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) AuthenticationTrustResolver(org.springframework.security.authentication.AuthenticationTrustResolver) JWSSigner(com.nimbusds.jose.JWSSigner) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) SecurityContext(org.springframework.security.core.context.SecurityContext) JwtException(org.springframework.security.oauth2.jwt.JwtException) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) AuthenticationTrustResolverImpl(org.springframework.security.authentication.AuthenticationTrustResolverImpl) JWKMatcher(com.nimbusds.jose.jwk.JWKMatcher) Authentication(org.springframework.security.core.Authentication) JWKSelector(com.nimbusds.jose.jwk.JWKSelector) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 5 with JwtClaimsSet

use of org.springframework.security.oauth2.jwt.JwtClaimsSet in project dhis2-core by dhis2.

the class JwtUtils method encode.

public Jwt encode(JoseHeader headers, JwtClaimsSet claims) throws JwtEncodingException {
    Assert.notNull(headers, "headers cannot be null");
    Assert.notNull(claims, "claims cannot be null");
    JWK jwk = selectJwk(headers);
    if (jwk == null) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
    } else if (!StringUtils.hasText(jwk.getKeyID())) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "The \"kid\" (key ID) from the selected JWK cannot be empty"));
    }
    headers = JoseHeader.from(headers).type(JOSEObjectType.JWT.getType()).keyId(jwk.getKeyID()).build();
    claims = JwtClaimsSet.from(claims).id(UUID.randomUUID().toString()).build();
    JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers);
    JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims);
    JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, (key) -> {
        try {
            return JWS_SIGNER_FACTORY.createJWSSigner(key);
        } catch (JOSEException ex) {
            throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to create a JWS Signer -> " + ex.getMessage()), ex);
        }
    });
    SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
    try {
        signedJwt.sign(jwsSigner);
    } catch (JOSEException ex) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
    }
    String jws = signedJwt.serialize();
    return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims());
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Jwt(org.springframework.security.oauth2.jwt.Jwt) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Aggregations

JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)9 SignedJWT (com.nimbusds.jwt.SignedJWT)8 SecretKey (javax.crypto.SecretKey)7 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)7 Test (org.junit.jupiter.api.Test)5 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)4 JWSHeader (com.nimbusds.jose.JWSHeader)4 JWSSigner (com.nimbusds.jose.JWSSigner)4 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)4 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)4 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)4 SecurityContext (com.nimbusds.jose.proc.SecurityContext)4 DefaultJWTProcessor (com.nimbusds.jwt.proc.DefaultJWTProcessor)4 JWTProcessor (com.nimbusds.jwt.proc.JWTProcessor)3 RSAPublicKey (java.security.interfaces.RSAPublicKey)3 ParseException (java.text.ParseException)3 Instant (java.time.Instant)3 JOSEException (com.nimbusds.jose.JOSEException)2 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)2 MACSigner (com.nimbusds.jose.crypto.MACSigner)2