Search in sources :

Example 1 with Base64URL

use of com.nimbusds.jose.util.Base64URL in project knox by apache.

the class JWTToken method getSignaturePayload.

/* (non-Javadoc)
   * @see org.apache.knox.gateway.services.security.token.impl.JWT#getSignaturePayload()
   */
@Override
public byte[] getSignaturePayload() {
    byte[] b = null;
    Base64URL b64 = jwt.getSignature();
    if (b64 != null) {
        b = b64.decode();
    }
    return b;
}
Also used : Base64URL(com.nimbusds.jose.util.Base64URL)

Example 2 with Base64URL

use of com.nimbusds.jose.util.Base64URL in project spring-security by spring-projects.

the class NimbusJwtEncoder method convert.

private static JWSHeader convert(JwsHeader headers) {
    JWSHeader.Builder builder = new JWSHeader.Builder(JWSAlgorithm.parse(headers.getAlgorithm().getName()));
    if (headers.getJwkSetUrl() != null) {
        builder.jwkURL(convertAsURI(JoseHeaderNames.JKU, headers.getJwkSetUrl()));
    }
    Map<String, Object> jwk = headers.getJwk();
    if (!CollectionUtils.isEmpty(jwk)) {
        try {
            builder.jwk(JWK.parse(jwk));
        } catch (Exception ex) {
            throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Unable to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex);
        }
    }
    String keyId = headers.getKeyId();
    if (StringUtils.hasText(keyId)) {
        builder.keyID(keyId);
    }
    if (headers.getX509Url() != null) {
        builder.x509CertURL(convertAsURI(JoseHeaderNames.X5U, headers.getX509Url()));
    }
    List<String> x509CertificateChain = headers.getX509CertificateChain();
    if (!CollectionUtils.isEmpty(x509CertificateChain)) {
        List<Base64> x5cList = new ArrayList<>();
        x509CertificateChain.forEach((x5c) -> x5cList.add(new Base64(x5c)));
        if (!x5cList.isEmpty()) {
            builder.x509CertChain(x5cList);
        }
    }
    String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint();
    if (StringUtils.hasText(x509SHA1Thumbprint)) {
        builder.x509CertThumbprint(new Base64URL(x509SHA1Thumbprint));
    }
    String x509SHA256Thumbprint = headers.getX509SHA256Thumbprint();
    if (StringUtils.hasText(x509SHA256Thumbprint)) {
        builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint));
    }
    String type = headers.getType();
    if (StringUtils.hasText(type)) {
        builder.type(new JOSEObjectType(type));
    }
    String contentType = headers.getContentType();
    if (StringUtils.hasText(contentType)) {
        builder.contentType(contentType);
    }
    Set<String> critical = headers.getCritical();
    if (!CollectionUtils.isEmpty(critical)) {
        builder.criticalParams(critical);
    }
    Map<String, Object> customHeaders = new HashMap<>();
    headers.getHeaders().forEach((name, value) -> {
        if (!JWSHeader.getRegisteredParameterNames().contains(name)) {
            customHeaders.put(name, value);
        }
    });
    if (!customHeaders.isEmpty()) {
        builder.customParams(customHeaders);
    }
    return builder.build();
}
Also used : JOSEObjectType(com.nimbusds.jose.JOSEObjectType) Base64(com.nimbusds.jose.util.Base64) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) JOSEException(com.nimbusds.jose.JOSEException) Base64URL(com.nimbusds.jose.util.Base64URL) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 3 with Base64URL

use of com.nimbusds.jose.util.Base64URL in project spring-security by spring-projects.

the class NimbusJwtEncoderTests method encodeWhenJwkSelectWithProvidedX5TS256ThenSelected.

@Test
public void encodeWhenJwkSelectWithProvidedX5TS256ThenSelected() {
    // @formatter:off
    RSAKey rsaJwk1 = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY).x509CertSHA256Thumbprint(new Base64URL("x509CertSHA256Thumbprint-1")).keyID(null).build();
    this.jwkList.add(rsaJwk1);
    RSAKey rsaJwk2 = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY).x509CertSHA256Thumbprint(new Base64URL("x509CertSHA256Thumbprint-2")).keyID(null).build();
    this.jwkList.add(rsaJwk2);
    // @formatter:on
    JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).x509SHA256Thumbprint(rsaJwk1.getX509CertSHA256Thumbprint().toString()).build();
    JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
    Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T_S256)).isEqualTo(rsaJwk1.getX509CertSHA256Thumbprint().toString());
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isNull();
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) Base64URL(com.nimbusds.jose.util.Base64URL) Test(org.junit.jupiter.api.Test)

Example 4 with Base64URL

use of com.nimbusds.jose.util.Base64URL in project ddf by codice.

the class OidcTokenValidator method validateAccessTokenSignature.

/**
 * Validates an access token's signature
 *
 * @param accessToken - the token to validate
 * @param idToken - the corresponding ID token or null if one is not available. If an ID token is
 *     provided, the signature algorithm in the ID token is used. Otherwise the Algorithm provided
 *     in the header of the access token is used.
 * @param resourceRetriever - resource retriever
 * @param metadata - OIDC metadata
 */
