com.nimbusds.jose.JWSHeader Java Examples

The following examples show how to use com.nimbusds.jose.JWSHeader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 8 votes vote down vote up
@Test
public void testValidSignature_RSA() throws NoSuchAlgorithmException, JOSEException {
    //Generate RSA key
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair rsaKey = kpg.generateKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) rsaKey.getPublic();
    RSAKey key = new RSAKey();
    key.setKty("RSA");
    key.setKid(KID);
    key.setE(Base64.getUrlEncoder().encodeToString(publicKey.getPublicExponent().toByteArray()));
    key.setN(Base64.getUrlEncoder().encodeToString(publicKey.getModulus().toByteArray()));

    //Sign JWT with RSA algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new RSASSASigner((RSAPrivateKey) rsaKey.getPrivate()));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #2
Source File: ScooldUtils.java    From scoold with Apache License 2.0 7 votes vote down vote up
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;
}
 
Example #3
Source File: EncryptionUtility.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
public String sign(String algorithm, String kid, String keyStr, String dataToSign) {
    try {

        Key key = getKey(algorithm, keyStr);

        JWSHeader.Builder jwsBuilder = new JWSHeader.Builder("HS256".equals(algorithm) ? JWSAlgorithm.HS256 : JWSAlgorithm.RS256);
        jwsBuilder.keyID(kid);

        JWSHeader signingHeader = jwsBuilder.build();
        JWSSigner signer = "HS256".equals(algorithm) ? new MACSigner(key.getEncoded()) : new RSASSASigner((RSAPrivateKey) key);
        JWSObject jwsObject = new JWSObject(signingHeader, new Payload(dataToSign));
        jwsObject.sign(signer);
        checkObject(jwsObject);

        String parts[] = jwsObject.serialize().split("\\.");

        return "{\"protected\":\"" + parts[0] + "\", \"payload\":\"" + parts[1] + "\", \"signature\":\"" + parts[2] + "\"}";

    } catch (Exception e) {
        throw new CryptoException("Exception signing data: " + e.getMessage(), e);
    }
}
 
Example #4
Source File: JwkKeyPairManager.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public String getSignedContent(String content) {
    Payload contentPayload = new Payload(content);

    try {
        RSASSASigner rsa = new RSASSASigner((RSAPrivateKey) clientJwk);
        JWSAlgorithm alg = JWSAlgorithm.RS256;
        JWSHeader header = new JWSHeader.Builder(alg)
            .keyID(clientJwk.getKeyID())
            .build();
        JWSObject jws = new JWSObject(header, contentPayload);
        jws.sign(rsa);
        return jws.serialize();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void refreshFlowTests()  throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.subject("test-subject")
			.expirationTime(Date.from(Instant.now().plusSeconds(60)))
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	OAuth2TokenValidator validator = mock(OAuth2TokenValidator.class);
	when(validator.validate(any())).thenReturn(OAuth2TokenValidatorResult.success());
	RestOperations operations = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	decoder.decode(signedJWT.serialize());
	decoder.decode(signedJWT.serialize());
	verify(operations, times(1)).exchange(eq("https://spring.local"),
			eq(HttpMethod.GET),
			isNull(),
			eq(new ParameterizedTypeReference<Map<String, String>>() { }));
}
 
Example #6
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidIssuerTests() throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.subject("test-subject")
			.audience("123456")
			.expirationTime(Date.from(Instant.now().plusSeconds(36000)))
			.issuer("https://spring.local/123456")
			.issueTime(Date.from(Instant.now().minusSeconds(3600)))
			.claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond())
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456"));
	DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
	RestOperations operations = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	assertThatExceptionOfType(JwtException.class)
			.isThrownBy(() -> decoder.decode(signedJWT.serialize()))
			.withMessageStartingWith("An error occurred while attempting to decode the Jwt");
}
 
