Java Code Examples for com.nimbusds.jwt.SignedJWT#serialize()

The following examples show how to use com.nimbusds.jwt.SignedJWT#serialize() . 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: 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 2
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 3
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 4
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createToken( String headerJson, String claimJson, String sharedKey )
{
    try
    {
        JWSHeader header = JWSHeader.parse( headerJson );
        JWSSigner signer = new MACSigner( sharedKey.getBytes() );
        JWTClaimsSet claimsSet = JWTClaimsSet.parse( claimJson );

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

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

        return "";
    }
}
 
Example 7
Source File: DefaultConsentReferencePolicy.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
private String signJWT(JWTClaimsSet claimsSet) {
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256).keyID(Ids.id()).build();
    SignedJWT signedJWT = new SignedJWT(header, claimsSet);
    try {
        signedJWT.sign(new MACSigner(hmacSecret));
    } catch (JOSEException e) {
        throw new IllegalStateException("Error signing user token", e);
    }
    return signedJWT.serialize();
}
 
Example 8
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private String generateJWT(RSAPrivateKey privateKey) throws JOSEException {
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).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(new RSASSASigner(privateKey));

    return signedJWT.serialize();
}
 
Example 9
Source File: TokenUtils.java    From tomee with Apache License 2.0 5 votes vote down vote up
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 10
Source File: TestJWTAuthenticationHandler.java    From registry with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnableToParseJWT() throws Exception {
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);

        KeyPair kp = kpg.genKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();

        handler.setPublicKey(publicKey);

        Properties props = getProperties();
        handler.init(props);

        SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() + 5000),
                privateKey);

        Cookie cookie = new Cookie("hadoop-jwt", "ljm" + jwt.serialize());
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        Mockito.when(request.getRequestURL()).thenReturn(
                new StringBuffer(SERVICE_URL));
        HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(
                SERVICE_URL);

        AuthenticationToken token = handler.authenticate(request,
                response);
        Mockito.verify(response).sendRedirect(REDIRECT_LOCATION);
    } catch (ServletException se) {
        fail("alternateAuthentication should NOT have thrown a ServletException");
    } catch (AuthenticationException ae) {
        fail("alternateAuthentication should NOT have thrown a AuthenticationException");
    }
}
 
Example 11
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 12
Source File: SSOCookieProviderTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
  Cookie cookie1 = new Cookie("hadoop-jwt", "garbage");
  Cookie cookie2 = new Cookie("hadoop-jwt", jwt.serialize());
  EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie1, cookie2 });

  if(ThreadLocalRandom.current().nextBoolean()) {
    LOGGER.info("Using XHR header for request");
    EasyMock.expect(request.getHeader(XHR_HEADER)).andReturn(XHR_VALUE).anyTimes();
  }
}
 
Example 13
Source File: JwtTokenGenerator.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 14
Source File: JWTGenerator.java    From msf4j with Apache License 2.0 5 votes vote down vote up
protected String generateJWT(User user) throws Exception {

        RSAPrivateKey privateKey = getPrivateKey(keyStore, keyStorePassword, alias);
        // Create RSA-signer with the private key
        JWSSigner signer = new RSASSASigner(privateKey);

        // Prepare JWT with claims set
        JWTClaimsSet claimsSet = new JWTClaimsSet();
        claimsSet.setSubject(user.getName());
        claimsSet.setClaim("email", user.getEmail());
        claimsSet.setClaim("roles", user.getRoles());
        claimsSet.setIssuer("wso2.org/products/msf4j");
        claimsSet.setExpirationTime(new Date(new Date().getTime() + 60 * 60 * 1000)); //60 min

        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);

        // Compute the RSA signature
        signedJWT.sign(signer);

        // To serialize to compact form, produces something like
        // eyJhbGciOiJSUzI1NiJ9.SW4gUlNBIHdlIHRydXN0IQ.IRMQENi4nJyp4er2L
        // mZq3ivwoAjqa1uUkSBKFIX7ATndFF5ivnt-m8uApHO4kfIFOrW7w2Ezmlg3Qd
        // maXlS9DhN0nUk_hGI3amEjkKd0BWYCB8vfUbUv0XGjQip78AI4z1PrFRNidm7
        // -jPDm5Iq0SZnjKjCNS5Q15fokXZc8u0A

        return signedJWT.serialize();
    }
 
Example 15
Source File: JwtTokenGenerator.java    From microprofile1.4-samples with MIT License 5 votes vote down vote up
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 16
Source File: TestJWTAuthenticationHandler.java    From registry with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidJWT() throws Exception {
    try {
        handler.setPublicKey(publicKey);

        Properties props = getProperties();
        handler.init(props);

        SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000),
                privateKey);

        Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        Mockito.when(request.getRequestURL()).thenReturn(
                new StringBuffer(SERVICE_URL));
        HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(
                SERVICE_URL);

        AuthenticationToken token = handler.authenticate(request,
                response);
        Assert.assertNotNull("Token should not be null.", token);
        Assert.assertEquals("alice", token.getUserName());
    } catch (ServletException se) {
        fail("alternateAuthentication should NOT have thrown a ServletException.");
    } catch (AuthenticationException ae) {
        fail("alternateAuthentication should NOT have thrown an AuthenticationException");
    }
}
 
Example 17
Source File: TestJWTAuthenticationHandler.java    From registry with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiredJWT() throws Exception {
    try {
        handler.setPublicKey(publicKey);

        Properties props = getProperties();
        handler.init(props);

        SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() - 1000),
                privateKey);

        Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        Mockito.when(request.getRequestURL()).thenReturn(
                new StringBuffer(SERVICE_URL));
        HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(
                SERVICE_URL);

        AuthenticationToken token = handler.authenticate(request,
                response);
        Mockito.verify(response).sendRedirect(REDIRECT_LOCATION);
    } catch (ServletException se) {
        fail("alternateAuthentication should NOT have thrown a ServletException");
    } catch (AuthenticationException ae) {
        fail("alternateAuthentication should NOT have thrown a AuthenticationException");
    }
}
 
Example 18
Source File: BookstoreTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private String token(boolean managerUser) {
    JSONObject claims = new JSONObject();

    claims.put(Claims.iss.name(), "https://server.example.com");
    claims.put(Claims.upn.name(), managerUser ? "[email protected]" : "[email protected]");
    long currentTimeInSecs = System.currentTimeMillis() / 1000;
    claims.put(Claims.iat.name(), currentTimeInSecs);
    claims.put(Claims.auth_time.name(), currentTimeInSecs);
    claims.put(Claims.exp.name(), currentTimeInSecs + 300);
    claims.put(Claims.jti.name(), "a-123");
    claims.put(Claims.sub.name(), "24400320");
    claims.put(Claims.preferred_username.name(), managerUser ? "alice" : "bob");
    claims.put(Claims.aud.name(), "s6BhdRkqt3");
    List<String> groups = new ArrayList<>();
    if (managerUser) {
        groups.add("manager");
        groups.add("reader");
    } else {
        groups.add("reader");
    }
    claims.put(Claims.groups.name(), groups);

    try {
        PrivateKey pk = readPrivateKey("/privateKey.pem");
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
                .keyID("/privateKey.pem")
                .type(JOSEObjectType.JWT)
                .build();

        JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);
        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 19
Source File: SimpleTokenManager.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public NewCookie createSecureTokenNewCookie(SignedJWT token) {
    return new NewCookie(TOKEN_NAME, token.serialize(), "/", null, null, (int) (tokenDuration / 1000), true);
}
 
Example 20
Source File: JWTFederationFilterTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
  String token = "Bearer " + jwt.serialize();
  EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
}