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

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

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

Claims.getId介绍

[英]Returns the JWTs jti (JWT ID) value or null if not present.

This value is a CaSe-SenSiTiVe unique identifier for the JWT. If available, this value is expected to be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object. The ID can be used to prevent the JWT from being replayed.
[中]

代码示例

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

Optional<Claims> decode(String token) {
 checkIsStarted();
 Claims claims = null;
 try {
  claims = Jwts.parser()
   .setSigningKey(secretKey)
   .parseClaimsJws(token)
   .getBody();
  requireNonNull(claims.getId(), "Token id hasn't been found");
  requireNonNull(claims.getSubject(), "Token subject hasn't been found");
  requireNonNull(claims.getExpiration(), "Token expiration date hasn't been found");
  requireNonNull(claims.getIssuedAt(), "Token creation date hasn't been found");
  return Optional.of(claims);
 } catch (ExpiredJwtException | SignatureException e) {
  return Optional.empty();
 } catch (Exception e) {
  throw AuthenticationException.newBuilder()
   .setSource(Source.jwt())
   .setLogin(claims == null ? null : claims.getSubject())
   .setMessage(e.getMessage())
   .build();
 }
}

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

@Test
public void decode_token() {
 setSecretKey(A_SECRET_KEY);
 underTest.start();
 Date now = new Date();
 String token = underTest.encode(new JwtSession(USER_LOGIN, 20 * 60));
 Claims claims = underTest.decode(token).get();
 assertThat(claims.getId()).isNotEmpty();
 assertThat(claims.getSubject()).isEqualTo(USER_LOGIN);
 assertThat(claims.getExpiration()).isNotNull();
 assertThat(claims.getIssuedAt()).isNotNull();
 // Check expiration date it set to more than 19 minutes in the future
 assertThat(claims.getExpiration()).isAfterOrEqualsTo(new Date(now.getTime() + 19 * 60 * 1000));
}

代码示例来源: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 String getJti() {
  return claims.getBody().getId();
}

代码示例来源: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: Apereo-Learning-Analytics-Initiative/OpenLRW

public String getJti() {
  return claims.getBody().getId();
}

代码示例来源:origin: stormpath/stormpath-sdk-java

private void uncacheRevokedToken(Map<String, Object> data) {
  String token = data.get(OAuthTokenRevocationAttempt.TOKEN.getName()).toString();
  int signatureIndex = token.lastIndexOf('.');
  if (signatureIndex <= 0) {
    return;
  }
  Object typeObject = data.get(OAuthTokenRevocationAttempt.TOKEN_TYPE_HINT.getName());
  String tokenTypeHint = null;
  if (typeObject instanceof String) {
    tokenTypeHint = typeObject.toString();
  }
  try {
    String nonSignedToken = token.substring(0, signatureIndex + 1);
    Jwt<Header, Claims> jwt = Jwts.parser().parseClaimsJwt(nonSignedToken);
    Object stt = jwt.getHeader().get("stt");
    String rti = null;
    Claims body = jwt.getBody();
    if ("refresh".equals(stt) || "refresh_token".equals(tokenTypeHint)) {
      rti = body.getId();
    } else if ("access".equals(stt) || "access_token".equals(tokenTypeHint)) {
      rti = body.get("rti", String.class);
    }
    if (rti != null) {
      String href = baseUrlResolver.getBaseUrl() + "/refreshTokens/" + rti;
      uncache(href, RefreshToken.class);
    }
  } catch (Exception e) {//ignored
  }
}

代码示例来源:origin: com.stormpath.sdk/stormpath-sdk-impl

private void uncacheRevokedToken(Map<String, Object> data) {
  String token = data.get(OAuthTokenRevocationAttempt.TOKEN.getName()).toString();
  int signatureIndex = token.lastIndexOf('.');
  if (signatureIndex <= 0) {
    return;
  }
  Object typeObject = data.get(OAuthTokenRevocationAttempt.TOKEN_TYPE_HINT.getName());
  String tokenTypeHint = null;
  if (typeObject instanceof String) {
    tokenTypeHint = typeObject.toString();
  }
  try {
    String nonSignedToken = token.substring(0, signatureIndex + 1);
    Jwt<Header, Claims> jwt = Jwts.parser().parseClaimsJwt(nonSignedToken);
    Object stt = jwt.getHeader().get("stt");
    String rti = null;
    Claims body = jwt.getBody();
    if ("refresh".equals(stt) || "refresh_token".equals(tokenTypeHint)) {
      rti = body.getId();
    } else if ("access".equals(stt) || "access_token".equals(tokenTypeHint)) {
      rti = body.get("rti", String.class);
    }
    if (rti != null) {
      String href = baseUrlResolver.getBaseUrl() + "/refreshTokens/" + rti;
      uncache(href, RefreshToken.class);
    }
  } catch (Exception e) {//ignored
  }
}