Example #7
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
public String build() throws CelleryAuthException {

        // Build the JWT Header
        try {
            JWSHeader jwsHeader = buildJWSHeader();
            // Add mandatory claims
            addMandatoryClaims(claimSetBuilder);
            JWTClaimsSet claimsSet = this.claimSetBuilder.build();

            SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet);
            JWSSigner signer = new RSASSASigner(getRSASigningKey());

            signedJWT.sign(signer);
            return signedJWT.serialize();
        } catch (IdentityOAuth2Exception | JOSEException e) {
            throw new CelleryAuthException("Error while generating the signed JWT.", e);
        }
    }
 
Example #8
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionErrorTests() throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.subject("test-subject")
			.expirationTime(Date.from(Instant.now().plusSeconds(60)))
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	OAuth2TokenValidator validator = mock(OAuth2TokenValidator.class);
	when(validator.validate(any())).thenReturn(OAuth2TokenValidatorResult.success());
	RestOperations operations = mock(RestOperations.class);
	when(operations.exchange(eq("https://spring.local"),
			eq(HttpMethod.GET),
			isNull(),
			eq(new ParameterizedTypeReference<Map<String, String>>() { }))).thenThrow(new RestClientException("Could not connect to remote peer"));
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	assertThatExceptionOfType(JwtException.class)
			.isThrownBy(() -> decoder.decode(signedJWT.serialize()))
			.withMessageStartingWith("Error fetching public keys");
}
 
Example #9
Source File: JSONWebTokenManager.java    From authmore-framework with Apache License 2.0 6 votes vote down vote up
@Override
public TokenResponse create(ClientDetails client, String userId, Set<String> scopes) {
    assertValidateScopes(client, scopes);
    JWTClaimsSet claims = new JWTClaimsSet.Builder()
            .claim(TOKEN_USER_ID, userId)
            .claim(TOKEN_CLIENT_ID, client.getClientId())
            .claim(TOKEN_AUTHORITIES, client.getAuthoritySet())
            .claim(TOKEN_SCOPES, scopes)
            .claim(TOKEN_EXPIRE_AT, expireAtByLiveTime(client.getAccessTokenValiditySeconds()))
            .claim(TOKEN_RESOURCE_IDS, client.getResourceIds())
            .build();
    PrivateKey privateKey = keyPair.getPrivate();
    RSASSASigner signer = new RSASSASigner(privateKey);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).build(), claims);
    try {
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        throw new OAuthException("Failed to sign jwt.");
    }
    return new TokenResponse(signedJWT.serialize(), client.getAccessTokenValiditySeconds(), scopes);
}
 
Example #10
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidAudienceTests() throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.subject("test-subject")
			.audience("123")
			.expirationTime(Date.from(Instant.now().plusSeconds(36000)))
			.issuer("https://securetoken.google.com/123456")
			.issueTime(Date.from(Instant.now().minusSeconds(3600)))
			.claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond())
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456"));
	validators.add(new FirebaseTokenValidator("123456"));
	DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
	RestOperations operations = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	assertThatExceptionOfType(JwtException.class)
			.isThrownBy(() -> decoder.decode(signedJWT.serialize()))
			.withMessageStartingWith("An error occurred while attempting to decode the Jwt: This aud claim is not equal to the configured audience");
}
 
Example #11
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidIssuedAt() throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.subject("test-subject")
			.audience("123456")
			.expirationTime(Date.from(Instant.now().plusSeconds(36000)))
			.issuer("https://securetoken.google.com/123456")
			.issueTime(Date.from(Instant.now().plusSeconds(3600)))
			.claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond())
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456"));
	validators.add(new FirebaseTokenValidator("123456"));
	DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
	RestOperations operations = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	assertThatExceptionOfType(JwtException.class)
			.isThrownBy(() -> decoder.decode(signedJWT.serialize()))
			.withMessageStartingWith("An error occurred while attempting to decode the Jwt: iat claim header must be in the past");
}
 
