Java Code Examples for com.nimbusds.jose.JWSAlgorithm#HS256

The following examples show how to use com.nimbusds.jose.JWSAlgorithm#HS256 . 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 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: 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: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method map signature algorithm define in identity.xml to nimbus
 * signature algorithm
 * format, Strings are defined inline hence there are not being used any
 * where
 *
 * @param signatureAlgorithm
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception {

    if (NONE.equals(signatureAlgorithm)) {
        return new JWSAlgorithm(JWSAlgorithm.NONE.getName());
    } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
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: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * This method map signature algorithm define in identity.xml to nimbus
 * signature algorithm
 * format, Strings are defined inline hence there are not being used any
 * where
 *
 * @param signatureAlgorithm
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception {

    if (NONE.equals(signatureAlgorithm)) {
        return new JWSAlgorithm(JWSAlgorithm.NONE.getName());
    } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
Example 9
Source File: ClientCredentialsGrantHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm)
        throws IdentityOAuth2Exception {
    if ("SHA256withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if ("SHA384withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if ("SHA512withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if ("SHA256withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if ("SHA384withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if ("SHA512withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if ("SHA256withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if ("SHA384withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if ("SHA512withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    log.error("Unsupported Signature Algorithm in identity.xml");
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
Example 10
Source File: TokenHelperImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
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 11
Source File: MobiTokenVerifier.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 12
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 13
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This method map signature algorithm define in identity.xml to nimbus
 * signature algorithm
 * format, Strings are defined inline hence there are not being used any
 * where
 *
 * @param signatureAlgorithm
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm)
        throws IdentityOAuth2Exception {
    if ("SHA256withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if ("SHA384withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if ("SHA512withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if ("SHA256withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if ("SHA384withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if ("SHA512withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if ("SHA256withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if ("SHA384withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if ("SHA512withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    } else if(NONE.equals(signatureAlgorithm)){
        return new JWSAlgorithm(JWSAlgorithm.NONE.getName());
    }
    log.error("Unsupported Signature Algorithm in identity.xml");
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
Example 14
Source File: SecurityUtils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * 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 15
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;
}