com.nimbusds.jose.JOSEException Java Examples

The following examples show how to use com.nimbusds.jose.JOSEException. 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: ScooldUtils.java    From scoold with Apache License 2.0 7 votes vote down vote up
public boolean isValidJWToken(String jwt) {
	try {
		String secret = Config.getConfigParam("app_secret_key", "");
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			SignedJWT sjwt = SignedJWT.parse(jwt);
			if (sjwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = sjwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				String jti = claims.getJWTID();
				boolean expired = expirationTime != null && expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);
				boolean jtiRevoked = isApiKeyRevoked(jti, expired);
				return !(expired || notYetValid || jtiRevoked);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
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: 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 #4
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 #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: 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 #7
Source File: SecurityUtils.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Validates a JWT token.
 * @param secret secret used for generating the token
 * @param jwt token to validate
 * @return true if token is valid
 */
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
	try {
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			if (jwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = jwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				boolean expired = expirationTime == null || expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);

				return !(expired || notYetValid);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
Example #8
Source File: DefaultJwtEncryptionAndDecryptionService.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void decryptJwt(JWEObject jwt) {
	if (getDefaultDecryptionKeyId() == null) {
		throw new IllegalStateException("Tried to call default decryption with no default decrypter ID set");
	}

	JWEDecrypter decrypter = decrypters.get(getDefaultDecryptionKeyId());

	try {
		jwt.decrypt(decrypter);
	} catch (JOSEException e) {

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

}
 
Example #9
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 #10
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 #11
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private JWSVerifier from(ECKey ecKey) {
    try {
        Curve curve = Curve.parse(ecKey.getCrv());
        if(curve.getStdName()==null) {
            throw new IllegalArgumentException("Unknown EC Curve: "+ecKey.getCrv());
        }
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec(curve.getStdName()));
        ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);

        byte[] x = Base64.getUrlDecoder().decode(ecKey.getX());
        byte[] y = Base64.getUrlDecoder().decode(ecKey.getY());
        ECPoint ecPoint = new ECPoint(new BigInteger(1,x), new BigInteger(1,y));

        ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameters);
        ECPublicKey ecPublicKey = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(ecPublicKeySpec);
        return new ECDSAVerifier(ecPublicKey);
    }
    catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException | JOSEException ex) {
        LOGGER.error("Unable to build Verifier from Elliptic Curve (EC) key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}
 
Example #12
Source File: JWTSecurityInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private boolean verifySignature(String jwt) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwt);
        if (new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) {
            JWSVerifier verifier =
                    new RSASSAVerifier((RSAPublicKey) getPublicKey(KEYSTORE, KEYSTORE_PASSWORD, ALIAS));
            return signedJWT.verify(verifier);
        } else {
            log.info("Token has expired");
        }
    } catch (ParseException | IOException | KeyStoreException | CertificateException |
            NoSuchAlgorithmException | UnrecoverableKeyException | JOSEException e) {
        log.error("Error occurred while JWT signature verification. JWT=" + jwt, e);
    }
    return false;
}
 
Example #13
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 #14
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 #15
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testRsaJwt_withClientJwks() throws NoSuchAlgorithmException, JOSEException{
    KeyPair rsaKey = generateRsaKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) rsaKey.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) rsaKey.getPrivate();

    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()));

    Client client = generateClient(key);
    client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
    String assertion = generateJWT(privateKey);
    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client));
    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);
    when(jwkService.getKey(any(),any())).thenReturn(Maybe.just(key));
    when(jwsService.isValidSignature(any(),any())).thenReturn(true);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertNoErrors();
    testObserver.assertValue(client);
}
 
Example #16
Source File: AbstractVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {JOSEException.class, AlgorithmMismatchException.class, InvalidJwtException.class, UnsupportedJwtException.class},
    description = "Illustrate validation of signature algorithm")
public void testFailSignatureAlgorithm() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.ALG);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
Example #17
Source File: JWEEllipticCurveTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encryptUserinfo() {
    try {
        //prepare encryption private & public key
        com.nimbusds.jose.jwk.ECKey jwk = new ECKeyGenerator(this.crv).generate();

        ECKey key = new ECKey();
        key.setKid("ecEnc");
        key.setUse("enc");
        key.setCrv(jwk.getCurve().getName());
        key.setX(jwk.getX().toString());
        key.setY(jwk.getY().toString());

        Client client = new Client();
        client.setUserinfoEncryptedResponseAlg(alg);
        client.setUserinfoEncryptedResponseEnc(enc);

        when(jwkService.getKeys(client)).thenReturn(Maybe.just(new JWKSet()));
        when(jwkService.filter(any(), any())).thenReturn(Maybe.just(key));

        TestObserver testObserver = jweService.encryptUserinfo("JWT", client).test();
        testObserver.assertNoErrors();
        testObserver.assertComplete();
        testObserver.assertValue(jweString -> {
            JWEObject jwe = JWEObject.parse((String) jweString);
            jwe.decrypt(new ECDHDecrypter(jwk));
            return "JWT".equals(jwe.getPayload().toString());
        });
    }
    catch (JOSEException e) {
        fail(e.getMessage());
    }
}
 
