com.nimbusds.jose.JWSAlgorithm Java Examples

The following examples show how to use com.nimbusds.jose.JWSAlgorithm. 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: BootstrapTests.java    From authmore-framework with Apache License 2.0 7 votes vote down vote up
@Test
public void testJSONWebTokenManager() throws ParseException, JOSEException, BadJOSEException {

    JSONWebTokenManager tokens = new JSONWebTokenManager(clients, keyPair);
    ClientDetails client = clients.findAll().get(0);
    String userId = "user_1";
    TokenResponse tokenResponse = tokens.create(client, userId, Collections.emptySet());
    String accessToken;
    assertNotNull(tokenResponse);
    assertNotNull(accessToken = tokenResponse.getAccess_token());
    ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
    JWKSource<SecurityContext> keySource = new ImmutableJWKSet<>(jwkSet);
    JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
    JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(expectedJWSAlg, keySource);
    jwtProcessor.setJWSKeySelector(keySelector);
    JWTClaimsSet claimsSet = jwtProcessor.process(accessToken, null);
    assertEquals(userId, claimsSet.getClaim(OAuthProperties.TOKEN_USER_ID));
}
 
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: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void expiredTokenTests() 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().minusSeconds(3600)))
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	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: Jwt expired at");
}
 
Example #4
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 #5
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 #6
Source File: KnoxServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test(expected = InvalidAuthenticationException.class)
public void testExpiredJwt() throws Exception {
    final String subject = "user-1";

    // token expires in 1 sec
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS));

    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair = keyGen.generateKeyPair();
    final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
    final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();

    // wait 2 sec
    Thread.sleep(TimeUnit.MILLISECONDS.convert(2, TimeUnit.SECONDS));

    final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
    final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);

    final KnoxConfiguration configuration = getConfiguration(publicKey);
    final KnoxService service = new KnoxService(configuration);

    service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize());
}
 
Example #7
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void validTokenTests() 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().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);
	Jwt jwt = decoder.decode(signedJWT.serialize());
	assertThat(jwt.getClaims()).isNotEmpty();
}
 
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: 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 #10
Source File: DefaultTokenAuthorityService.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verifyToken(JWT token, String jwksurl, String algorithm) throws TokenServiceException {
  boolean verified = false;
  try {
    if (algorithm != null && jwksurl != null) {
      JWSAlgorithm expectedJWSAlg = JWSAlgorithm.parse(algorithm);
      JWKSource<SecurityContext> keySource = new RemoteJWKSet<>(new URL(jwksurl));
      JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(expectedJWSAlg, keySource);

      // Create a JWT processor for the access tokens
      ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
      jwtProcessor.setJWSKeySelector(keySelector);
      JWTClaimsSetVerifier<SecurityContext> claimsVerifier = new DefaultJWTClaimsVerifier<>();
      jwtProcessor.setJWTClaimsSetVerifier(claimsVerifier);

      // Process the token
      SecurityContext ctx = null; // optional context parameter, not required here
      jwtProcessor.process(token.toString(), ctx);
      verified = true;
    }
  } catch (BadJOSEException | JOSEException | ParseException | MalformedURLException e) {
    throw new TokenServiceException("Cannot verify token.", e);
  }
  return verified;
}
 
Example #11
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 #12
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 #13
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * This method map signature algorithm define in identity.xml to nimbus
 * signature algorithm
 * format, Strings are defined inline hence there are not being used any
 * where
 *
 * @param signatureAlgorithm
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception {

    if (NONE.equals(signatureAlgorithm)) {
        return new JWSAlgorithm(JWSAlgorithm.NONE.getName());
    } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
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: 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 #17
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 #18
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 #19
Source File: JWTUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the JWT token signature.
 *
 * @param jwt SignedJwt Token
 * @param publicKey      public certificate
 * @return whether the signature is verified or or not
 */
public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) {

    JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
    if ((JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
            JWSAlgorithm.RS384.equals(algorithm))) {
        try {
            JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey);
            return jwt.verify(jwsVerifier);
        } catch (JOSEException e) {
            log.error("Error while verifying JWT signature", e);
            return false;
        }
    } else {
        log.error("Public key is not a RSA");
        return false;
    }
}
 
Example #20
Source File: DefaultJwtSigningAndValidationService.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void signJwt(SignedJWT jwt, JWSAlgorithm alg) {

	JWSSigner signer = null;

	for (JWSSigner s : signers.values()) {
		if (s.supportedJWSAlgorithms().contains(alg)) {
			signer = s;
			break;
		}
	}

	if (signer == null) {
		//If we can't find an algorithm that matches, we can't sign
		logger.error("No matching algirthm found for alg=" + alg);

	}

	try {
		jwt.sign(signer);
	} catch (JOSEException e) {

		logger.error("Failed to sign JWT, error was: ", e);
	}

}
 
Example #21
Source File: KnoxServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test(expected = InvalidAuthenticationException.class)
public void testBadSignedJwt() throws Exception {
    final String subject = "user-1";
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));

    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    final KeyPair pair1 = keyGen.generateKeyPair();
    final RSAPrivateKey privateKey1 = (RSAPrivateKey) pair1.getPrivate();

    final KeyPair pair2 = keyGen.generateKeyPair();
    final RSAPublicKey publicKey2 = (RSAPublicKey) pair2.getPublic();

    // sign the jwt with pair 1
    final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
    final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey1, null, null);

    // attempt to verify it with pair 2
    final KnoxConfiguration configuration = getConfiguration(publicKey2);
    final KnoxService service = new KnoxService(configuration);

    service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize());
}
 
Example #22
Source File: ClientCredentialsGrantHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm)
        throws IdentityOAuth2Exception {
    if ("SHA256withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if ("SHA384withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if ("SHA512withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if ("SHA256withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if ("SHA384withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if ("SHA512withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if ("SHA256withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if ("SHA384withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if ("SHA512withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    log.error("Unsupported Signature Algorithm in identity.xml");
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
Example #23
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param jwtClaimsSet contains JWT body
 * @param request
 * @return
 * @throws IdentityOAuth2Exception
 */
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example #24
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method map signature algorithm define in identity.xml to nimbus
 * signature algorithm
 * format, Strings are defined inline hence there are not being used any
 * where
 *
 * @param signatureAlgorithm
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception {

    if (NONE.equals(signatureAlgorithm)) {
        return new JWSAlgorithm(JWSAlgorithm.NONE.getName());
    } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
Example #25
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 #26
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param signedJWT
 * @param tenantDomain
 * @param tenantId
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWT signJWT(SignedJWT signedJWT, String tenantDomain, int tenantId)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(signedJWT, signatureAlgorithm, tenantDomain, tenantId);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(payLoad,jwsAlgorithm,tenantDomain,tenantId); implementation
        // need to be done
    } else if (JWSAlgorithm.ES256.equals(signatureAlgorithm) ||
            JWSAlgorithm.ES384.equals(signatureAlgorithm) ||
            JWSAlgorithm.ES512.equals(signatureAlgorithm)) {
        // return signWithEC(payLoad,jwsAlgorithm,tenantDomain,tenantId); implementation
        // need to be done
    }
    log.error("UnSupported Signature Algorithm");
    throw new IdentityOAuth2Exception("UnSupported Signature Algorithm");
}
 
Example #27
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 #28
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 #29
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 #30
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));
}