com.nimbusds.jose.crypto.MACSigner Java Examples
The following examples show how to use
com.nimbusds.jose.crypto.MACSigner.
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: 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 #3
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@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 #4
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@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 #5
Source File: EncryptionUtility.java From amex-api-java-client-core with Apache License 2.0 | 6 votes |
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 #6
Source File: TokenUtil.java From peer-os with Apache License 2.0 | 6 votes |
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: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@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 #8
Source File: UserRepository.java From shiro-jwt with MIT License | 6 votes |
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 #9
Source File: AuthUtils.java From blog with MIT License | 5 votes |
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 #10
Source File: DefaultConsentReferencePolicy.java From XS2A-Sandbox with Apache License 2.0 | 5 votes |
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 #11
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 #12
Source File: CookieCsrfSignedTokenRepository.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public void afterPropertiesSet() throws Exception { // Add padding if necessary // HS256 need, at least, 32 ascii characters secret = org.apache.commons.lang3.StringUtils.leftPad(secret, 32, '0'); signer = new MACSigner(secret); verifier = new MACVerifier(secret); }
Example #13
Source File: ReferenceSerializer.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
public String serialize(IdentityReference reference) throws Exception { // Create HMAC signer JWSSigner signer = new MACSigner(secretKey.getEncoded()); // Prepare JWT with claims set JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject(reference.getReference()) .issuer(reference.getSource()) .build(); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet); // Apply the HMAC protection signedJWT.sign(signer); // Create JWE object with signed JWT as payload JWEObject jweObject = new JWEObject( new JWEHeader.Builder(JWEAlgorithm.DIR, EncryptionMethod.A256GCM) .contentType("JWT") // required to signal nested JWT .build(), new Payload(signedJWT)); // Perform encryption jweObject.encrypt(new DirectEncrypter(secretKey.getEncoded())); // Serialize to compact form return new String(Base64.getEncoder().encode(jweObject.serialize().getBytes())); }
Example #14
Source File: ZendeskRedirectServlet.java From codenvy with Eclipse Public License 1.0 | 5 votes |
@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 #15
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 #16
Source File: Jwt.java From JWT with MIT License | 5 votes |
/** * 生成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 #17
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 #18
Source File: CookieCsrfSignedTokenRepository.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public void afterPropertiesSet() throws Exception { // Add padding if necessary // HS256 need, at least, 32 ascii characters secret = org.apache.commons.lang3.StringUtils.leftPad(secret, 32, '0'); signer = new MACSigner(secret); verifier = new MACVerifier(secret); }
Example #19
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void testHmacJwt_invalidClientAuthMethod() throws NoSuchAlgorithmException, JOSEException { // Generate random 256-bit (32-byte) shared secret SecureRandom random = new SecureRandom(); byte[] sharedSecret = new byte[32]; random.nextBytes(sharedSecret); String clientSecret = new String(sharedSecret, StandardCharsets.UTF_8); JWSSigner signer = new MACSigner(clientSecret); Client client = new Client(); client.setClientId(CLIENT_ID); client.setClientSecret(new String(sharedSecret)); client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT); String assertion = generateJWT(signer); OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class); String basePath="/"; when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client)); when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE); when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test(); testObserver.assertError(InvalidClientException.class); testObserver.assertNotComplete(); }
Example #20
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void testHmacJwt() throws NoSuchAlgorithmException, JOSEException { // Generate random 256-bit (32-byte) shared secret SecureRandom random = new SecureRandom(); byte[] sharedSecret = new byte[32]; random.nextBytes(sharedSecret); String clientSecret = new String(sharedSecret, StandardCharsets.UTF_8); JWSSigner signer = new MACSigner(clientSecret); Client client = new Client(); client.setClientId(CLIENT_ID); client.setClientSecret(new String(sharedSecret)); client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT); String assertion = generateJWT(signer); OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class); String basePath="/"; when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client)); when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE); when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test(); testObserver.assertNoErrors(); testObserver.assertValue(client); }
Example #21
Source File: JWT.java From api-server-seed with Apache License 2.0 | 4 votes |
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; }