io.jsonwebtoken.JwtBuilder Java Examples
The following examples show how to use
io.jsonwebtoken.JwtBuilder.
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: JsonWebToken.java From pravega with Apache License 2.0 | 8 votes |
/** * Returns the 3 part JWT string representation. * * Example JWT: * - Compact representation: * eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjM3MDc2MjUyMjgsInMxIjoiUkVBRF9VUERBVEUifQ.j6xbFRIIZxv3GEedqKcZVy-49Y7U1710q-gjY43-UMgO_kwCH_9kJRuZ7Am589kg5TJewmGhGB9SPblES78pEg * - Decoded parts: * - header: {alg=HS512} * - body/payload: {exp=3707625228, s1=READ_UPDATE}, * - signature: j6xbFRIIZxv3GEedqKcZVy-49Y7U1710q-gjY43-UMgO_kwCH_9kJRuZ7Am589kg5TJewmGhGB9SPblES78pEg * * @return compact representation of JWT */ public String toCompactString() { JwtBuilder builder = Jwts.builder() .setSubject(subject) .setAudience(audience) .setIssuedAt(Date.from(currentInstant)); if (this.permissionsByResource != null) { // Subject, audience and issued at fields are claims (in the JWT body) too. Invoking the setClaims() // will override the fields we set before. Therefore, we use the append method addClaims(..), instead. builder.addClaims(permissionsByResource); } if (this.expirationTime != null) { builder.setExpiration(expirationTime); } builder.signWith(signatureAlgorithm, signingKey); return builder.compact(); }
Example #2
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 8 votes |
@Override public String createToken(String subject, long ttlMillis) { if (ttlMillis <= 0) { throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] "); } SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // The JWT signature algorithm we will be using to sign the token long nowMillis = System.currentTimeMillis(); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signatureAlgorithm, signingKey); builder.setExpiration(new Date(nowMillis + ttlMillis)); return builder.compact(); }
Example #3
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 8 votes |
@Override public String createToken(String subject, long ttlMillis) { if (ttlMillis <= 0) { throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] "); } SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // The JWT signature algorithm we will be using to sign the token long nowMillis = System.currentTimeMillis(); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signatureAlgorithm, signingKey); builder.setExpiration(new Date(nowMillis + ttlMillis)); return builder.compact(); }
Example #4
Source File: JjwtUtil.java From ProjectStudy with MIT License | 7 votes |
/** * 生成签名,获取Token * * @param username * @param base64Security * @return java.lang.String * @author Wang926454 * @date 2018/8/31 10:03 */ public static String createJWT(String username, String base64Security) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // 生成JWT的时间 long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); // 添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .setIssuedAt(now) .setSubject(username) .signWith(signatureAlgorithm, base64Security.getBytes()); // 设置过期时间 if (EXPIRE_TIME >= 0) { long expMillis = nowMillis + EXPIRE_TIME; Date exp = new Date(expMillis); builder.setExpiration(exp); } // 生成JWT return builder.compact(); }
Example #5
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 7 votes |
@Override public String createToken(String subject, long ttlMillis) { if (ttlMillis <= 0) { throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] "); } SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // The JWT signature algorithm we will be using to sign the token long nowMillis = System.currentTimeMillis(); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signatureAlgorithm, signingKey); builder.setExpiration(new Date(nowMillis + ttlMillis)); return builder.compact(); }
Example #6
Source File: MqttExample.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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 NoSuchAlgorithmException, IOException, InvalidKeySpecException { 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("EC"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
Example #7
Source File: MqttExample.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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 NoSuchAlgorithmException, IOException, InvalidKeySpecException { 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(); }
Example #8
Source File: MqttCommandsDemo.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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 NoSuchAlgorithmException, IOException, InvalidKeySpecException { 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(); }
Example #9
Source File: HttpExample.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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("EC"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
Example #10
Source File: MqttCommandsDemo.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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 NoSuchAlgorithmException, IOException, InvalidKeySpecException { 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("EC"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
Example #11
Source File: CloudiotPubsubExampleMqttDevice.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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(); }
Example #12
Source File: CloudiotPubsubExampleMqttDevice.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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("EC"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
Example #13
Source File: DefaultJwtBuilder.java From jjwt with Apache License 2.0 | 6 votes |
@Override public JwtBuilder claim(String name, Object value) { Assert.hasText(name, "Claim property name cannot be null or empty."); if (this.claims == null) { if (value != null) { ensureClaims().put(name, value); } } else { if (value == null) { this.claims.remove(name); } else { this.claims.put(name, value); } } return this; }
Example #14
Source File: JwtUtils.java From my_curd with Apache License 2.0 | 6 votes |
/** * 生成签名 * * @param username 用户名 * @param roleList 角色集合 * @param permissionList 权限集合 * @return */ public static String buildToken(String username, List<String> roleList, List<String> permissionList) { // HS256签名算法 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); // 构造payload long nowSeconds = System.currentTimeMillis() / 1000; JSONObject payload = new JSONObject(); payload.put("iss", ISS); // 签发者 payload.put("iat", nowSeconds); // 签发时间 payload.put("exp", nowSeconds + EXPIRATION_TIME_VALUE); // 过期时间 payload.put("username", username); if (roleList == null) { payload.put("roleList", new ArrayList<>()); } if (permissionList == null) { payload.put("permissionList", new ArrayList<>()); } JwtBuilder builder = Jwts.builder().setPayload(payload.toJSONString()) .signWith(signatureAlgorithm, signingKey); return builder.compact(); }
Example #15
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 6 votes |
@Override public String createToken(String subject, long ttlMillis) { if (ttlMillis <= 0) { throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] "); } SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // The JWT signature algorithm we will be using to sign the token long nowMillis = System.currentTimeMillis(); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signatureAlgorithm, signingKey); builder.setExpiration(new Date(nowMillis + ttlMillis)); return builder.compact(); }
Example #16
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 6 votes |
@Override public String createToken(String subject, long ttlMillis) { if (ttlMillis <= 0) { throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] "); } SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // The JWT signature algorithm we will be using to sign the token long nowMillis = System.currentTimeMillis(); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signatureAlgorithm, signingKey); builder.setExpiration(new Date(nowMillis + ttlMillis)); return builder.compact(); }
Example #17
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 6 votes |
@Override public String createToken(String subject, long ttlMillis) { if (ttlMillis <= 0) { throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] "); } SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // The JWT signature algorithm we will be using to sign the token long nowMillis = System.currentTimeMillis(); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signatureAlgorithm, signingKey); builder.setExpiration(new Date(nowMillis + ttlMillis)); return builder.compact(); }
Example #18
Source File: JwtService.java From faster-framework-project with Apache License 2.0 | 6 votes |
/** * 生成token * * @param audience 观众,理解为此token允许哪些人使用。 * 可以是一个数组字符串,包含了所有的允许对象,如"www.baidu.com","www.qq.com"。 * 也可以是一个单一字符串,如:"{userId}" * @param expSecond 过期时间(秒) * @param base64Security 秘钥 * @return String */ private String createToken(String audience, long expSecond, String base64Security) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder() .setAudience(audience) .setIssuedAt(now) .claim("env", env) .signWith(signatureAlgorithm, signingKey); //添加Token过期时间 if (expSecond > 0) { long expMillis = nowMillis + expSecond * 1000; Date exp = new Date(expMillis); builder = builder.setExpiration(exp).setNotBefore(now); } //生成Token return builder.compact(); }
Example #19
Source File: JwtHelper.java From github-branch-source-plugin with MIT License | 6 votes |
/** * Create a JWT for authenticating to GitHub as an app installation * @param githubAppId the app ID * @param privateKey PKC#8 formatted private key * @return JWT for authenticating to GitHub */ static String createJWT(String githubAppId, final String privateKey) { requireNonNull(githubAppId, privateKey); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Key signingKey; try { signingKey = getPrivateKeyFromString(privateKey); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("Couldn't parse private key for GitHub app, make sure it's PKCS#8 format", e); } JwtBuilder builder = Jwts.builder() .setIssuedAt(now) .setIssuer(githubAppId) .signWith(signingKey, signatureAlgorithm); Date exp = new Date(nowMillis + VALIDITY_MS); builder.setExpiration(exp); return builder.compact(); }
Example #20
Source File: JwtHelper.java From kisso with Apache License 2.0 | 6 votes |
/** * <p> * 签名并生成 Token * </p> */ public static String signCompact(JwtBuilder jwtBuilder) { SSOConfig config = SSOConfig.getInstance(); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm()); if (SSOConstants.RSA.equals(signatureAlgorithm.getFamilyName())) { try { if(null == RSA_KEY) { ClassPathResource resource = new ClassPathResource(config.getRsaJksStore()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(resource.getInputStream(), config.getRsaStorepass().toCharArray()); RSA_KEY = keystore.getKey(config.getRsaAlias(), config.getRsaKeypass().toCharArray()); } // RSA 签名 return jwtBuilder.signWith(RSA_KEY, signatureAlgorithm).compact(); } catch (Exception e) { throw new KissoException("signCompact error.", e); } } // 普通签名 SecretKey secretKey = getSecretKey(config.getSignKey(), signatureAlgorithm); return jwtBuilder.signWith(secretKey, signatureAlgorithm).compact(); }
Example #21
Source File: Utils.java From samples-android with Apache License 2.0 | 6 votes |
public static String getJwt(String issuer, String nonce, Date expiredDate, Date issuedAt, String... audience) { JwtBuilder builder = Jwts.builder(); KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256); Map<String, Object> map = new HashMap<>(); map.put(Claims.AUDIENCE, Arrays.asList(audience)); return builder .addClaims(map) .claim("nonce", nonce) .setIssuer(issuer) .setSubject("sub") .setExpiration(expiredDate) .setIssuedAt(issuedAt) .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256) .compact(); }
Example #22
Source File: JwtTokenGenerator.java From hsweb-framework with Apache License 2.0 | 6 votes |
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(); }
Example #23
Source File: JsonWebTokenService.java From spring-boot-mongodb-jwt with Apache License 2.0 | 6 votes |
@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()); } }
Example #24
Source File: JwtUtil.java From hello-sso-jwt-auth with MIT License | 5 votes |
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); return builder.compact(); }
Example #25
Source File: DefaultJwtBuilder.java From jjwt with Apache License 2.0 | 5 votes |
@Override public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) throws InvalidKeyException { Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty."); Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead."); byte[] bytes = Decoders.BASE64.decode(base64EncodedSecretKey); return signWith(alg, bytes); }
Example #26
Source File: SSOClientTest.java From sso-client with Apache License 2.0 | 5 votes |
protected JwtBuilder jwtBuilder(long exp, Map<String, Object> ext){ JwtBuilder jwt = Jwts.builder() .claim("user_id","43FE6476-CD7B-493B-8044-C7E3149D0876") .claim("scope","perm name user") .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; }
Example #27
Source File: JwtTokenService.java From secrets-proxy with Apache License 2.0 | 5 votes |
/** * Generate a JWT token for the given user. The roles will be stored as a claim in JWT token as a * comma separated string. * * @param user authenticated user details object. * @return compact JWS (JSON Web Signature) */ public @Nonnull String generateToken(OneOpsUser user) { Instant now = Instant.now(); Instant expiresIn = now.plusSeconds(expiresInSec); JwtBuilder jwt = Jwts.builder() .setSubject(user.getUsername()) .setIssuer(issuer) .setIssuedAt(Date.from(now)) .setExpiration(Date.from(expiresIn)) .signWith(SIGNATURE_ALGORITHM, String.valueOf(secretKey)); if (user.getAuthorities() != null) { List<String> roles = user.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList()); jwt.claim(ROLE_CLAIM, String.join(",", roles)); } if (user.getDomain() != null) { jwt.claim(DOMAIN_CLAIM, user.getDomain().getType()); } if (user.getCn() != null) { jwt.claim(CN_CLAIM, user.getCn()); } if (compressionEnabled) { jwt.compressWith(CompressionCodecs.DEFLATE); } return jwt.compact(); }
Example #28
Source File: JsonWebTokenHandler.java From presto with Apache License 2.0 | 5 votes |
public String getBearerToken(String subject) { checkState(jwtSigner.isPresent(), "not configured"); JwtBuilder jwt = Jwts.builder() .setSubject(subject) .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant())); jwtSigner.get().accept(jwt); jwtKeyId.ifPresent(keyId -> jwt.setHeaderParam(KEY_ID, keyId)); jwtIssuer.ifPresent(jwt::setIssuer); jwtAudience.ifPresent(jwt::setAudience); return jwt.compact(); }
Example #29
Source File: DefaultJwtBuilder.java From jjwt with Apache License 2.0 | 5 votes |
@Override public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKeyBytes) throws InvalidKeyException { Assert.notNull(alg, "SignatureAlgorithm cannot be null."); Assert.notEmpty(secretKeyBytes, "secret key byte array cannot be null or empty."); Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead."); SecretKey key = new SecretKeySpec(secretKeyBytes, alg.getJcaName()); return signWith(key, alg); }
Example #30
Source File: AuthenticationProviderTokenTest.java From pulsar with Apache License 2.0 | 5 votes |
private static String createTokenWithAudience(Key signingKey, String audienceClaim, List<String> audience) { JwtBuilder builder = Jwts.builder() .setSubject(SUBJECT) .signWith(signingKey); builder.claim(audienceClaim, audience); return builder.compact(); }