private static void validateAccessTokenSignature(AccessToken accessToken, JWT idToken, ResourceRetriever resourceRetriever, OIDCProviderMetadata metadata) throws OidcValidationException {
    try {
        ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor();
        JWKSource keySource = new RemoteJWKSet(metadata.getJWKSetURI().toURL(), resourceRetriever);
        // Get signature algorithm, if ID token is given get algorithm from ID Token otherwise
        // get algorithm from access token header
        Algorithm expectedAlgorithm;
        if (idToken == null || idToken.getHeader().getAlgorithm() == Algorithm.NONE) {
            String accessTokenString = accessToken.getValue();
            Base64URL header = new Base64URL(accessTokenString.substring(0, accessTokenString.indexOf('.')));
            JSONObject jsonObject = JSONObjectUtils.parse(header.decodeToString());
            expectedAlgorithm = Header.parseAlgorithm(jsonObject);
        } else {
            expectedAlgorithm = idToken.getHeader().getAlgorithm();
        }
        if (expectedAlgorithm == Algorithm.NONE) {
            LOGGER.error("Error validating access token. Access token was not signed.");
            throw new OidcValidationException("Error validating access token. Access token was not signed.");
        }
        JWSAlgorithm expectedJWSAlgorithm = new JWSAlgorithm(expectedAlgorithm.getName(), expectedAlgorithm.getRequirement());
        JWSKeySelector keySelector = new JWSVerificationKeySelector(expectedJWSAlgorithm, keySource);
        jwtProcessor.setJWSKeySelector(keySelector);
        jwtProcessor.process(accessToken.getValue(), null);
    } catch (Exception e) {
        LOGGER.error(ACCESS_VALIDATION_ERR_MSG, e);
        throw new OidcValidationException(ACCESS_VALIDATION_ERR_MSG, e);
    }
}
Also used : JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Algorithm(com.nimbusds.jose.Algorithm) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) RemoteJWKSet(com.nimbusds.jose.jwk.source.RemoteJWKSet) Base64URL(com.nimbusds.jose.util.Base64URL) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) ConfigurableJWTProcessor(com.nimbusds.jwt.proc.ConfigurableJWTProcessor) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) JSONObject(net.minidev.json.JSONObject) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector)

Example 5 with Base64URL

use of com.nimbusds.jose.util.Base64URL in project metron by apache.

the class KnoxSSOAuthenticationFilterTest method validateSignatureShouldProperlyValidateToken.

@Test
public void validateSignatureShouldProperlyValidateToken() throws Exception {
    KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("userSearchBase", mock(Path.class), "knoxKeyString", "knoxCookie", mock(LdapTemplate.class)));
    SignedJWT jwtToken = mock(SignedJWT.class);
    {
        // Should be invalid if algorithm is not ES256
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.ES384);
        when(jwtToken.getHeader()).thenReturn(jwsHeader);
        assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
    }
    {
        // Should be invalid if state is not SIGNED
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.RS256);
        when(jwtToken.getHeader()).thenReturn(jwsHeader);
        when(jwtToken.getState()).thenReturn(JWSObject.State.UNSIGNED);
        assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
    }
    {
        // Should be invalid if signature is null
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.RS256);
        when(jwtToken.getHeader()).thenReturn(jwsHeader);
        when(jwtToken.getState()).thenReturn(JWSObject.State.SIGNED);
        assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
    }
    {
        Base64URL signature = mock(Base64URL.class);
        when(jwtToken.getSignature()).thenReturn(signature);
        RSAPublicKey rsaPublicKey = mock(RSAPublicKey.class);
        RSASSAVerifier rsaSSAVerifier = mock(RSASSAVerifier.class);
        doReturn(rsaSSAVerifier).when(knoxSSOAuthenticationFilter).getRSASSAVerifier();
        {
            // Should be invalid if token verify throws an exception
            when(jwtToken.verify(rsaSSAVerifier)).thenThrow(new JOSEException("verify exception"));
            assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
        }
        {
            // Should be invalid if RSA verification fails
            doReturn(false).when(jwtToken).verify(rsaSSAVerifier);
            assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
        }
        {
            // Should be valid if RSA verification succeeds
            doReturn(true).when(jwtToken).verify(rsaSSAVerifier);
            assertTrue(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
        }
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) Base64URL(com.nimbusds.jose.util.Base64URL) Test(org.junit.jupiter.api.Test)

Aggregations

Base64URL (com.nimbusds.jose.util.Base64URL)8 Test (org.junit.jupiter.api.Test)4 RSAKey (com.nimbusds.jose.jwk.RSAKey)3 JOSEException (com.nimbusds.jose.JOSEException)2 JWSHeader (com.nimbusds.jose.JWSHeader)2 HashMap (java.util.HashMap)2 Algorithm (com.nimbusds.jose.Algorithm)1 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)1 ECKey (com.nimbusds.jose.jwk.ECKey)1 JWKSelector (com.nimbusds.jose.jwk.JWKSelector)1 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)1 RemoteJWKSet (com.nimbusds.jose.jwk.source.RemoteJWKSet)1 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)1 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)1 SecurityContext (com.nimbusds.jose.proc.SecurityContext)1 Base64 (com.nimbusds.jose.util.Base64)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ConfigurableJWTProcessor (com.nimbusds.jwt.proc.ConfigurableJWTProcessor)1