代码示例来源:origin: lzh-boy/cskit

public static Claims parseJWT(String jwt) {

    //This line will throw an exception if it is not a signed JWS (as expected)

    JwsHeader claims1 = Jwts.parser()
        .setSigningKey(DatatypeConverter.parseBase64Binary(SIGN))
        .parseClaimsJws(jwt).getHeader();

    Claims claims = Jwts.parser()
        .setSigningKey(DatatypeConverter.parseBase64Binary(SIGN))
        .parseClaimsJws(jwt).getBody();

//        createJWT()
    System.out.println("ID: " + claims.getId());
    System.out.println("Subject: " + claims.getSubject());
    System.out.println("Issuer: " + claims.getIssuer());
    System.out.println("Expiration: " + claims.getExpiration());
    return claims;
  }
}

代码示例来源:origin: com.stormpath.sdk/stormpath-sdk-impl

public RefreshToken getAsRefreshToken() {

    String refreshToken;

    if ((refreshToken = getRefreshToken()) == null) {
      return null;
    }

    // okta refresh tokens are NOT JWTs
    if (refreshToken.split("\\.").length == 1) {
      return null;
    }

    Jws<Claims> jws = AbstractBaseOAuthToken.parseJws(refreshToken, getDataStore());
    Map<String, Object> props = new LinkedHashMap<>(1);
    String refreshTokenID = jws.getBody().getId();
    props.put("href", getDataStore().getBaseUrl() + "/refreshTokens/" + refreshTokenID);
    return getDataStore().instantiate(RefreshToken.class, props);
  }
}

代码示例来源:origin: stormpath/stormpath-sdk-java

public RefreshToken getAsRefreshToken() {

    String refreshToken;

    if ((refreshToken = getRefreshToken()) == null) {
      return null;
    }

    // okta refresh tokens are NOT JWTs
    if (refreshToken.split("\\.").length == 1) {
      return null;
    }

    Jws<Claims> jws = AbstractBaseOAuthToken.parseJws(refreshToken, getDataStore());
    Map<String, Object> props = new LinkedHashMap<>(1);
    String refreshTokenID = jws.getBody().getId();
    props.put("href", getDataStore().getBaseUrl() + "/refreshTokens/" + refreshTokenID);
    return getDataStore().instantiate(RefreshToken.class, props);
  }
}

代码示例来源:origin: stormpath/stormpath-sdk-java

@Override
  public boolean isValidCsrfToken(HttpServletRequest request, HttpServletResponse response, String csrfToken) {

    if (csrfToken == null) {
      return false;
    }

    try {
      Jws<Claims> jws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(csrfToken);

      //signature is valid, now let's ensure it hasn't been submitted before:

      String id = jws.getBody().getId();

      String usedNonce = nonceCache.get(id);

      if (usedNonce == null) {
        //CSRF token hasn't been used yet, mark it as used:
        nonceCache.put(id, csrfToken);
        return true;
      }
    } catch (Exception e) {
      log.debug("CSRF token is invalid (this is likely to happen and not an error condition).", e);
    }

    return false;
  }
}

代码示例来源:origin: com.stormpath.sdk/stormpath-sdk-servlet

@Override
  public boolean isValidCsrfToken(HttpServletRequest request, HttpServletResponse response, String csrfToken) {

    if (csrfToken == null) {
      return false;
    }

    try {
      Jws<Claims> jws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(csrfToken);

      //signature is valid, now let's ensure it hasn't been submitted before:

      String id = jws.getBody().getId();

      String usedNonce = nonceCache.get(id);

      if (usedNonce == null) {
        //CSRF token hasn't been used yet, mark it as used:
        nonceCache.put(id, csrfToken);
        return true;
      }
    } catch (Exception e) {
      log.debug("CSRF token is invalid (this is likely to happen and not an error condition).", e);
    }

    return false;
  }
}

代码示例来源:origin: org.sonarsource.sonarqube/sonar-server

Optional<Claims> decode(String token) {
 checkIsStarted();
 Claims claims = null;
 try {
  claims = Jwts.parser()
   .setSigningKey(secretKey)
   .parseClaimsJws(token)
   .getBody();
  requireNonNull(claims.getId(), "Token id hasn't been found");
  requireNonNull(claims.getSubject(), "Token subject hasn't been found");
  requireNonNull(claims.getExpiration(), "Token expiration date hasn't been found");
  requireNonNull(claims.getIssuedAt(), "Token creation date hasn't been found");
  return Optional.of(claims);
 } catch (ExpiredJwtException | SignatureException e) {
  return Optional.empty();
 } catch (Exception e) {
  throw AuthenticationException.newBuilder()
   .setSource(Source.jwt())
   .setLogin(claims == null ? null : claims.getSubject())
   .setMessage(e.getMessage())
   .build();
 }
}

