private JwtToken createJWT(String id, String issuer, String subject, String privileges, long ttlMillis) { // The JWT signature algorithm we will be using to sign the token final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256; final long nowMillis = System.currentTimeMillis(); final Date now = new Date(nowMillis); // We will sign our JWT with our ApiKey secret final Key signingKey = EncryptionUtil.getPrivateKey( env.getProperty("service.jwt.secret")); final Map<String, Object> claims = new HashMap<>(); claims.put("privileges", privileges); // Let's set the JWT Claims final JwtBuilder builder = Jwts.builder() .setClaims(claims) .setId(id) .setIssuer(issuer) .setIssuedAt(now) .setSubject(subject) .signWith(signatureAlgorithm, signingKey); // If it has been specified, let's add the expiration if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } // Builds the JWT and serializes it to a compact, URL-safe string return new JwtToken(builder.compact()); }
/** * 创建jwt * @param id * @param subject * @param ttlMillis * @return * @throws Exception */ public String createJWT(String id, String subject, long ttlMillis) throws Exception { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(now) .setSubject(subject) .signWith(signatureAlgorithm, key); if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); }
@Before public void before(){ String pk = org.apache.commons.codec.binary.Base64.encodeBase64String(keyPair.getPublic().getEncoded()); stubFor(get("/oauth2/publickey").willReturn(aResponse().withStatus(200).withBody(pk))); JwtBuilder builder = jwtBuilder(System.currentTimeMillis()+3600*1000L) .signWith(SignatureAlgorithm.RS256,keyPair.getPrivate()); jwtToken = builder.compact(); SSOConfig config = new SSOConfig().autoConfigureUrls(baseUrl); config.setClientId("test"); config.setClientSecret("test_secret"); config.setResourceName("resourceName"); config.setRedirectUri("http://www.example.com"); client = new SSOClient(config); basicHeader = SSOUtils.encodeBasicAuthorizationHeader(config.getClientId(),config.getClientSecret()); }
@Override public TokenDto generate(final String username, final String password) { if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { throw new BadCredentialsException("Input data can't be empty."); } final User user = userService.findByUsername(username); validateInputPassword(user.getPassword(), password); final Map<String, Object> tokenData = new HashMap<>(); tokenData.put("username", user.getUsername()); tokenData.put("password", user.getPassword()); tokenData.put("create_date", LocalDateTime.now()); final JwtBuilder jwtBuilder = Jwts.builder(); jwtBuilder.setClaims(tokenData); final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, expirationTime); jwtBuilder.setExpiration(calendar.getTime()); final String token = jwtBuilder.signWith(SignatureAlgorithm.HS512, secretKey).compact(); return new TokenDto(token, mapper.map(user, UserDto.class)); }
public String createJWT(String id, String subject, long ttlMillis) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = jwtConfig.generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(now) .setSubject(subject) .signWith(signatureAlgorithm, key); if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); }
@Test public void Can_create_a_jwt_token_with_no_expiry() { final String principal = someString(); final JwtBuilder builder = mock(JwtBuilder.class); final JwtBuilder principleBuilder = mock(JwtBuilder.class); final JwtBuilder secretBuilder = mock(JwtBuilder.class); final String expected = someString(); // Given given(builderFactory.create()).willReturn(builder); given(builder.claim(PRINCIPAL, principal)).willReturn(principleBuilder); given(principleBuilder.signWith(algorithm, privateKey)).willReturn(secretBuilder); given(secretBuilder.compact()).willReturn(expected); // When final String actual = new JJwtEncryptor(builderFactory, algorithm, keyPair, -1, expiryUnit, clock) .encrypt(principal); // Then verifyZeroInteractions(clock); assertThat(actual, is(expected)); }
/** * <p> * 签名并生成 Token * </p> */ public static String signCompact(JwtBuilder jwtBuilder) { SSOConfig config = SSOConfig.getInstance(); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm()); if (SSOConstants.SIGN_RSA.equals(signatureAlgorithm.getFamilyName())) { try { ClassPathResource resource = new ClassPathResource(config.getRsaKeystore()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(resource.getInputStream(), config.getRsaStorepass().toCharArray()); Key key = keystore.getKey(config.getRsaAlias(), config.getRsaKeypass().toCharArray()); // RSA 签名 return jwtBuilder.signWith(signatureAlgorithm, key).compact(); } catch (Exception e) { throw new KissoException("signCompact error.", e); } } // 普通签名 return jwtBuilder.signWith(signatureAlgorithm, config.getSignkey()).compact(); }
@Path("login") @POST @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") public String login(@FormParam(value = "id") String id) throws IOException { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRECT); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setIssuedAt(now) .setIssuer(id) .signWith(signatureAlgorithm, signingKey); long expMillis = nowMillis + EXPIRE ; Date exp = new Date(expMillis); builder.setExpiration(exp); return builder.compact(); }
/** * {@inheritDoc} */ @Override public String issueJwt(String subject, Map<String, Object> claims) { Assert.hasText(subject, "Subject can't be null or empty!!"); Instant now = Instant.now(); JwtBuilder jwtBuilder = Jwts.builder() .setHeaderParam(TYPE, JWT_TYPE) .setClaims(claims) .setSubject(subject) .setIssuer(this.jwtConfig.issuer()) .setIssuedAt(Date.from(now)) .setExpiration(Date.from(now.plus(this.jwtConfig.expirationTime(), MINUTES))) .setId(UUID.randomUUID().toString()); this.signWith(jwtBuilder); return jwtBuilder.compact(); }
/** * Creates the jwt for the given dawg credentials * @param dawgCreds The credentials to encode * @return */ public String createUserJWT(DawgCreds dawgCreds) { long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Key signingKey = new SecretKeySpec(jwtSecret.getBytes(), SIGNATURE_ALG.getJcaName()); Map<String, Object> claims = new HashMap<String, Object>(); claims.put(DawgJwt.JWT_FIELD_CREDS, dawgCreds); JwtBuilder builder = Jwts.builder() .setClaims(claims) .setId(UUID.randomUUID().toString()) .setIssuedAt(now) .setSubject(JWT_SUBJECT) .setIssuer(this.jwtIssuer) .signWith(SIGNATURE_ALG, signingKey); if (this.ttlMillis >= 0) { long expMillis = nowMillis + this.ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); }
/** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */ private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception { DateTime now = new DateTime(); // Create a JWT to authenticate this device. The device will be disconnected after the token // expires, and will have to reconnect with a new token. The audience field should always be set // to the GCP project id. JwtBuilder jwtBuilder = Jwts.builder() .setIssuedAt(now.toDate()) .setExpiration(now.plusMinutes(20).toDate()) .setAudience(projectId); byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact(); }
/** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */ private static String createJwtEs(String projectId, String privateKeyFile) throws Exception { DateTime now = new DateTime(); // Create a JWT to authenticate this device. The device will be disconnected after the token // expires, and will have to reconnect with a new token. The audience field should always be set // to the GCP project id. JwtBuilder jwtBuilder = Jwts.builder() .setIssuedAt(now.toDate()) .setExpiration(now.plusMinutes(20).toDate()) .setAudience(projectId); byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("ES256"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
/** Create a RSA-based JWT for the given project id, signed with the given private key. */ private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception { DateTime now = new DateTime(); // Create a JWT to authenticate this device. The device will be disconnected after the token // expires, and will have to reconnect with a new token. The audience field should always be set // to the GCP project id. JwtBuilder jwtBuilder = Jwts.builder() .setIssuedAt(now.toDate()) .setExpiration(now.plusMinutes(20).toDate()) .setAudience(projectId); byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact(); }
/** Create an ES-based JWT for the given project id, signed with the given private key. */ private static String createJwtEs(String projectId, String privateKeyFile) throws Exception { DateTime now = new DateTime(); // Create a JWT to authenticate this device. The device will be disconnected after the token // expires, and will have to reconnect with a new token. The audience field should always be set // to the GCP project id. JwtBuilder jwtBuilder = Jwts.builder() .setIssuedAt(now.toDate()) .setExpiration(now.plusMinutes(20).toDate()) .setAudience(projectId); byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("ES256"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
private String createJWT(String id, String issuer, String subject, Date expiration){ //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; Date now = new Date(System.currentTimeMillis()); //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(now) .setSubject(subject) .setIssuer(issuer) .setExpiration(expiration) .signWith(signatureAlgorithm, signingKey); //Builds the JWT and serializes it to a compact, URL-safe string return builder.compact(); }
private static JwtBuilder createJwtBuilderWithClaimMap(Map<String, Object> claimMap) { byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("testKey"); Key signingKey = new SecretKeySpec(apiKeySecretBytes, SIGNATURE_ALGORITHM.getJcaName()); LocalDate now = LocalDate.now(); LocalDate expirationDate = LocalDate.of(2020, 12, 31); return Jwts.builder() .setIssuedAt(valueOf(now)) .setClaims(claimMap) .setIssuer("testing-org") .setExpiration(valueOf(expirationDate)) .signWith(SIGNATURE_ALGORITHM, signingKey); }
public static String Gerate(String issuer, int idSubject, int hours) { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //Hours to milliseconds long ttlMillis = hours * 3600000; String subject = String.valueOf(idSubject); long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder().setIssuedAt(now) .setSubject(subject) .setIssuer(issuer) .signWith(signatureAlgorithm, signingKey); //if it has been specified, let's add the expiration if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } //Builds the JWT and serializes it to a compact, URL-safe string return builder.compact(); }
/** * Creates a new JWT for the specified principal. Token is signed using * the SecretKey with an HMAC 256 algorithm. * * @param principal the Principal to create the token for * @return a String representation of the generated token * @since 1.0.0 */ public String createToken(Principal principal) { final Date today = new Date(); final JwtBuilder jwtBuilder = Jwts.builder(); jwtBuilder.setSubject(principal.getName()); jwtBuilder.setIssuer("Alpine"); jwtBuilder.setIssuedAt(today); jwtBuilder.setExpiration(addDays(today, 7)); return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact(); }
public static String generateToken(String signingKey, String subject) { long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); JwtBuilder builder = Jwts.builder() .setSubject(subject) .setIssuedAt(now) .signWith(SignatureAlgorithm.HS256, signingKey); String token = builder.compact(); RedisUtil.INSTANCE.sadd(REDIS_SET_ACTIVE_SUBJECTS, subject); return token; }
public static String generate(String shopperId, Integer validitySeconds) throws IOException { JwtBuilder builder = Jwts.builder(); String apiKey = Lightrail.apiKey; String secret = Lightrail.clientSecret; if (apiKey == null) throw new BadParameterException("Lightrail.apiKey is not set."); if (secret == null) throw new BadParameterException("Lightrail.clientSecret is not set."); String payload = apiKey.substring(apiKey.indexOf(".") + 1); payload = payload.substring(0, payload.indexOf(".")); payload = new String(new BASE64Decoder().decodeBuffer(payload)); JsonObject jsonObject = new Gson().fromJson(payload, JsonObject.class); String gui = jsonObject.get("g").getAsJsonObject().get("gui").getAsString(); Map<String, Object> claims = new HashMap<String, Object>(); Long iat = System.currentTimeMillis()/1000; claims.put("iat", iat); claims.put("shopperId", shopperId); Map<String, Object> gClaims = new HashMap<String, Object>(); gClaims.put("gui", gui); claims.put("g", gClaims); if (validitySeconds != null) { Long exp = iat + validitySeconds; claims.put("exp", exp); } return builder.setClaims(claims) .setHeaderParam("typ", "JWT") .signWith(SignatureAlgorithm.HS256, secret.getBytes("UTF-8")) .compact(); }
public char[] createJwt(String projectId) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { DateTime now = new DateTime(); // Create a JWT to authenticate this device. The device will be disconnected after the token // expires, and will have to reconnect with a new token. The audience field should always // be set to the GCP project id. JwtBuilder jwtBuilder = Jwts.builder() .setIssuedAt(now.toDate()) .setExpiration(now.plusMinutes(60).toDate()) .setAudience(projectId); return jwtBuilder.signWith(SignatureAlgorithm.RS256, privateKey).compact().toCharArray(); }
@Override public String getToken(final String username, final String password) { if (username == null || password == null) { return null; } final User user = (User) userDetailsService.loadUserByUsername(username); Map<String, Object> tokenData = new HashMap<>(); if (password.equals(user.getPassword())) { tokenData.put("clientType", "user"); tokenData.put("userID", user.getId()); tokenData.put("username", user.getUsername()); tokenData.put("token_create_date", LocalDateTime.now()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, tokenExpirationTime); tokenData.put("token_expiration_date", calendar.getTime()); JwtBuilder jwtBuilder = Jwts.builder(); jwtBuilder.setExpiration(calendar.getTime()); jwtBuilder.setClaims(tokenData); return jwtBuilder.signWith(SignatureAlgorithm.HS512, tokenKey).compact(); } else { throw new ServiceException("Authentication error", this.getClass().getName()); } }
protected JwtBuilder jwtBuilder(long exp, Map<String, Object> ext){ JwtBuilder jwt = Jwts.builder() .claim("user_id","43FE6476-CD7B-493B-8044-C7E3149D0876") .claim("scope","perm") .claim("client_id","console") .claim("username","admin"); if(ext != null){ for (Entry<String, Object> entry : ext.entrySet()){ jwt.claim(entry.getKey(),entry.getValue()); } } jwt.setExpiration(new Date(exp)); return jwt; }
private static String buildJWT(Authentication authentication, String id, String issuer, Long timeToLiveMs, SignatureAlgorithm algorithm, Key privateKey, byte[] signingKey, AuthPart... includeParts) { if (authentication == null) { throw new IllegalArgumentException("Null Authentication"); } JwtBuilder builder = createJWT(id, authentication.getName(), issuer, (timeToLiveMs != null) ? timeToLiveMs.longValue() : -1); // sign if (privateKey != null || signingKey != null) { if (algorithm == null) { throw new IllegalArgumentException("Null signature algorithm"); } if (privateKey != null) { builder.signWith(algorithm, privateKey); } else { builder.signWith(algorithm, signingKey); } } // auth parts if (includeParts != null) { for (AuthPart part : includeParts) { processAuthPart(builder, authentication, part); } } return builder.compact(); }
private static void processAuthPart(JwtBuilder builder, Authentication authentication, AuthPart part) { if (part != null) { switch (part) { case PERMISSIONS: processAuthPermissions(builder, authentication); break; case DETAILS: processAuthDetails(builder, authentication); break; default: break; } } }
private static void processAuthPermissions(JwtBuilder builder, Authentication authentication) { builder.claim(AuthenticationClaims.CLAIM_NAME_ROOT, Boolean.valueOf(authentication.isRoot())); Collection<Permission> permissions = authentication.getPermissions(); if (permissions != null && !permissions.isEmpty()) { Collection<String> ps = new ArrayList<>(permissions.size()); for (Permission permission : permissions) { permission.getPermission().ifPresent(p -> ps.add(p)); } if (!ps.isEmpty()) { builder.claim(AuthenticationClaims.CLAIM_NAME_PERMISSIONS, ps); } } }
private static JwtBuilder createJWT(String id, String subject, String issuer, long timeToLiveMs) { long nowMs = System.currentTimeMillis(); Date now = new Date(nowMs); JwtBuilder builder = Jwts.builder(); builder.setIssuedAt(now); if (id != null) { builder.setId(id); } if (subject != null) { builder.setSubject(subject); } if (issuer != null) { builder.setIssuer(issuer); } if (timeToLiveMs >= 0) { long expireMs = nowMs + timeToLiveMs; builder.setExpiration(new Date(expireMs)); } return builder; }
private String modifyTokenExpirationTime(final String token) { final Jws<Claims> tokenData = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); final JwtBuilder jwtBuilder = Jwts.builder(); final Calendar calendar = Calendar.getInstance(); jwtBuilder.setClaims(tokenData.getBody()); calendar.add(Calendar.MILLISECOND, 1); jwtBuilder.setExpiration(calendar.getTime()); return jwtBuilder.signWith(SignatureAlgorithm.HS512, secretKey).compact(); }
public static JwtBuilder builder(KeyEncrypt keyEncrypt) throws KeyOperationException { SecretKey secretKey = MacProvider.generateKey(SignatureAlgorithm.HS256); byte[] encryptedKey = keyEncrypt.encrypt(secretKey.getEncoded()); return Jwts.builder() .setHeaderParam("kid", DatatypeConverter.printBase64Binary(encryptedKey)) .signWith(SignatureAlgorithm.HS256, secretKey); }
private String createJwtToken(String subject, LocalDateTime tokenExpirationDateTime, boolean isRefreshToken) { JwtBuilder jwtBuilder = Jwts.builder() .setSubject(subject) .signWith(SignatureAlgorithm.HS512, privateKey) .setExpiration(toDate(tokenExpirationDateTime)); if (isRefreshToken) { jwtBuilder.claim(REFRESH_TOKEN_CLAIM_KEY, true); } return jwtBuilder.compact(); }
private String createToken(final Map<String, Object> tokenData, final User user) { fulfillTokenUserData(tokenData, user); fulfillTokenDates(tokenData); final JwtBuilder jwtBuilder = Jwts.builder(); prepareJwtBuilder(jwtBuilder); jwtBuilder.setClaims(tokenData); return jwtBuilder.signWith(SignatureAlgorithm.HS512, tokenKey).compact(); }
@Test public void testSuccess(@Mocked CloseableHttpClient httpClient, @Mocked CloseableHttpResponse response, @Mocked JwtBuilder jwtBuilder, @Mocked BasicResponseHandler responseHandler) throws IOException { new Expectations() {{ //setup enough expectations to allow us to return the result that would have //happened via http get. HttpClientBuilder.create(); result = builder; builder.build(); result = httpClient; httpClient.execute((HttpGet)any); result = response; responseHandler.handleResponse(response); result = "{\"credentials\":{\"sharedSecret\":\"WIBBLE\"}}"; //setup enough expectations to allow jwt generation to end up with a known result. Jwts.builder(); result = jwtBuilder; jwtBuilder.setHeaderParam((String)any,any); result = jwtBuilder; jwtBuilder.setClaims((Claims)any); result = jwtBuilder; jwtBuilder.signWith((SignatureAlgorithm)any, key); result = jwtBuilder; jwtBuilder.compact(); result = "<<BUILTJWT>>"; }}; String secret = pc.getSecretForId("fish"); Assert.assertEquals(secret,"WIBBLE"); new Verifications() {{ HttpGet httpGet; httpClient.execute(httpGet = withCapture()); //check if jwt header was set on request. Assert.assertEquals("<<BUILTJWT>>", httpGet.getFirstHeader("gameon-jwt").getValue()); Assert.assertEquals("playerURL/fish", httpGet.getURI().toString()); }}; }
@Override public String encrypt(Object principal) { final JwtBuilder signedBuilder = builderFactory.create().claim(PRINCIPAL, principal) .signWith(algorithm, keyPair.getPrivate()); if (expiryDuration >= 0) { return signedBuilder.setExpiration(clock.nowPlus(expiryDuration, expiryUnit)).compact(); } return signedBuilder.compact(); }
@Test public void Can_create_a_jwt_builder() { // When final JwtBuilder actual = new JJwtBuilderFactory().create(); // Then assertThat(actual, not(nullValue())); }
@Test public void Can_create_a_jwt_token_from_a_principle() { final String principal = someString(); final JwtBuilder builder = mock(JwtBuilder.class); final JwtBuilder principleBuilder = mock(JwtBuilder.class); final JwtBuilder secretBuilder = mock(JwtBuilder.class); final Date date = mock(Date.class); final JwtBuilder expiringBuilder = mock(JwtBuilder.class); final String expected = someString(); // Given given(builderFactory.create()).willReturn(builder); given(builder.claim(PRINCIPAL, principal)).willReturn(principleBuilder); given(principleBuilder.signWith(algorithm, privateKey)).willReturn(secretBuilder); given(clock.nowPlus(expiryDuration, expiryUnit)).willReturn(date); given(secretBuilder.setExpiration(date)).willReturn(expiringBuilder); given(expiringBuilder.compact()).willReturn(expected); // When final String actual = encryptor.encrypt(principal); // Then assertThat(actual, is(expected)); }
@Override public String createToken(final String authorizationId, final Authorities authorities) { JwtBuilder builder = Jwts.builder() .signWith(algorithm, key) .setIssuer("Hono") .setSubject(Objects.requireNonNull(authorizationId)) .setExpiration(Date.from(Instant.now().plus(tokenLifetime))); if (authorities != null) { authorities.asMap().forEach((key, value) -> { builder.claim(key, value); }); } return builder.compact(); }
private void signWith(JwtBuilder jwtBuilder) { if (this.rsaPrivateKey == null) { jwtBuilder.signWith(this.signatureAlgo, this.hmacSecretKey); } else { jwtBuilder.signWith(this.signatureAlgo, this.rsaPrivateKey); } }