Java Code Examples for io.jsonwebtoken.Claims#put()

The following examples show how to use io.jsonwebtoken.Claims#put() . 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: JwtTokenUtil.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
/**
 * 当原来的token没过期时是可以刷新的
 *
 * @param oldToken 带tokenHead的token
 */
public String refreshHeadToken(String oldToken) {
    if(StrUtil.isEmpty(oldToken)){
        return null;
    }
    String token = oldToken.substring(tokenHead.length());
    if(StrUtil.isEmpty(token)){
        return null;
    }
    //token校验不通过
    Claims claims = getClaimsFromToken(token);
    if(claims==null){
        return null;
    }
    //如果token已经过期,不支持刷新
    if(isTokenExpired(token)){
        return null;
    }
    //如果token在30分钟之内刚刷新过,返回原token
    if(tokenRefreshJustBefore(token,30*60)){
        return token;
    }else{
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }
}
 
Example 2
Source File: JwtTokenFactory.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public JwtToken createRefreshToken(SecurityUser securityUser) {
    if (StringUtils.isBlank(securityUser.getEmail())) {
        throw new IllegalArgumentException("Cannot create JWT Token without username/email");
    }

    ZonedDateTime currentTime = ZonedDateTime.now();

    UserPrincipal principal = securityUser.getUserPrincipal();
    Claims claims = Jwts.claims().setSubject(principal.getValue());
    claims.put(SCOPES, Collections.singletonList(Authority.REFRESH_TOKEN.name()));
    claims.put(USER_ID, securityUser.getId());
    claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);

    String token = Jwts.builder()
            .setClaims(claims)
            .setIssuer(settings.getTokenIssuer())
            .setId(UUID.randomUUID().toString())
            .setIssuedAt(Date.from(currentTime.toInstant()))
            .setExpiration(Date.from(currentTime.plusSeconds(settings.getRefreshTokenExpTime()).toInstant()))
            .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
            .compact();

    return new AccessJwtToken(token, claims);
}
 
Example 3
Source File: JWTUtil.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> validateToken(String token) {
   /* 成功则返回user 失败抛出未授权异常,但是如果要刷新token,我想也在这里完成,因为如果后面判断token是否过期
    就还需要再解析一次token,解token是比较消耗性能的,因此这里需要一个东西存token
    超时时间可以随着刷新自增长 最大为7天*/
    Claims claims = getAllClaimsFromToken(token);
    long difference = claims.getExpiration().getTime() - System.currentTimeMillis();
    if (difference < 0) {
        //无效 抛token过期异常
        throw new AuthExpirationException(HttpStatus.UNAUTHORIZED, "登录身份信息过期");
    }
    if (difference < authProperties.getRefreshInterval()) {
        //小于一定区间,刷新
        token = refreshToken(claims);
        claims.put("newToken", token);
    }
    return claims;
}
 
Example 4
Source File: JwtTokenFactory.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
public JwtToken createRefreshToken(SecurityUser securityUser) {
  if (StringUtils.isBlank(securityUser.getEmail())) {
    throw new IllegalArgumentException("Cannot create JWT Token without username/email");
  }

  DateTime currentTime = new DateTime();

  UserPrincipal principal = securityUser.getUserPrincipal();
  Claims claims = Jwts.claims().setSubject(principal.getValue());
  claims.put(SCOPES, Arrays.asList(Authority.REFRESH_TOKEN.name()));
  claims.put(USER_ID, securityUser.getId().getId().toString());
  claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);

  String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
      .setId(UUID.randomUUID().toString()).setIssuedAt(currentTime.toDate())
      .setExpiration(currentTime.plusSeconds(settings.getRefreshTokenExpTime()).toDate())
      .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

  return new AccessJwtToken(token, claims);
}
 
Example 5
Source File: Crust.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 刷新令牌
 * @return Token
 */
