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

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

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

Claims.get介绍

[英]Returns the JWT aud (audience) value or null if not present.
[中]返回JWTaud(访问群体)值,如果不存在,则返回null。

代码示例

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

private static Date getLastRefreshDate(Claims token) {
 Long lastFreshTime = (Long) token.get(LAST_REFRESH_TIME_PARAM);
 requireNonNull(lastFreshTime, "last refresh time is missing in token");
 return new Date(lastFreshTime);
}

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

private Optional<Token> validateToken(String tokenEncoded, HttpServletRequest request, HttpServletResponse response) {
 Optional<Claims> claims = jwtSerializer.decode(tokenEncoded);
 if (!claims.isPresent()) {
  return Optional.empty();
 }
 Date now = new Date(system2.now());
 Claims token = claims.get();
 if (now.after(addSeconds(token.getIssuedAt(), SESSION_DISCONNECT_IN_SECONDS))) {
  return Optional.empty();
 }
 jwtCsrfVerifier.verifyState(request, (String) token.get(CSRF_JWT_PARAM), token.getSubject());
 if (now.after(addSeconds(getLastRefreshDate(token), SESSION_REFRESH_IN_SECONDS))) {
  refreshToken(token, request, response);
 }
 Optional<UserDto> user = selectUserFromUuid(token.getSubject());
 if (!user.isPresent()) {
  return Optional.empty();
 }
 return Optional.of(new Token(user.get(), claims.get()));
}

代码示例来源:origin: apache/nifi

@Override
  public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
    final String identity = claims.getSubject();
    // Get the key based on the key id in the claims
    final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
    final Key key = keyService.getKey(keyId);
    // Ensure we were able to find a key that was previously issued by this key service for this user
    if (key == null || key.getKey() == null) {
      throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
    }
    return key.getKey().getBytes(StandardCharsets.UTF_8);
  }
}).parseClaimsJws(base64EncodedToken);

代码示例来源: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: mrdear/JavaWEB

/**
 * 从token中取出用户
 */
public TokenUserDTO parse(String token) {
 Claims claims = Jwts.parser()
   .setSigningKey(secret)
   .parseClaimsJws(token)
   .getBody();
 TokenUserDTO userDTO = new TokenUserDTO();
 userDTO.setId(NumberUtils.toLong(claims.getId()));
 userDTO.setAvatar(claims.get("avatar",String.class));
 userDTO.setUsername(claims.get("username",String.class));
 userDTO.setEmail(claims.get("email",String.class));
 userDTO.setRoles((List<String>) claims.get("roles"));
 return userDTO;
}

代码示例来源:origin: alibaba/nacos

/**
 * Get auth Info
 *
 * @param token token
 * @return auth info
 */
public Authentication getAuthentication(String token) {
  /**
   *  parse the payload of token
   */
  Claims claims = Jwts.parser()
    .setSigningKey(secretKey)
    .parseClaimsJws(token)
    .getBody();
  List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY));
  User principal = new User(claims.getSubject(), "", authorities);
  return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}

代码示例来源:origin: apache/usergrid

@Override
public Map<String, String> getDecodedTokenDetails(String token) throws Exception {
  Jws<Claims> jws = getClaims(token);
  Claims claims = jws.getBody();
  Map<String, String> tokenDetails = new HashMap<>();
  tokenDetails.put("username", (String)claims.get("user_name"));
  tokenDetails.put("email", (String)claims.get("email"));
  tokenDetails.put("expiry", claims.get("exp").toString());
  tokenDetails.put("user_id", claims.get("user_id").toString());
  return tokenDetails;
}

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

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
  Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey());
  String subject = jwsClaims.getBody().getSubject();
  List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
  List<GrantedAuthority> authorities = scopes.stream()
    .map(SimpleGrantedAuthority::new)
    .collect(Collectors.toList());
  
  UserContext context = UserContext.create(subject, authorities);
  
  return new JwtAuthenticationToken(context, context.getAuthorities());
}

代码示例来源:origin: stylefeng/Guns

/**
 * 获取私有的jwt claim
 */
public static String getPrivateClaimFromToken(String token, String key) {
  return getClaimFromToken(token).get(key).toString();
}

代码示例来源:origin: Exrick/x-boot

String authority = claims.get(SecurityConstant.AUTHORITIES).toString();

代码示例来源:origin: apache/usergrid

private void validateClaims (final Jws<Claims> claims) throws ExpiredTokenException {
  final Claims body = claims.getBody();
  final long expiry = Long.valueOf(body.get("exp").toString());
  if (expiry - (System.currentTimeMillis()/1000) < 0 ){
    final long expirationDelta = ((System.currentTimeMillis()/1000) - expiry)*1000;
    throw new ExpiredTokenException(String.format("Token expired %d milliseconds ago.", expirationDelta ));
  }
}

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

private void refreshToken(Claims token, HttpServletRequest request, HttpServletResponse response) {
 String refreshToken = jwtSerializer.refresh(token, sessionTimeoutInSeconds);
 response.addCookie(createCookie(request, JWT_COOKIE, refreshToken, sessionTimeoutInSeconds));
 jwtCsrfVerifier.refreshState(request, response, (String) token.get(CSRF_JWT_PARAM), sessionTimeoutInSeconds);
}

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