Example #18
Source File: JWEEllipticCurveTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encryptIdToken() {
    try {
        //prepare encryption private & public key
        com.nimbusds.jose.jwk.ECKey jwk = new ECKeyGenerator(this.crv).generate();

        ECKey key = new ECKey();
        key.setKid("ecEnc");
        key.setUse("enc");
        key.setCrv(jwk.getCurve().getName());
        key.setX(jwk.getX().toString());
        key.setY(jwk.getY().toString());

        Client client = new Client();
        client.setIdTokenEncryptedResponseAlg(alg);
        client.setIdTokenEncryptedResponseEnc(enc);

        when(jwkService.getKeys(client)).thenReturn(Maybe.just(new JWKSet()));
        when(jwkService.filter(any(), any())).thenReturn(Maybe.just(key));

        TestObserver testObserver = jweService.encryptIdToken("JWT", client).test();
        testObserver.assertNoErrors();
        testObserver.assertComplete();
        testObserver.assertValue(jweString -> {
            JWEObject jwe = JWEObject.parse((String) jweString);
            jwe.decrypt(new ECDHDecrypter(jwk));
            return "JWT".equals(jwe.getPayload().toString());
        });
    }
    catch (JOSEException e) {
        fail(e.getMessage());
    }
}
 
Example #19
Source File: OAuth2GenericAuthenticationProviderTest_idToken.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadUserByUsername_authentication_badToken() throws ParseException, JOSEException, BadJOSEException {
    when(jwtProcessor.process("test", null)).thenThrow(new JOSEException("jose exception"));

    when(configuration.getResponseType()).thenReturn(ResponseType.ID_TOKEN);
    TestObserver<User> testObserver = authenticationProvider.loadUserByUsername(new Authentication() {
        @Override
        public Object getCredentials() {
            return "__social__";
        }

        @Override
        public Object getPrincipal() {
            return "__social__";
        }

        @Override
        public AuthenticationContext getContext() {
            DummyRequest dummyRequest = new DummyRequest();
            dummyRequest.setParameters(Collections.singletonMap("urlHash", Collections.singletonList("#id_token=test")));
            return new DummyAuthenticationContext(Collections.singletonMap("id_token", "test"), dummyRequest);
        }
    }).test();

    testObserver.awaitTerminalEvent();
    testObserver.assertError(BadCredentialsException.class);
}
 
Example #20
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidSignature(JWT jwt, JWK jwk) {
    try {
        SignedJWT signedJwt = (SignedJWT)jwt;
        return signedJwt.verify(this.verifier(jwk));
    } catch (ClassCastException | JOSEException ex) {
        LOGGER.error(ex.getMessage(),ex);
        return false;
    }
}
 
Example #21
Source File: OAuth2GenericAuthenticationProviderTest_idToken.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadUserByUsername_authentication() throws ParseException, JOSEException, BadJOSEException {
    JWTClaimsSet claims = new JWTClaimsSet.Builder().subject("bob").build();

    when(configuration.getResponseType()).thenReturn(ResponseType.ID_TOKEN);
    when(jwtProcessor.process("test", null)).thenReturn(claims);

    TestObserver<User> testObserver = authenticationProvider.loadUserByUsername(new Authentication() {
        @Override
        public Object getCredentials() {
            return "__social__";
        }

        @Override
        public Object getPrincipal() {
            return "__social__";
        }

        @Override
        public AuthenticationContext getContext() {
            DummyRequest dummyRequest = new DummyRequest();
            dummyRequest.setParameters(Collections.singletonMap("urlHash", Collections.singletonList("#id_token=test")));
            return new DummyAuthenticationContext(Collections.singletonMap("id_token", "test"), dummyRequest);
        }
    }).test();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(u -> "bob".equals(u.getUsername()));
}
 
Example #22
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testRsaJwt_withClientJwksUri() throws NoSuchAlgorithmException, JOSEException{
    KeyPair rsaKey = generateRsaKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) rsaKey.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) rsaKey.getPrivate();

    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()));
    JWKSet jwkSet = new JWKSet();
    jwkSet.setKeys(Arrays.asList(key));

    Client client = new Client();
    client.setClientId(CLIENT_ID);
    client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
    client.setJwksUri("http://fake/jwk/uri");
    String assertion = generateJWT(privateKey);
    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client));
    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);
    when(jwkService.getKeys(anyString())).thenReturn(Maybe.just(jwkSet));
    when(jwkService.getKey(any(),any())).thenReturn(Maybe.just(key));
    when(jwsService.isValidSignature(any(),any())).thenReturn(true);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertNoErrors();
    testObserver.assertValue(client);
}
 
