Search in sources :

Example 51 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project flow by vaadin.

the class JwtSecurityContextRepositoryTest method saveContext_doesNotSaveJwt_when_keySourceNull.

@Test
public void saveContext_doesNotSaveJwt_when_keySourceNull() throws JOSEException {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    JWSHeader header = getHeaderBuilder().build();
    JWTClaimsSet claimsSet = getClaimsSetBuilder().build();
    Mockito.doReturn(getJwtAuthenticationToken(header, claimsSet)).when(securityContext).getAuthentication();
    jwtSecurityContextRepository.setJwkSource(null);
    Assert.assertThrows(NullPointerException.class, () -> jwtSecurityContextRepository.saveContext(securityContext, request, response));
    String serializedJwt = getSavedSerializedJwt();
    Assert.assertNull(serializedJwt);
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SecurityContext(org.springframework.security.core.context.SecurityContext) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.Test)

Example 52 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project flow by vaadin.

the class JwtSecurityContextRepositoryTest method saveContext_doesSaveJwt_when_givenJwtContext.

@Test
public void saveContext_doesSaveJwt_when_givenJwtContext() throws JOSEException, BadJOSEException, ParseException {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    JWSHeader header = getHeaderBuilder().build();
    JWTClaimsSet claimsSet = getClaimsSetBuilder().build();
    Mockito.doReturn(getJwtAuthenticationToken(header, claimsSet)).when(securityContext).getAuthentication();
    jwtSecurityContextRepository.saveContext(securityContext, request, response);
    String serializedJwt = getSavedSerializedJwt();
    JWTClaimsSet decodedClaimsSet = decodeSerializedJwt(serializedJwt, jwtProcessor);
    assertClaims(decodedClaimsSet, TEST_USERNAME, TEST_ROLES, 1800);
    Assert.assertEquals(null, decodedClaimsSet.getIssuer());
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SecurityContext(org.springframework.security.core.context.SecurityContext) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.Test)

Example 53 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project connect-android-sdk by telenordigital.

the class IdTokenValidatorTest method expiredTimeThrows.

@Test(expected = ConnectException.class)
public void expiredTimeThrows() throws Exception {
    BDDMockito.given(ConnectSdk.getConnectApiUrl()).willReturn(HttpUrl.parse("https://connect.telenordigital.com"));
    BDDMockito.given(ConnectSdk.getClientId()).willReturn("connect-tests");
    BDDMockito.given(ConnectSdk.getExpectedIssuer()).willReturn("https://connect.telenordigital.com/oauth");
    JWTClaimsSet claimsSet = new JWTClaimsSet();
    claimsSet.setIssuer("https://connect.telenordigital.com/oauth");
    claimsSet.setAudience("connect-tests");
    claimsSet.setExpirationTime(twoHoursAgo);
    claimsSet.setIssueTime(now);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.ES256), claimsSet);
    signedJWT.sign(new ECDSASigner(new BigInteger("123")));
    IdToken idToken = new IdToken(signedJWT.serialize());
    IdTokenValidator.validate(idToken, null);
}
Also used : IdToken(com.telenor.connect.id.IdToken) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) BigInteger(java.math.BigInteger) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 54 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project scoold by Erudika.

the class ScooldUtils method generateJWToken.

public SignedJWT generateJWToken(Map<String, Object> claims, long validitySeconds) {
    String secret = Config.getConfigParam("app_secret_key", "");
    if (!StringUtils.isBlank(secret)) {
        try {
            Date now = new Date();
            JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
            claimsSet.issueTime(now);
            if (validitySeconds > 0) {
                claimsSet.expirationTime(new Date(now.getTime() + (validitySeconds * 1000)));
            }
            claimsSet.notBeforeTime(now);
            claimsSet.claim(Config._APPID, Config.getConfigParam("access_key", "x"));
            claims.entrySet().forEach((claim) -> claimsSet.claim(claim.getKey(), claim.getValue()));
            JWSSigner signer = new MACSigner(secret);
            SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
            signedJWT.sign(signer);
            return signedJWT;
        } catch (JOSEException e) {
            logger.warn("Unable to sign JWT: {}.", e.getMessage());
        }
    }
    logger.error("Failed to generate JWT token - app_secret_key is blank.");
    return null;
}
Also used : MACSigner(com.nimbusds.jose.crypto.MACSigner) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) Date(java.util.Date) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 55 with JWSHeader

use of com.nimbusds.jose.JWSHeader 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

JWSHeader (com.nimbusds.jose.JWSHeader)67 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)56 SignedJWT (com.nimbusds.jwt.SignedJWT)50 Test (org.junit.Test)24 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)21 JWSSigner (com.nimbusds.jose.JWSSigner)18 ArrayList (java.util.ArrayList)12 SecurityContext (org.springframework.security.core.context.SecurityContext)12 OAuth2TokenValidator (org.springframework.security.oauth2.core.OAuth2TokenValidator)12 JOSEException (com.nimbusds.jose.JOSEException)11 DelegatingOAuth2TokenValidator (org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator)10 RestOperations (org.springframework.web.client.RestOperations)10 Test (org.junit.jupiter.api.Test)9 Date (java.util.Date)8 Jwt (org.springframework.security.oauth2.jwt.Jwt)8 JSONObject (net.minidev.json.JSONObject)7 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)6 MACSigner (com.nimbusds.jose.crypto.MACSigner)6 JWK (com.nimbusds.jose.jwk.JWK)6 PrivateKey (java.security.PrivateKey)6