Example #12
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidSubject() throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.audience("123456")
			.expirationTime(Date.from(Instant.now().plusSeconds(36000)))
			.issuer("https://securetoken.google.com/123456")
			.issueTime(Date.from(Instant.now().minusSeconds(3600)))
			.claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond())
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456"));
	validators.add(new FirebaseTokenValidator("123456"));
	DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
	RestOperations operations = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	assertThatExceptionOfType(JwtException.class)
			.isThrownBy(() -> decoder.decode(signedJWT.serialize()))
			.withMessageStartingWith("An error occurred while attempting to decode the Jwt: sub claim can not be empty");
}
 
Example #13
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidSignature_OKP() throws JOSEException{
    //Generate OKP key
    OctetKeyPair okp = new OctetKeyPairGenerator(Curve.Ed25519).generate();
    OKPKey key = new OKPKey();
    key.setKty("OKP");
    key.setKid(KID);
    key.setCrv(okp.getCurve().getStdName());
    key.setX(okp.getX().toString());

    //Sign JWT with Edward Curve algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.EdDSA).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new Ed25519Signer(okp));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #14
Source File: RSAKeyProcessor.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
JWSKeySelector<C> jwsKeySelector(JWKSource<C> jwkSource, Signature signature) {
    return new JWSVerificationKeySelector<C>(signature.getAlg(), jwkSource) {
        @Override
        protected JWKMatcher createJWKMatcher(final JWSHeader jwsHeader) {

            if (! getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) {
                // Unexpected JWS alg
                return null;
            } else if (JWSAlgorithm.Family.RSA.contains(getExpectedJWSAlgorithm()) || JWSAlgorithm.Family.EC.contains(getExpectedJWSAlgorithm())) {
                // RSA or EC key matcher
                return new JWKMatcher.Builder()
                        .keyType(KeyType.forAlgorithm(getExpectedJWSAlgorithm()))
                        .keyUses(KeyUse.SIGNATURE, null)
                        .algorithms(getExpectedJWSAlgorithm(), null)
                        .x509CertSHA256Thumbprint(jwsHeader.getX509CertSHA256Thumbprint())
                        .build();
            } else {
                return null; // Unsupported algorithm
            }
        }
    };
}
 
Example #15
Source File: HMACKeyProcessor.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
JWSKeySelector<C> jwsKeySelector(JWKSource<C> jwkSource, Signature signature) {
    return new JWSVerificationKeySelector<C>(signature.getAlg(), jwkSource) {
        @Override
        protected JWKMatcher createJWKMatcher(final JWSHeader jwsHeader) {

            if (! getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) {
                // Unexpected JWS alg
                return null;
            } else if (JWSAlgorithm.Family.HMAC_SHA.contains(getExpectedJWSAlgorithm())) {
                // HMAC secret matcher
                return new JWKMatcher.Builder()
                        .keyType(KeyType.forAlgorithm(getExpectedJWSAlgorithm()))
                        .privateOnly(true)
                        .algorithms(getExpectedJWSAlgorithm(), null)
                        .build();
            } else {
                return null; // Unsupported algorithm
            }
        }
    };
}
 
Example #16
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidSignature_OCT() throws JOSEException{
    // Generate random 256-bit (32-byte) shared secret
    SecureRandom random = new SecureRandom();
    byte[] sharedSecret = new byte[32];
    random.nextBytes(sharedSecret);

    OCTKey key = new OCTKey();
    key.setKty("oct");
    key.setKid(KID);
    key.setK(Base64.getEncoder().encodeToString(sharedSecret));

    //Sign JWT with MAC algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.HS256).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new MACSigner(sharedSecret));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #17
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createToken( String headerJson, String claimJson, String sharedKey )
{
    try
    {
        JWSHeader header = JWSHeader.parse( headerJson );
        JWSSigner signer = new MACSigner( sharedKey.getBytes() );
        JWTClaimsSet claimsSet = JWTClaimsSet.parse( claimJson );

        SignedJWT signedJWT = new SignedJWT( header, claimsSet );
        signedJWT.sign( signer );

        return signedJWT.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating token", e.getMessage() );

        return "";
    }
}
 
Example #18
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
    try
    {
        JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );

        Payload pl = new Payload( claimJson );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );

        jwsObject.sign( signer );

        return jwsObject.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating RSA token", e.getMessage() );

        return "";
    }
}
 
