io.jsonwebtoken.Claims.put()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.9k)|赞(0)|评价(0)|浏览(225)

本文整理了Java中io.jsonwebtoken.Claims.put()方法的一些代码示例,展示了Claims.put()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Claims.put()方法的具体详情如下:
包路径:io.jsonwebtoken.Claims
类名称:Claims
方法名:put

Claims.put介绍

暂无

代码示例

代码示例来源:origin: macrozheng/mall

/**
   * 刷新token
   */
  public String refreshToken(String token) {
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
  }
}

代码示例来源:origin: jwtk/jjwt

@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;
}

代码示例来源:origin: jwtk/jjwt

@Override
public JwtParser require(String claimName, Object value) {
  Assert.hasText(claimName, "claim name cannot be null or empty.");
  Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
  expectedClaims.put(claimName, value);
  return this;
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void validate_token_refresh_session_when_refresh_time_is_reached() {
 UserDto user = db.users().insertUser();
 addJwtCookie();
 // Token was created 10 days ago and refreshed 6 minutes ago
 Claims claims = createToken(user.getUuid(), TEN_DAYS_AGO);
 claims.put("lastRefreshTime", SIX_MINUTES_AGO);
 when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
 assertThat(underTest.validateToken(request, response).isPresent()).isTrue();
 verify(jwtSerializer).refresh(any(Claims.class), eq(3 * 24 * 60 * 60));
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void validate_token_does_not_refresh_session_when_refresh_time_is_not_reached() {
 UserDto user = db.users().insertUser();
 addJwtCookie();
 // Token was created 10 days ago and refreshed 4 minutes ago
 Claims claims = createToken(user.getUuid(), TEN_DAYS_AGO);
 claims.put("lastRefreshTime", FOUR_MINUTES_AGO);
 when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
 assertThat(underTest.validateToken(request, response).isPresent()).isTrue();
 verify(jwtSerializer, never()).refresh(any(Claims.class), anyInt());
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void validate_token_does_not_refresh_session_when_disconnected_timeout_is_reached() {
 UserDto user = db.users().insertUser();
 addJwtCookie();
 // Token was created 4 months ago, refreshed 4 minutes ago, and it expired in 5 minutes
 Claims claims = createToken(user.getUuid(), NOW - (4L * 30 * 24 * 60 * 60 * 1000));
 claims.setExpiration(new Date(NOW + 5 * 60 * 1000));
 claims.put("lastRefreshTime", FOUR_MINUTES_AGO);
 when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
 assertThat(underTest.validateToken(request, response).isPresent()).isFalse();
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void validate_token_refresh_state_when_refreshing_token() {
 UserDto user = db.users().insertUser();
 addJwtCookie();
 // Token was created 10 days ago and refreshed 6 minutes ago
 Claims claims = createToken(user.getUuid(), TEN_DAYS_AGO);
 claims.put("xsrfToken", "CSRF_STATE");
 when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
 underTest.validateToken(request, response);
 verify(jwtSerializer).refresh(any(Claims.class), anyInt());
 verify(jwtCsrfVerifier).refreshState(request, response, "CSRF_STATE", 3 * 24 * 60 * 60);
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void validate_token_verify_csrf_state() {
 UserDto user = db.users().insertUser();
 addJwtCookie();
 Claims claims = createToken(user.getUuid(), NOW);
 claims.put("xsrfToken", CSRF_STATE);
 when(jwtSerializer.decode(JWT_TOKEN)).thenReturn(Optional.of(claims));
 underTest.validateToken(request, response);
 verify(jwtCsrfVerifier).verifyState(request, CSRF_STATE, user.getUuid());
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void refresh_token() {
 setSecretKey(A_SECRET_KEY);
 underTest.start();
 Date now = new Date();
 Date createdAt = DateUtils.parseDate("2016-01-01");
 // Expired in 10 minutes
 Date expiredAt = new Date(now.getTime() + 10 * 60 * 1000);
 Claims token = new DefaultClaims()
  .setId("id")
  .setSubject("subject")
  .setIssuer("sonarqube")
  .setIssuedAt(createdAt)
  .setExpiration(expiredAt);
 token.put("key", "value");
 // Refresh the token with a higher expiration time
 String encodedToken = underTest.refresh(token, 20 * 60);
 Claims result = underTest.decode(encodedToken).get();
 assertThat(result.getId()).isEqualTo("id");
 assertThat(result.getSubject()).isEqualTo("subject");
 assertThat(result.getIssuer()).isEqualTo("sonarqube");
 assertThat(result.getIssuedAt()).isEqualTo(createdAt);
 assertThat(result.get("key")).isEqualTo("value");
 // Expiration date has been changed
 assertThat(result.getExpiration()).isNotEqualTo(expiredAt)
  .isAfterOrEqualsTo(new Date(now.getTime() + 19 * 1000));
}

代码示例来源:origin: svlada/springboot-security-jwt

public JwtToken createRefreshToken(UserContext userContext) {
    if (StringUtils.isBlank(userContext.getUsername())) {
      throw new IllegalArgumentException("Cannot create JWT Token without username");
    }

    LocalDateTime currentTime = LocalDateTime.now();

    Claims claims = Jwts.claims().setSubject(userContext.getUsername());
    claims.put("scopes", Arrays.asList(Scopes.REFRESH_TOKEN.authority()));
    
    String token = Jwts.builder()
     .setClaims(claims)
     .setIssuer(settings.getTokenIssuer())
     .setId(UUID.randomUUID().toString())
     .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
     .setExpiration(Date.from(currentTime
       .plusMinutes(settings.getRefreshTokenExpTime())
       .atZone(ZoneId.systemDefault()).toInstant()))
     .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
    .compact();

    return new AccessJwtToken(token, claims);
  }
}

代码示例来源:origin: svlada/springboot-security-jwt

/**
 * Factory method for issuing new JWT Tokens.
 * 
 * @param username
 * @param roles
 * @return
 */
public AccessJwtToken createAccessJwtToken(UserContext userContext) {
  if (StringUtils.isBlank(userContext.getUsername())) 
    throw new IllegalArgumentException("Cannot create JWT Token without username");
  if (userContext.getAuthorities() == null || userContext.getAuthorities().isEmpty()) 
    throw new IllegalArgumentException("User doesn't have any privileges");
  Claims claims = Jwts.claims().setSubject(userContext.getUsername());
  claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
  LocalDateTime currentTime = LocalDateTime.now();
  
  String token = Jwts.builder()
   .setClaims(claims)
   .setIssuer(settings.getTokenIssuer())
   .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
   .setExpiration(Date.from(currentTime
     .plusMinutes(settings.getTokenExpirationTime())
     .atZone(ZoneId.systemDefault()).toInstant()))
   .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
  .compact();
  return new AccessJwtToken(token, claims);
}

代码示例来源:origin: stackoverflow.com

public String createToken( Email mail )
{
  Claims claims = Jwts.claims().setSubject( String.valueOf( mail.getId() ) );
   claims.put( "mailId", mail.getId() );
   Date currentTime = new Date();
   currentTime.setTime( currentTime.getTime() + tokenExpiration * 60000 );
   return Jwts.builder()
    .setClaims( claims )
    .setExpiration( currentTime )
    .signWith( SignatureAlgorithm.HS512, salt.getBytes() )
    .compact();
}

代码示例来源:origin: jonsychen/rest-security-demo

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;
}

代码示例来源:origin: koldaman/springboot-jwt-swagger

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;
}

代码示例来源:origin: Jasig/uPortal

public Preferences createPreferences(
    Map<String, List<String>> preferencesMap, String username, Date expires) {
  final Claims claims = createClaims(Preferences.class, username, expires);
  // PreferencesMap
  for (Map.Entry<String, List<String>> y : preferencesMap.entrySet()) {
    claims.put(y.getKey(), y.getValue());
  }
  return new Preferences(generateEncryptedToken(claims), preferencesMap);
}

代码示例来源:origin: io.jsonwebtoken/jjwt-impl

@Override
public JwtParser require(String claimName, Object value) {
  Assert.hasText(claimName, "claim name cannot be null or empty.");
  Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
  expectedClaims.put(claimName, value);
  return this;
}

代码示例来源:origin: io.jsonwebtoken/jjwt

@Override
public JwtParser require(String claimName, Object value) {
  Assert.hasText(claimName, "claim name cannot be null or empty.");
  Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
  expectedClaims.put(claimName, value);
  return this;
}

代码示例来源:origin: murraco/spring-boot-jwt

public String createToken(String username, List<Role> roles) {
 Claims claims = Jwts.claims().setSubject(username);
 claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
 Date now = new Date();
 Date validity = new Date(now.getTime() + validityInMilliseconds);
 return Jwts.builder()//
   .setClaims(claims)//
   .setIssuedAt(now)//
   .setExpiration(validity)//
   .signWith(SignatureAlgorithm.HS256, secretKey)//
   .compact();
}

代码示例来源:origin: hantsy/springboot-jwt-sample

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() + validityInMilliseconds);
  return Jwts.builder()//
    .setClaims(claims)//
    .setIssuedAt(now)//
    .setExpiration(validity)//
    .signWith(SignatureAlgorithm.HS256, secretKey)//
    .compact();
}

代码示例来源:origin: BHRother/spring-boot-security-jwt

public static String generateToken(JwtUserDto u, String secret) {
    Claims claims = Jwts.claims().setSubject(u.getUsername());
    claims.put("role", u.getRole());

    return Jwts.builder()
        .setClaims(claims)
        .signWith(SignatureAlgorithm.HS512, secret)
        .setExpiration(DateTime.now().plusSeconds(30).toDate())
        .compact();
  }
}

相关文章