Java Code Examples for com.nimbusds.jose.JWSObject#sign()

The following examples show how to use com.nimbusds.jose.JWSObject#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: JwkKeyPairManager.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public String getSignedContent(String content) {
    Payload contentPayload = new Payload(content);

    try {
        RSASSASigner rsa = new RSASSASigner((RSAPrivateKey) clientJwk);
        JWSAlgorithm alg = JWSAlgorithm.RS256;
        JWSHeader header = new JWSHeader.Builder(alg)
            .keyID(clientJwk.getKeyID())
            .build();
        JWSObject jws = new JWSObject(header, contentPayload);
        jws.sign(rsa);
        return jws.serialize();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: EncryptionUtility.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
public String sign(String algorithm, String kid, String keyStr, String dataToSign) {
    try {

        Key key = getKey(algorithm, keyStr);

        JWSHeader.Builder jwsBuilder = new JWSHeader.Builder("HS256".equals(algorithm) ? JWSAlgorithm.HS256 : JWSAlgorithm.RS256);
        jwsBuilder.keyID(kid);

        JWSHeader signingHeader = jwsBuilder.build();
        JWSSigner signer = "HS256".equals(algorithm) ? new MACSigner(key.getEncoded()) : new RSASSASigner((RSAPrivateKey) key);
        JWSObject jwsObject = new JWSObject(signingHeader, new Payload(dataToSign));
        jwsObject.sign(signer);
        checkObject(jwsObject);

        String parts[] = jwsObject.serialize().split("\\.");

        return "{\"protected\":\"" + parts[0] + "\", \"payload\":\"" + parts[1] + "\", \"signature\":\"" + parts[2] + "\"}";

    } catch (Exception e) {
        throw new CryptoException("Exception signing data: " + e.getMessage(), e);
    }
}
 
Example 3
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
    try
    {
        JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );

        Payload pl = new Payload( claimJson );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );

        jwsObject.sign( signer );

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

        return "";
    }
}
 
Example 4
Source File: UserRepository.java    From shiro-jwt with MIT License 6 votes vote down vote up
default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(new Date().getTime() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());

        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

        Payload payload = new Payload(claimsSet.toJSONObject());

        JWSObject jwsObject = new JWSObject(header, payload);

        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
 
Example 5
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void validToken() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertTrue("Must be valid", signed.verify(verifier));
}
 
Example 6
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example 7
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example 8
Source File: JWTUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static JWToken issue(String subject, String keyId, PrivateKey privateKey, Long expires) throws JOSEException {

        JSONObject payload = new JSONObject();
        JWSHeader header = new JWSHeader(JWSAlgorithm.RS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, keyId, null, null);
        payload.put("sub", subject);
        payload.put("exp", expires);
        JWSObject jwsObject = new JWSObject(header, new Payload(payload));
        jwsObject.sign(new RSASSASigner(privateKey));
        return new JWToken(jwsObject.serialize());
    }
 
Example 9
Source File: Jwt.java    From JWT with MIT License 5 votes vote down vote up
/**
 * 生成token,该方法只在用户登录成功后调用
 * 
 * @param Map集合,可以存储用户id,token生成时间,token过期时间等自定义字段
 * @return token字符串,若失败则返回null
 */
public static String createToken(Map<String, Object> payload) {
	String tokenString=null;
	// 创建一个 JWS object
	JWSObject jwsObject = new JWSObject(header, new Payload(new JSONObject(payload)));
	try {
		// 将jwsObject 进行HMAC签名
		jwsObject.sign(new MACSigner(SECRET));
		tokenString=jwsObject.serialize();
	} catch (JOSEException e) {
		System.err.println("签名失败:" + e.getMessage());
		e.printStackTrace();
	}
	return tokenString;
}
 
Example 10
Source File: ZendeskRedirectServlet.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

  if (shared_key == null || subdomain == null)
    throw new ServletException("Zendesk is not configured.");
  // Given a user instance
  // Compose the JWT claims set
  JWTClaimsSet jwtClaims = new JWTClaimsSet();
  jwtClaims.setIssueTime(new Date());
  jwtClaims.setJWTID(UUID.randomUUID().toString());
  Subject subject = EnvironmentContext.getCurrent().getSubject();
  jwtClaims.setCustomClaim("name", getName());
  jwtClaims.setCustomClaim("email", subject.getUserName());
  // Create JWS header with HS256 algorithm
  JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
  JWSObject jwsObject = new JWSObject(header, new Payload(jwtClaims.toJSONObject()));
  // Create HMAC signer
  JWSSigner signer = new MACSigner(shared_key.getBytes());
  try {
    jwsObject.sign(signer);
  } catch (JOSEException e) {
    String msg = String.format("Error signing JWT: %s", e.getMessage());
    LOG.warn(msg);
    response.sendError(500, msg);
  }
  // Serialise to JWT compact form
  String jwtString = jwsObject.serialize();
  String redirectUrl = "https://" + subdomain + ".zendesk.com/access/jwt?jwt=" + jwtString;
  response.sendRedirect(redirectUrl);
}
 
Example 11
Source File: JWT.java    From api-server-seed with Apache License 2.0 4 votes vote down vote up
public static JWSObject newJWSObject(JWTUser user) throws JOSEException {
	JWSSigner signer = new MACSigner(JWT.SHARED_SECRET);
	JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload(user));
	jwsObject.sign(signer);
	return jwsObject;
}
 
Example 12
Source File: EncryptionUtils.java    From Protocol with Apache License 2.0 2 votes vote down vote up
/**
 * Sign JWS object with a given private key.
 *
 * @param jws object to be signed
 * @param key key to sign object with
 * @throws JOSEException invalid key provided
 */
public static void signJwt(JWSObject jws, ECPrivateKey key) throws JOSEException {
    jws.sign(new ECDSASigner(key, ECKey.Curve.P_384));
}