Example #19
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static boolean verifyTokenRSA( PublicKey pKey, String token )
{
    try
    {
        Payload pl = new Payload( token );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );
        JWSVerifier verifier = new RSASSAVerifier( ( RSAPublicKey ) pKey );

        return jwsObject.verify( verifier );
    }
    catch ( JOSEException e )
    {
        LOG.warn( "Error verifying RSA token", e.getMessage() );

        return false;
    }
}
 
Example #20
Source File: JwtAuthorizerTest.java    From outbackcdx with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    RSAKey rsaJWK = new RSAKeyGenerator(2048).generate();
    RSAKey rsaPublicJWK = rsaJWK.toPublicJWK();
    JWSSigner signer = new RSASSASigner(rsaJWK);
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
            .claim("permissions", Arrays.asList(RULES_EDIT.toString(), INDEX_EDIT.toString()))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(),
            claimsSet);
    signedJWT.sign(signer);
    String token = signedJWT.serialize();

    JwtAuthorizer authorizer = new JwtAuthorizer(new ImmutableJWKSet<>(new JWKSet(rsaPublicJWK)), "permissions");
    Set<Permission> permissions = authorizer.verify("beARer " + token).permissions;
    assertEquals(EnumSet.of(RULES_EDIT, INDEX_EDIT), permissions);
}
 
Example #21
Source File: UserRepository.java    From shiro-jwt with MIT License 6 votes vote down vote up
default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(new Date().getTime() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());

        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

        Payload payload = new Payload(claimsSet.toJSONObject());

        JWSObject jwsObject = new JWSObject(header, payload);

        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
 
Example #22
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void validToken() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertTrue("Must be valid", signed.verify(verifier));
}
 
Example #23
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #24
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #25
Source File: AbstractJWTFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
protected SignedJWT getJWT(String issuer, String sub, String aud, Date expires, Date nbf, RSAPrivateKey privateKey,
                           String signatureAlgorithm)
    throws Exception {
  List<String> audiences = new ArrayList<>();
  if (aud != null) {
    audiences.add(aud);
  }

  JWTClaimsSet claims = new JWTClaimsSet.Builder()
  .issuer(issuer)
  .subject(sub)
  .audience(aud)
  .expirationTime(expires)
  .notBeforeTime(nbf)
  .claim("scope", "openid")
  .build();

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.parse(signatureAlgorithm)).build();

  SignedJWT signedJWT = new SignedJWT(header, claims);
  JWSSigner signer = new RSASSASigner(privateKey);

  signedJWT.sign(signer);

  return signedJWT;
}
 
Example #26
Source File: JWTToken.java    From knox with Apache License 2.0 6 votes vote down vote up
public JWTToken(String alg, String[] claimsArray, List<String> audiences) {
  JWSHeader header = new JWSHeader(new JWSAlgorithm(alg));

  if (claimsArray[2] != null) {
    if (audiences == null) {
      audiences = new ArrayList<>();
    }
    audiences.add(claimsArray[2]);
  }
  JWTClaimsSet claims;
  JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder()
  .issuer(claimsArray[0])
  .subject(claimsArray[1])
  .audience(audiences);
  if(claimsArray[3] != null) {
    builder = builder.expirationTime(new Date(Long.parseLong(claimsArray[3])));
  }

  // Add a private UUID claim for uniqueness
  builder.claim(KNOX_ID_CLAIM, String.valueOf(UUID.randomUUID()));

  claims = builder.build();

  jwt = new SignedJWT(header, claims);
}
 
Example #27
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #28
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #29
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #30
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public String asToken(final String claims) throws Exception {
    try {
        final JWSHeader header = new JWSHeader.Builder(new JWSAlgorithm("RS"+hashSize, Requirement.OPTIONAL))
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(privateKey));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}