本文整理了Java中io.jsonwebtoken.Claims
类的一些代码示例,展示了Claims
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Claims
类的具体详情如下:
包路径:io.jsonwebtoken.Claims
类名称:Claims
[英]A JWT Claims set.
This is ultimately a JSON map and any values can be added to it, but JWT standard names are provided as type-safe getters and setters for convenience.
Because this interface extends Map<String, Object>, if you would like to add your own properties, you simply use map methods, for example:
claims.
Map#put(Object,Object)("someKey", "someValue");
It is easiest to create a Claims instance by calling one of the Jwts#claims() factory methods.
[中]一个JWTClaims set。
这最终是一个JSON映射,可以向其中添加任何值,但为了方便起见,JWT标准名称作为类型安全的getter和setter提供。
由于此接口扩展了Map<String,Object>,如果您想添加自己的属性,只需使用Map方法即可,例如:
claims.
Map#put(Object,Object)("someKey", "someValue");
####创作
通过调用Jwts#Claims()工厂方法之一,创建索赔实例最简单。
代码示例来源: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: 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 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: 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: com.arsframework/ars-core
/**
* 解析令牌
*
* @param code 令牌标识
* @return 令牌对象
*/
public static Token parse(String code) {
if (code == null) {
throw new IllegalArgumentException("Code must not be null");
}
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(code).getBody();
int timeout = (int) (claims.getExpiration().getTime() - claims.getIssuedAt().getTime());
return new Token(code, timeout, claims);
}
代码示例来源: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;
}
代码示例来源:origin: stormpath/stormpath-sdk-java
private String getUserId(String token) {
// if we have a signing key resolver use it to validate the token locally
// otherwise hit the introspect endpoint
if (signingKeyResolver != null) {
Jws<Claims> claims = Jwts.parser()
.setSigningKeyResolver(signingKeyResolver)
.parseClaimsJws(token);
return claims.getBody().get("uid", String.class);
}
return resolveAccessToken(token).getUid();
}
代码示例来源:origin: stormpath/stormpath-sdk-java
private int getMaxAge(String token, byte[] clientSecret, CookieConfig cookieConfig, HttpServletRequest request, HttpServletResponse response) {
// non-zero indicates override from cookie config
if (cookieConfig.getMaxAge() != 0 ) {
return cookieConfig.getMaxAge();
}
if(Strings.hasText(token) && token.split("\\.").length == 3) {
// otherwise, use the claims in the JWT to determine maxAge
Jws<Claims> claimsJws = Jwts.parser().setSigningKeyResolver(createKeyResolver(request, response)).parseClaimsJws(token);
DateTime issueAt = new DateTime(claimsJws.getBody().getIssuedAt());
DateTime expiration = new DateTime(claimsJws.getBody().getExpiration());
return Seconds.secondsBetween(issueAt, expiration).getSeconds() - Seconds.secondsBetween(issueAt, DateTime.now()).getSeconds();
}
return DEFAULT_COOKIE_MAX_AGE;
}
代码示例来源:origin: prestodb/presto
@Override
public Principal authenticate(HttpServletRequest request)
throws AuthenticationException
{
String header = nullToEmpty(request.getHeader(AUTHORIZATION));
int space = header.indexOf(' ');
if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) {
throw needAuthentication(null);
}
String token = header.substring(space + 1).trim();
if (token.isEmpty()) {
throw needAuthentication(null);
}
try {
Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
String subject = claimsJws.getBody().getSubject();
return new BasicPrincipal(subject);
}
catch (JwtException e) {
throw needAuthentication(e.getMessage());
}
catch (RuntimeException e) {
throw new RuntimeException("Authentication error", e);
}
}
代码示例来源: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: 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: apache/nifi
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
// The library representations of the JWT should be kept internal to this service.
try {
final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);
if (jws == null) {
throw new JwtException("Unable to parse token");
}
// Additional validation that subject is present
if (StringUtils.isEmpty(jws.getBody().getSubject())) {
throw new JwtException("No subject available in token");
}
// TODO: Validate issuer against active registry?
if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
throw new JwtException("No issuer available in token");
}
return jws.getBody().getSubject();
} catch (JwtException e) {
logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
final String errorMessage = "There was an error validating the JWT";
logger.error(errorMessage, e);
throw e;
}
}
代码示例来源:origin: eclipse/hono
@Override
public Instant getExpirationTime() {
return expandedToken.getBody().getExpiration().toInstant();
}
}
代码示例来源:origin: line/line-sdk-android
@NonNull
private static LineIdToken buildIdToken(final Claims claims) {
return new LineIdToken.Builder()
.issuer(claims.getIssuer())
.subject(claims.getSubject())
.audience(claims.getAudience())
.expiresAt(claims.getExpiration())
.issuedAt(claims.getIssuedAt())
.authTime(claims.get("auth_time", Date.class))
.nonce(claims.get("nonce", String.class))
.name(claims.get("name", String.class))
.picture(claims.get("picture", String.class))
.phoneNumber(claims.get("phone_number", String.class))
.email(claims.get("email", String.class))
.gender(claims.get("gender", String.class))
.birthdate(claims.get("birthdate", String.class))
.address(buildAddress(claims))
.givenName(claims.get("given_name", String.class))
.givenNamePronunciation(claims.get("given_name_pronunciation", String.class))
.middleName(claims.get("middle_name", String.class))
.familyName(claims.get("family_name", String.class))
.familyNamePronunciation(claims.get("family_name_pronunciation", String.class))
.build();
}
代码示例来源:origin: svlada/springboot-security-jwt
public String getSubject() {
return claims.getBody().getSubject();
}
}
代码示例来源: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 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: hs-web/hsweb-framework
try {
Claims claims = parseJWT(headerToken);
if (claims.getExpiration().getTime() <= System.currentTimeMillis()) {
return JSON.parseObject(claims.getSubject(), JwtAuthorizedToken.class);
} catch (ExpiredJwtException e) {
return null;
内容来源于网络,如有侵权,请联系作者删除!