com.nimbusds.jwt.SignedJWT Java Examples
The following examples show how to use
com.nimbusds.jwt.SignedJWT.
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 |
@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 |
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: JWTTokenGenerator.java From carbon-identity with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: KnoxService.java From nifi with Apache License 2.0 | 6 votes |
/** * Validate the jwt signature. * * @param jwtToken knox jwt * @return whether this jwt signature is valid * @throws JOSEException if the jws object couldn't be verified */ private boolean validateSignature(final SignedJWT jwtToken) throws JOSEException { boolean valid = false; // ensure the token is signed if (JWSObject.State.SIGNED.equals(jwtToken.getState())) { // ensure the signature is present if (jwtToken.getSignature() != null) { // verify the token valid = jwtToken.verify(verifier); } } if (!valid) { logger.error("The Knox JWT has an invalid signature."); } return valid; }
Example #5
Source File: KnoxService.java From nifi with Apache License 2.0 | 6 votes |
/** * Validate the jwt expiration. * * @param jwtToken knox jwt * @return whether this jwt is not expired * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set */ private boolean validateExpiration(final SignedJWT jwtToken) throws ParseException { boolean valid = false; final JWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet(); if (claimsSet == null) { logger.error("Claims set is missing from Knox JWT."); return false; } final Date now = new Date(); final Date expiration = claimsSet.getExpirationTime(); // the token is not expired if the expiration isn't present or the expiration is after now if (expiration == null || now.before(expiration)) { valid = true; } if (!valid) { logger.error("The Knox JWT is expired."); } return valid; }
Example #6
Source File: KnoxJwtRealm.java From zeppelin with Apache License 2.0 | 6 votes |
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken * the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("SSO token expiration date has been " + "successfully validated"); } valid = true; } else { LOGGER.warn("SSO expiration date validation failed."); } } catch (ParseException pe) { LOGGER.warn("SSO expiration date validation failed.", pe); } return valid; }
Example #7
Source File: JWSServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@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 #8
Source File: JWTUtil.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: JWSServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@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: DefaultJwtSigningAndValidationService.java From MaxKey with Apache License 2.0 | 6 votes |
/** * Sign a jwt in place using the configured default signer. */ @Override public void signJwt(SignedJWT jwt) { if (getDefaultSignerKeyId() == null) { throw new IllegalStateException("Tried to call default signing with no default signer ID set"); } JWSSigner signer = signers.get(getDefaultSignerKeyId()); try { jwt.sign(signer); } catch (JOSEException e) { logger.error("Failed to sign JWT, error was: ", e); } }
Example #11
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@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 #12
Source File: JWTAuthenticationHandler.java From registry with Apache License 2.0 | 6 votes |
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { LOG.debug("JWT token expiration date has been " + "successfully validated"); valid = true; } else { LOG.warn("JWT expiration date validation failed."); } } catch (ParseException pe) { LOG.warn("JWT expiration date validation failed.", pe); } return valid; }
Example #13
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@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 #14
Source File: RangerSSOAuthenticationFilter.java From ranger with Apache License 2.0 | 6 votes |
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken * the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { if (LOG.isDebugEnabled()) { LOG.debug("SSO token expiration date has been " + "successfully validated"); } valid = true; } else { LOG.warn("SSO expiration date validation failed."); } } catch (ParseException pe) { LOG.warn("SSO expiration date validation failed.", pe); } return valid; }
Example #15
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@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 #16
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@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 #17
Source File: AbstractGrantTypeHandler.java From tutorials with MIT License | 6 votes |
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception { //4. Signing JWSSigner jwsSigner = getJwsSigner(); Instant now = Instant.now(); //Long expiresInMin = 30L; Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); //3. JWT Payload or claims JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() .issuer("http://localhost:9080") .subject(subject) .claim("upn", subject) .claim("client_id", clientId) .audience("http://localhost:9280") .claim("scope", approvedScope) .claim("groups", Arrays.asList(approvedScope.split(" "))) .expirationTime(expirationTime) // expires in 30 minutes .notBeforeTime(Date.from(now)) .issueTime(Date.from(now)) .jwtID(UUID.randomUUID().toString()) .build(); SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); signedJWT.sign(jwsSigner); return signedJWT.serialize(); }
Example #18
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@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 #19
Source File: FirebaseJwtTokenDecoder.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Override public Jwt decode(String token) throws JwtException { SignedJWT jwt = parse(token); if (isExpired()) { try { keysLock.tryLock(); refresh(); } finally { keysLock.unlock(); } } JwtDecoder decoder = delegates.get(jwt.getHeader().getKeyID()); if (decoder == null) { throw new JwtException("No certificate found for key: " + jwt.getHeader().getKeyID()); } return decoder.decode(token); }
Example #20
Source File: Tokens.java From tomee with Apache License 2.0 | 6 votes |
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 #21
Source File: JWTValidationServiceImpl.java From carbon-apimgt with Apache License 2.0 | 6 votes |
@Override public JWTValidationInfo validateJWTToken(SignedJWT signedJWT) throws APIManagementException { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); try { String issuer = signedJWT.getJWTClaimsSet().getIssuer(); if (StringUtils.isNotEmpty(issuer)) { KeyManagerDto keyManagerDto = KeyManagerHolder.getKeyManagerByIssuer(tenantDomain, issuer); if (keyManagerDto != null && keyManagerDto.getJwtValidator() != null) { JWTValidationInfo validationInfo = keyManagerDto.getJwtValidator().validateToken(signedJWT); validationInfo.setKeyManager(keyManagerDto.getName()); return validationInfo; } } jwtValidationInfo.setValid(false); jwtValidationInfo.setValidationCode(APIConstants.KeyValidationStatus.API_AUTH_GENERAL_ERROR); return jwtValidationInfo; } catch (ParseException e) { log.error("Error while parsing JWT Token", e); jwtValidationInfo.setValid(false); jwtValidationInfo.setValidationCode(APIConstants.KeyValidationStatus.API_AUTH_GENERAL_ERROR); return jwtValidationInfo; } }
Example #22
Source File: SecurityUtils.java From para with Apache License 2.0 | 6 votes |
/** * 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 #23
Source File: AtlasKnoxSSOAuthenticationFilter.java From atlas with Apache License 2.0 | 6 votes |
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { if (LOG.isDebugEnabled()) { LOG.debug("SSO token expiration date has been successfully validated"); } valid = true; } else { LOG.warn("SSO expiration date validation failed."); } } catch (ParseException pe) { LOG.warn("SSO expiration date validation failed.", pe); } return valid; }
Example #24
Source File: AtlasKnoxSSOAuthenticationFilter.java From incubator-atlas with Apache License 2.0 | 6 votes |
/** * Validate that the expiration time of the JWT token has not been violated. * If it has then throw an AuthenticationException. Override this method in * subclasses in order to customize the expiration validation behavior. * * @param jwtToken the token that contains the expiration date to validate * @return valid true if the token has not expired; false otherwise */ protected boolean validateExpiration(SignedJWT jwtToken) { boolean valid = false; try { Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); if (expires == null || new Date().before(expires)) { if (LOG.isDebugEnabled()) { LOG.debug("SSO token expiration date has been successfully validated"); } valid = true; } else { LOG.warn("SSO expiration date validation failed."); } } catch (ParseException pe) { LOG.warn("SSO expiration date validation failed.", pe); } return valid; }
Example #25
Source File: JwtLoginServiceTest.java From cruise-control with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void testRevalidateTokenPasses() throws Exception { UserStore testUserStore = new UserStore(); testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"}); TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER); JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null); SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token()); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token()); replay(request); UserIdentity identity = loginService.login(TEST_USER, jwtToken, request); verify(request); assertNotNull(identity); assertEquals(TEST_USER, identity.getUserPrincipal().getName()); assertTrue(loginService.validate(identity)); }
Example #26
Source File: OAuthHandler.java From attic-stratos with Apache License 2.0 | 6 votes |
private String extractAppIdFromIdToken(String token) { String appId = null; KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); try { keyStoreManager.getDefaultPrimaryCertificate(); JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey()); SignedJWT jwsObject = SignedJWT.parse(token); if (jwsObject.verify(verifier)) { appId = jwsObject.getJWTClaimsSet().getStringClaim("appId"); } } catch (Exception e) { String message = "Could not extract application id from id token"; log.error(message, e); } return appId; }
Example #27
Source File: JwtTokenGenerator.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static String generateJWTString(String jsonResource) throws Exception { byte[] byteBuffer = new byte[16384]; currentThread().getContextClassLoader() .getResource(jsonResource) .openStream() .read(byteBuffer); JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE); JSONObject jwtJson = (JSONObject) parser.parse(byteBuffer); long currentTimeInSecs = (System.currentTimeMillis() / 1000); long expirationTime = currentTimeInSecs + 1000; jwtJson.put(Claims.iat.name(), currentTimeInSecs); jwtJson.put(Claims.auth_time.name(), currentTimeInSecs); jwtJson.put(Claims.exp.name(), expirationTime); SignedJWT signedJWT = new SignedJWT(new JWSHeader .Builder(RS256) .keyID("/privateKey.pem") .type(JWT) .build(), parse(jwtJson)); signedJWT.sign(new RSASSASigner(readPrivateKey("privateKey.pem"))); return signedJWT.serialize(); }
Example #28
Source File: JWTTokenGenerator.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * Populate JWT Token with defined claim set * * @param jwtTokenDTO token info object * @param rsaJWK RSAKey * @return Signable JWT object */ private SignedJWT populateSignedJWTToken(JWTTokenInfoDTO jwtTokenDTO, RSAKey rsaJWK) { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject(jwtTokenDTO.getUsername()) .issuer(jwtTokenDTO.getIssuer()) .expirationTime(new Date(jwtTokenDTO.getExpiry())) .build(); //Add additional claims if needed return new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(), claimsSet); }
Example #29
Source File: SimpleTokenManager.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
@Override public Cookie createSecureTokenCookie(SignedJWT token) { Cookie cookie = new Cookie(TOKEN_NAME, token.serialize()); cookie.setSecure(true); cookie.setPath("/"); cookie.setMaxAge((int) (tokenDuration / 1000)); return cookie; }
Example #30
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void signedTokenTests() 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()); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(mockRestOperations(), "https://spring.local", validator); decoder.decode(signedJWT.serialize()); }