public String refreshToken() {
    if (!props.isStateless()) { return null; }
    String refreshedToken;
    try {
        Claims claims = JwtUtil.parseToken(getToken(), getUnSignKey());
        claims.put(CREATED, new Date());
        refreshedToken = JwtUtil.generateToken(claims, getSignKey(), Math.toIntExact(props.getExpire().toMinutes()), props.isUseRsa());
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 6
Source File: JwtTokenUtil.java    From tour-of-heros-api-security-zerhusen with MIT License 5 votes vote down vote up
public String refreshToken(String token) {
    String refreshedToken;
    try {
        final Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        refreshedToken = generateToken(claims);
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 7
Source File: JwtTokenUtil.java    From microservices-sample-project with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token) {
    String refreshedToken;
    try {
        final Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        refreshedToken = generateToken(claims);
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 8
Source File: JwtHelper.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token, String base64Security, long TTLMillis) {
    String refreshedToken;
    try {
        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());

        final Claims claims = parseJWT(token, base64Security);
        claims.put("creatDate", new Date());
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setSubject(getUsername(token, base64Security))
                .setIssuer(getIssuer(token, base64Security))
                .setAudience(getAudience(token, base64Security))
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }
        refreshedToken = builder.compact();
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 9
Source File: JwtTokenFactory.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
/**
 * Factory method for issuing new JWT Tokens.
 * 
 * @param username
 * @param roles
 * @return
 */
public AccessJwtToken createAccessJwtToken(UserContext userContext) {
    if (StringUtils.isBlank(userContext.getTenantId())) 
        throw new IllegalArgumentException("Cannot create JWT Token without tenantId");

    if (StringUtils.isBlank(userContext.getOrgId())) 
        throw new IllegalArgumentException("Cannot create JWT Token without orgId");

    if (userContext.getAuthorities() == null || userContext.getAuthorities().isEmpty()) 
        throw new IllegalArgumentException("User doesn't have any privileges");

    Claims claims = Jwts.claims().setSubject(userContext.getOrgId());
    claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
    claims.put("tenant", userContext.getTenantId());

    DateTime currentTime = new DateTime();

    String token = Jwts.builder()
      .setClaims(claims)
      .setIssuer(settings.getTokenIssuer())
      .setIssuedAt(currentTime.toDate())
      .setExpiration(currentTime.plusMinutes(settings.getTokenExpirationTime()).toDate())
      .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
    .compact();

    return new AccessJwtToken(token, claims);
}
 
Example 10
Source File: JwtTokenUtil.java    From spring-security with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token) {
    String refreshedToken;
    try {
        final Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        refreshedToken = generateToken(claims);
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 11
Source File: JwtTokenFactory.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method for issuing new JWT Tokens.
 */
public AccessJwtToken createAccessJwtToken(SecurityUser securityUser) {
  if (StringUtils.isBlank(securityUser.getEmail()))
    throw new IllegalArgumentException("Cannot create JWT Token without username/email");

  if (securityUser.getAuthority() == null)
    throw new IllegalArgumentException("User doesn't have any privileges");

  UserPrincipal principal = securityUser.getUserPrincipal();
  String subject = principal.getValue();
  Claims claims = Jwts.claims().setSubject(subject);
  claims.put(SCOPES, securityUser.getAuthorities().stream().map(s -> s.getAuthority()).collect(Collectors.toList()));
  claims.put(USER_ID, securityUser.getId().getId().toString());
  claims.put(FIRST_NAME, securityUser.getFirstName());
  claims.put(LAST_NAME, securityUser.getLastName());
  claims.put(ENABLED, securityUser.isEnabled());
  claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);
  if (securityUser.getTenantId() != null) {
    claims.put(TENANT_ID, securityUser.getTenantId().getId().toString());
  }
  if (securityUser.getCustomerId() != null) {
    claims.put(CUSTOMER_ID, securityUser.getCustomerId().getId().toString());
  }

  DateTime currentTime = new DateTime();

  String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
      .setIssuedAt(currentTime.toDate())
      .setExpiration(currentTime.plusSeconds(settings.getTokenExpirationTime()).toDate())
      .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

  return new AccessJwtToken(token, claims);
}
 
Example 12
Source File: JwtTokenUtil.java    From digag-server with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token) {
    String refreshedToken;
    try {
        final Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        refreshedToken = generateToken(claims);
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 13
Source File: JwtTokenProvider.java    From spring-webmvc-jwt-sample with GNU General Public License v3.0 5 votes vote down vote up
public String createToken(String username, List<String> roles) {

        Claims claims = Jwts.claims().setSubject(username);
        claims.put("roles", roles);

        Date now = new Date();
        Date validity = new Date(now.getTime() + jwtProperties.getValidityInMs());

        return Jwts.builder()//
            .setClaims(claims)//
            .setIssuedAt(now)//
            .setExpiration(validity)//
            .signWith(SignatureAlgorithm.HS256, secretKey)//
            .compact();
    }
 
Example 14
Source File: JwtTokenUtil.java    From xmanager with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token) {
    String refreshedToken;
    try {
        final Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, timeProvider.now());
        refreshedToken = doGenerateToken(claims);
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 15
Source File: JwtTokenUtil.java    From mall-learning with Apache License 2.0 4 votes vote down vote up
/**
 * 刷新token
 */
public String refreshToken(String token) {
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
}
 
Example 16
Source File: JwtTokenUtil.java    From mall-learning with Apache License 2.0 4 votes vote down vote up
/**
 * 刷新token
 */
public String refreshToken(String token) {
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
}
 
Example 17
Source File: AuthTokenBuilder.java    From production-ready-microservices-starter with MIT License 4 votes vote down vote up
/**
 * Creates access tokens from Authentication.
 *
 * @param authentication
 * @return token.
 */
public String createAccessToken(Authentication authentication) {

    String principal = (String) authentication.getPrincipal();

    if (StringUtils.isBlank(principal)) {
        throw new IllegalStateException("Authentication principle can not be null or empty.");
    }

    String[] orgTenantUsername = principal.split(String.valueOf(Character.LINE_SEPARATOR));

    if (orgTenantUsername == null || orgTenantUsername.length != 3) {
        throw new IllegalStateException(
                String.format("Authentication principle[%s] should contain org, tenant and username.", principal));
    }

    String org = orgTenantUsername[0];
    String tenant = orgTenantUsername[1];
    String username = orgTenantUsername[2];
    List<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities());

    if (StringUtils.isBlank(org)) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain org.", principal));
    }

    if (StringUtils.isBlank(tenant)) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain tenant.", principal));
    }

    if (StringUtils.isBlank(username)) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain username.", principal));
    }

    if (authorities == null || authorities.isEmpty()) {
        throw new IllegalArgumentException(
                String.format("Authentication principle[%s] does not contain authorities.", principal));
    }

    Claims claims = Jwts.claims();
    claims.setSubject(username);
    claims.put("org", org);
    claims.put("tenant", tenant);
    claims.put("scopes", authorities.stream().map(s -> s.toString()).collect(Collectors.toList()));

    LocalDateTime currentTime = dateUtil.getCurrentLocalDateTime();
    Date issueDate = Date.from(currentTime.toInstant(ZoneOffset.UTC));
    Date expiration = Date.from(currentTime.plusSeconds(
            authJwtProperties.getTokenExpirationTimeInSecond()).toInstant(ZoneOffset.UTC));

    PrivateKey privateKey = encryptionKeyUtil.loadPrivateKey(authJwtProperties.getTokenSigningPrivateKeyPath());

    return jwtUtil.getJwts(claims, authJwtProperties.getTokenIssuer(), issueDate, expiration, privateKey);
}
 
Example 18
Source File: JwtTokenUtil.java    From HIS with Apache License 2.0 4 votes vote down vote up
/**
 * 刷新token
 */
public String refreshToken(String token) {
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
}
 
Example 19
Source File: JwtTokenUtil.java    From HIS with Apache License 2.0 4 votes vote down vote up
/**
 * 刷新token
 */
public String refreshToken(String token) {
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
}
 
Example 20
Source File: JwtTokenUtil.java    From HIS with Apache License 2.0 4 votes vote down vote up
/**
 * 刷新token
 */
public String refreshToken(String token) {
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
}