private void validateExpectedClaims(Header header, Claims claims) {
  for (String expectedClaimName : expectedClaims.keySet()) {
    Object expectedClaimValue = normalize(expectedClaims.get(expectedClaimName));
    Object actualClaimValue = normalize(claims.get(expectedClaimName));
    if (expectedClaimValue instanceof Date) {
      try {
        actualClaimValue = claims.get(expectedClaimName, Date.class);
      } catch (Exception e) {
        String msg = "JWT Claim '" + expectedClaimName + "' was expected to be a Date, but its value " +
          "cannot be converted to a Date using current heuristics.  Value: " + actualClaimValue;
        throw new IncorrectClaimException(header, claims, msg);
      }
    }
    InvalidClaimException invalidClaimException = null;
    if (actualClaimValue == null) {
      String msg = String.format(ClaimJwtException.MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE,
        expectedClaimName, expectedClaimValue);
      invalidClaimException = new MissingClaimException(header, claims, msg);
    } else if (!expectedClaimValue.equals(actualClaimValue)) {
      String msg = String.format(ClaimJwtException.INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE,
        expectedClaimName, expectedClaimValue, actualClaimValue);
      invalidClaimException = new IncorrectClaimException(header, claims, msg);
    }
    if (invalidClaimException != null) {
      invalidClaimException.setClaimName(expectedClaimName);
      invalidClaimException.setClaimValue(expectedClaimValue);
      throw invalidClaimException;
    }
  }
}

代码示例来源:origin: apache/usergrid

@Override
public UserInfo validateAndReturnUserInfo(String token, long ttl) throws Exception {
  Jws<Claims> payload = getClaims(token);
  // this step super important to ensure the token is a valid token
  validateClaims(payload);
  UserInfo userInfo = management.getAdminUserByEmail(payload.getBody().get("email").toString());
  return userInfo;
}

代码示例来源:origin: apache/usergrid

final long expiry = Long.valueOf( e.getClaims().get( "exp" ).toString() );
final long expirationDelta = ((System.currentTimeMillis() / 1000) - expiry) * 1000;
logger.debug(String.format("Apigee JWT Token expired %d milliseconds ago.", expirationDelta));

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

@Test
public void generate_token_with_property() {
 setSecretKey(A_SECRET_KEY);
 underTest.start();
 String token = underTest.encode(new JwtSession(USER_LOGIN, 10, ImmutableMap.of("custom", "property")));
 assertThat(token).isNotEmpty();
 Claims claims = underTest.decode(token).get();
 assertThat(claims.get("custom")).isEqualTo("property");
}

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

/**
 * Creates and validates Refresh token 
 * 
 * @param token
 * @param signingKey
 * 
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 * 
 * @return
 */
public static Optional<RefreshToken> create(RawAccessJwtToken token, String signingKey) {
  Jws<Claims> claims = token.parseClaims(signingKey);
  List<String> scopes = claims.getBody().get("scopes", List.class);
  if (scopes == null || scopes.isEmpty() 
      || !scopes.stream().filter(scope -> Scopes.REFRESH_TOKEN.authority().equals(scope)).findFirst().isPresent()) {
    return Optional.empty();
  }
  return Optional.of(new RefreshToken(claims));
}

代码示例来源:origin: pig4cloud/pig

/**
 * 根据请求heard中的token获取用户角色
 *
 * @param httpServletRequest request
 * @return 角色名
 */
public static List<String> getRole(HttpServletRequest httpServletRequest) {
  String token = getToken(httpServletRequest);
  String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
  Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
  List<String> roleNames = (List<String>) claims.get("authorities");
  return roleNames;
}

代码示例来源:origin: pig4cloud/pig

/**
 * 根据header中的token获取用户ID
 *
 * @param httpServletRequest
 * @return 用户ID
 */
public static Integer getUserId(HttpServletRequest httpServletRequest) {
  String token = getToken(httpServletRequest);
  String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
  Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
  Integer userId = (Integer) claims.get("userId");
  return userId;
}

代码示例来源:origin: yinjihuan/spring-cloud

/**
 * 检查Token是否合法
 * @param token
 * @return JWTResult
 */
public JWTResult checkToken(String token) {
  try {
    Claims claims = Jwts.parser().setSigningKey(pubKey).parseClaimsJws(token).getBody();
    String sub = claims.get("sub", String.class);
    return new JWTResult(true, sub, "合法请求", ResponseCode.SUCCESS_CODE.getCode());
  } catch (ExpiredJwtException e) {
    // 在解析JWT字符串时,如果‘过期时间字段’已经早于当前时间,将会抛出ExpiredJwtException异常,说明本次请求已经失效
    return new JWTResult(false, null, "token已过期", ResponseCode.TOKEN_TIMEOUT_CODE.getCode());
  } catch (SignatureException e) {
    // 在解析JWT字符串时,如果密钥不正确,将会解析失败,抛出SignatureException异常,说明该JWT字符串是伪造的
    return new JWTResult(false, null, "非法请求", ResponseCode.NO_AUTH_CODE.getCode());
  } catch (Exception e) {
    return new JWTResult(false, null, "非法请求", ResponseCode.NO_AUTH_CODE.getCode());
  }
}

相关文章