Java Code Examples for com.nimbusds.jwt.SignedJWT#sign()
The following examples show how to use
com.nimbusds.jwt.SignedJWT#sign() .
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 |
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 2
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 3
Source File: JSONWebTokenManager.java From authmore-framework with Apache License 2.0 | 6 votes |
@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 4
Source File: JwtAuthorizerTest.java From outbackcdx with Apache License 2.0 | 6 votes |
@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 5
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 6
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void override_redirect_uri() throws Exception { RSAKey rsaKey = getRSAKey(); JWSSigner signer = new RSASSASigner(rsaKey); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("alice") .issuer("https://c2id.com") .claim("redirect_uri", "https://op-test:60001/authz_cb") .expirationTime(new Date(new Date().getTime() + 60 * 1000)) .build(); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(), claimsSet); signedJWT.sign(signer); String jwt = signedJWT.serialize(); System.out.println(jwt); }
Example 7
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 8
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void invalid_do_not_override_state_and_nonce() throws Exception { RSAKey rsaKey = getRSAKey(); JWSSigner signer = new RSASSASigner(rsaKey); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("alice") .issuer("https://c2id.com") .claim("state", "override-state") .claim("nonce", "override-nonce") .expirationTime(new Date(new Date().getTime() + 60 * 1000)) .build(); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(), claimsSet); signedJWT.sign(signer); String jwt = signedJWT.serialize(); System.out.println(jwt); }
Example 9
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void invalid_client() throws Exception { RSAKey rsaKey = getRSAKey(); JWSSigner signer = new RSASSASigner(rsaKey); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("alice") .issuer("https://c2id.com") .claim("client_id", "unknown_client") .expirationTime(new Date(new Date().getTime() + 60 * 1000)) .build(); System.out.println(new PlainJWT(claimsSet).serialize()); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(), claimsSet); signedJWT.sign(signer); String jwt = signedJWT.serialize(); System.out.println(jwt); }
Example 10
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void invalid_request_object() throws Exception { RSAKey rsaKey = getRSAKey(); JWSSigner signer = new RSASSASigner(rsaKey); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("alice") .issuer("https://c2id.com") .expirationTime(new Date(new Date().getTime() + 60 * 1000)) .build(); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(), claimsSet); signedJWT.sign(signer); String jwt = signedJWT.serialize(); System.out.println(jwt); }
Example 11
Source File: TokenUtils.java From tomee with Apache License 2.0 | 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 12
Source File: AbstractGrantTypeHandler.java From tutorials with MIT License | 5 votes |
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception { JWSSigner jwsSigner = getJwsSigner(); Instant now = Instant.now(); //6.Build refresh token JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder() .subject(subject) .claim("client_id", clientId) .claim("scope", approvedScope) //refresh token for 1 day. .expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS))) .build(); SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims); signedRefreshToken.sign(jwsSigner); return signedRefreshToken.serialize(); }
Example 13
Source File: TokenHelperImpl.java From peer-os with Apache License 2.0 | 5 votes |
protected String generate( final String issuer, final String subject, final Date issueTime, final Date expireTime, final String secret ) throws JOSEException { JWSHeader jwtHeader = new JWSHeader( JWSAlgorithm.HS256 ); JWTClaimsSet claimset = new JWTClaimsSet.Builder().expirationTime( expireTime ).issuer( issuer ).issueTime( issueTime ) .subject( subject ).build(); SignedJWT jwt = new SignedJWT( jwtHeader, claimset ); JWSSigner signer = new MACSigner( secret ); jwt.sign( signer ); return jwt.serialize(); }
Example 14
Source File: DCOSAuthCredentials.java From marathon-client with Apache License 2.0 | 5 votes |
private static String signJWT(String uid, PrivateKey privateKey) { final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); final JWTClaimsSet payload = new JWTClaimsSet.Builder().claim("uid", uid).build(); final SignedJWT signedJWT = new SignedJWT(header, payload); try { signedJWT.sign(new RSASSASigner(privateKey)); return signedJWT.serialize(); } catch (JOSEException e) { throw new RuntimeException(e); } }
Example 15
Source File: JWSServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void testValidSignature_EC() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JOSEException { //Generate EC key KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec gps = new ECGenParameterSpec (Curve.P_521.getStdName()); kpg.initialize(gps); KeyPair ecKey = kpg.generateKeyPair(); ECPublicKey ecPublicKey = (ECPublicKey)ecKey.getPublic(); ECKey key = new ECKey(); key.setKty("EC"); key.setKid(KID); key.setCrv(Curve.P_521.getName()); key.setX(Base64.getUrlEncoder().encodeToString(ecPublicKey.getW().getAffineX().toByteArray())); key.setY(Base64.getUrlEncoder().encodeToString(ecPublicKey.getW().getAffineY().toByteArray())); //Sign JWT with Elliptic Curve algorithm SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.ES512).keyID(KID).build(), new JWTClaimsSet.Builder() .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ); signedJWT.sign(new ECDSASigner((ECPrivateKey) ecKey.getPrivate())); assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key)); }
Example 16
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 17
Source File: MobiTokenVerifier.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
/** * Creates a JWT Token String for the user with the provided username using the Mobi token key and the provided * issuer, scope, tokenDuration, and additional claims. * * @param username The sub of the token * @param issuer The issuer of the token * @param scope The scope of the token * @param tokenDuration The duration for the new token * @param claims An optional map of custom claims to add to the token * @return The String representing the encoded and compact JWT Token * @throws JOSEException if there is a problem creating the token */ SignedJWT generateToken(String username, String issuer, String scope, long tokenDuration, @Nullable Map<String, Object> claims) throws JOSEException { // Create HMAC signer JWSSigner signer = new MACSigner(padKey(KEY)); Date now = new Date(); Date expirationDate = new Date(now.getTime() + tokenDuration); // Prepare JWT Builder with claims set JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder() .subject(username) .issuer(issuer) .expirationTime(expirationDate) .claim("scope", scope); if (claims != null) { claims.forEach(builder::claim); } SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), builder.build()); // Apply the HMAC protection signedJWT.sign(signer); return signedJWT; }
Example 18
Source File: SecurityUtils.java From para with Apache License 2.0 | 5 votes |
/** * Generates a new JWT token. * @param user a User object belonging to the app * @param app the app object * @return a new JWT or null */ public static SignedJWT generateJWToken(User user, App app) { if (app != null) { try { Date now = new Date(); JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder(); String userSecret = ""; claimsSet.issueTime(now); claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000))); claimsSet.notBeforeTime(now); claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec())); claimsSet.claim(Config._APPID, app.getId()); if (user != null) { claimsSet.subject(user.getId()); claimsSet.claim("idp", user.getIdentityProvider()); userSecret = user.getTokenSecret(); } JWSSigner signer = new MACSigner(app.getSecret() + userSecret); 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()); } } return null; }
Example 19
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private String generateJWT(JWSSigner jwsSigner) throws JOSEException { SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.HS256).keyID(KID).build(), new JWTClaimsSet.Builder() .issuer(ISSUER) .subject(CLIENT_ID) .audience(AUDIENCE) .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ); signedJWT.sign(jwsSigner); return signedJWT.serialize(); }
Example 20
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 4 votes |
@Test public void testRsaJwt_withoutKid() 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); OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class); String basePath="/"; SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).build(), new JWTClaimsSet.Builder() .issuer(ISSUER) .subject(CLIENT_ID) .audience(AUDIENCE) .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ); signedJWT.sign(new RSASSASigner(privateKey)); String assertion = signedJWT.serialize(); 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); }