代码示例来源:origin: getheimdall/heimdall

public Authentication getAuthentication(HttpServletRequest request, HttpServletResponse response) {
  String token = request.getHeader(HEIMDALL_AUTHORIZATION_NAME);
  if (token != null && !token.isEmpty()) {
    token = token.replace(TOKEN_PREFIX, "");
    // faz parse do token
    try {
      Claims claims = Jwts.parser()
          .setSigningKey(jwtProperty.getSecret())
          .parseClaimsJws(token)
          .getBody();
      String user = claims.getSubject();
      if (user != null) {
        if (!credentialStateService.verifyIfTokenIsRevokeOrLogout(claims.getId())) {
          User userFound = userService.findByUsername(user);
          addAuthentication(response, user, claims.getId());
          return new UsernamePasswordAuthenticationToken(userFound.getUserName(), userFound.getPassword(), getAuthoritiesByRoles(userFound.getRoles()));
        }
        return null;
      }
    } catch (ExpiredJwtException ex) {
      credentialStateService.logout(token);
      ExceptionMessage.TOKEN_EXPIRED.raise();
    }
  }
  return null;
}

代码示例来源:origin: craftingjava/springuni-particles

@Override
protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
 try {
  Claims claims = Jwts.parser()
    .setSigningKey(getKey())
    .parseClaimsJws(cookieValue)
    .getBody();
  return new String[] { claims.getId(), claims.getSubject() };
 } catch (JwtException e) {
  LOGGER.warn(e.getMessage());
  throw new InvalidCookieException(e.getMessage());
 }
}

代码示例来源:origin: stormpath/stormpath-sdk-java

int accessTokenIdStartingPoint = accessTokenHref.lastIndexOf("/") + 1;
accessTokenHref = accessTokenHref.substring(0, accessTokenIdStartingPoint);
accessTokenHref = accessTokenHref + claims.getId();

代码示例来源:origin: com.stormpath.sdk/stormpath-sdk-impl

int accessTokenIdStartingPoint = accessTokenHref.lastIndexOf("/") + 1;
accessTokenHref = accessTokenHref.substring(0, accessTokenIdStartingPoint);
accessTokenHref = accessTokenHref + claims.getId();

代码示例来源:origin: songxinjianqwe/EShop-SOA

@Override
public TokenCheckResult checkToken(String token) {
  if (token == null) {
    return new TokenCheckResult.TokenCheckResultBuilder().inValid().exception(new TokenStateInvalidException(TokenState.NOT_FOUND.toString())).build();
  }
  Claims claims;
  try {
    claims = Jwts.parser()
        .setSigningKey(DatatypeConverter.parseBase64Binary(authenticationProperties.getSecretKey()))
        .parseClaimsJws(token).getBody();
  } catch (ExpiredJwtException e) {
    log.info("Token过期 {}",token);
    return new TokenCheckResult.TokenCheckResultBuilder().inValid().exception(new TokenStateInvalidException(TokenState.EXPIRED.toString())).build();
  } catch (Exception e) {
    return new TokenCheckResult.TokenCheckResultBuilder().inValid().exception(new TokenStateInvalidException(TokenState.INVALID.toString())).build();
  }
  String username = claims.getId();
  String cachedToken = redisCacheManager.get(String.valueOf(username.hashCode()), String.class);
  if (cachedToken == null || !cachedToken.equals(token)) {
    return new TokenCheckResult.TokenCheckResultBuilder().inValid().exception(new TokenStateInvalidException(TokenState.INVALID.toString())).build();
  }
  return new TokenCheckResult.TokenCheckResultBuilder().valid().username(username).build();
}

代码示例来源:origin: tomsun28/bootshiro

/**
 * 验签JWT
 *
 * @param jwt json web token
 */
public static JwtAccount parseJwt(String jwt, String appKey) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
  Claims claims = Jwts.parser()
      .setSigningKey(DatatypeConverter.parseBase64Binary(appKey))
      .parseClaimsJws(jwt)
      .getBody();
  JwtAccount jwtAccount = new JwtAccount();
  jwtAccount.setTokenId(claims.getId());// 令牌ID
  jwtAccount.setAppId(claims.getSubject());// 客户标识
  jwtAccount.setIssuer(claims.getIssuer());// 签发者
  jwtAccount.setIssuedAt(claims.getIssuedAt());// 签发时间
  jwtAccount.setAudience(claims.getAudience());// 接收方
  jwtAccount.setRoles(claims.get("roles", String.class));// 访问主张-角色
  jwtAccount.setPerms(claims.get("perms", String.class));// 访问主张-权限
  return jwtAccount;
}

相关文章