Example #23
Source File: TokenUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignatureAndDate( String token, String sharedKey ) throws SystemSecurityException
{
    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );

        if ( jwsObject.verify( verifier ) )
        {
            long date = getDate( jwsObject );

            if ( date == 0 || System.currentTimeMillis() <= date )
            {
                return true;
            }
            else
            {
                throw new IdentityExpiredException();
            }
        }
        else
        {
            throw new InvalidLoginException();
        }
    }
    catch ( JOSEException | ParseException ex )
    {
        LOG.warn( ex.getMessage() );

        throw new InvalidLoginException();
    }
}
 
Example #24
Source File: JWTTokenGenerator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Generate JWT Token with JWTTokenInfo object
 *
 * @param jwtToken JWT Token info object
 * @return Serialized JWT token
 * @throws JOSEException
 * @throws NoSuchAlgorithmException
 */
public String generateJWTToken(JWTTokenInfoDTO jwtToken) throws JOSEException, NoSuchAlgorithmException {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(AuthConstants.TOKEN_STORE_KEY_ALGORITHM);
    keyPairGenerator.initialize(Integer.parseInt(JWTConfig.getInstance().getJwtConfigDto().getTokenSize()));
    RSAKey rsaJWK = generateRSAKey(jwtToken, keyPairGenerator); //Currently uses generated key pair

    SignedJWT signedJWT = populateSignedJWTToken(jwtToken, rsaJWK);

    JWSSigner signer = new RSASSASigner(rsaJWK);
    signedJWT.sign(signer);

    return signedJWT.serialize();
}
 
Example #25
Source File: JWTToken.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(JWSVerifier verifier) {
  boolean rc = false;

  try {
    rc = jwt.verify(verifier);
  } catch (JOSEException e) {
    log.unableToVerifyToken(e);
  }

  return rc;
}
 
Example #26
Source File: TokenHelperImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public TokenHelperImpl( String issuer, String subject, Date issueTime, Date expireTime, String secret )
        throws TokenCreateException
{
    try
    {
        this.token = generate( issuer, subject, issueTime, expireTime, secret );
    }
    catch ( JOSEException e )
    {
        throw new TokenCreateException( e.getMessage() );
    }
}
 
Example #27
Source File: SimpleTokenManagerTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void generateAuthTokenExceptionTest() throws Exception {
    // Setup:
    when(mobiTokenVerifier.generateToken(anyString(), anyString(), anyString(), anyLong(), any(Map.class))).thenThrow(new JOSEException(""));
    thrown.expect(MobiException.class);

    SignedJWT result = manager.generateAuthToken("username");
    assertEquals(jwt, result);
    verify(mobiTokenVerifier).generateToken("username", SimpleTokenManager.ISSUER, SimpleTokenManager.AUTH_SCOPE, 86400000, null);
}
 
Example #28
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testHmacJwt_invalidClientAuthMethod() throws NoSuchAlgorithmException, JOSEException {
    // Generate random 256-bit (32-byte) shared secret
    SecureRandom random = new SecureRandom();
    byte[] sharedSecret = new byte[32];
    random.nextBytes(sharedSecret);

    String clientSecret = new String(sharedSecret, StandardCharsets.UTF_8);

    JWSSigner signer = new MACSigner(clientSecret);

    Client client = new Client();
    client.setClientId(CLIENT_ID);
    client.setClientSecret(new String(sharedSecret));
    client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
    String assertion = generateJWT(signer);
    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client));
    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertError(InvalidClientException.class);
    testObserver.assertNotComplete();
}
 
Example #29
Source File: AuthUtils.java    From blog with MIT License 5 votes vote down vote up
public static Token createToken(String host, long sub) throws JOSEException {
  JWTClaimsSet claim = new JWTClaimsSet();
  claim.setSubject(Long.toString(sub));
  claim.setIssuer(host);
  claim.setIssueTime(DateTime.now().toDate());
  claim.setExpirationTime(DateTime.now().plusDays(14).toDate());

  JWSSigner signer = new MACSigner(TOKEN_SECRET);
  SignedJWT jwt = new SignedJWT(JWT_HEADER, claim);
  jwt.sign(signer);

  return new Token(jwt.serialize());
}
 
Example #30
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private JWSVerifier from(OCTKey octKey) {
    try {
        OctetSequenceKey jwk = new OctetSequenceKey.Builder(new Base64URL(octKey.getK())).build();
        return new MACVerifier(jwk);
    }
    catch (JOSEException ex) {
        LOGGER.error("Unable to build Verifier from Edwards Curve (OKP) key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}