本文整理了Java中io.jsonwebtoken.Claims.getSubject()
方法的一些代码示例,展示了Claims.getSubject()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Claims.getSubject()
方法的具体详情如下:
包路径:io.jsonwebtoken.Claims
类名称:Claims
方法名:getSubject
[英]Returns the JWT sub
(subject) value or null if not present.
[中]返回JWTsub
(主题)值,如果不存在,则返回null。
代码示例来源:origin: macrozheng/mall
/**
* 从token中获取登录用户名
*/
public String getUserNameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
代码示例来源:origin: stylefeng/Guns
/**
* 获取用户名从token中
*/
public static String getUsernameFromToken(String token) {
return getClaimFromToken(token).getSubject();
}
代码示例来源:origin: hs-web/hsweb-framework
return JSON.parseObject(claims.getSubject(), JwtAuthorizedToken.class);
} catch (ExpiredJwtException e) {
return null;
代码示例来源: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: 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: 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/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: 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: 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: 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: zhangxd1989/springboot-dubbox
/**
* 获取用户名
*
* @param token Token
* @return String
*/
public String getUsernameFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims != null ? claims.getSubject() : null;
}
代码示例来源:origin: svlada/springboot-security-jwt
public String getSubject() {
return claims.getBody().getSubject();
}
}
代码示例来源: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: Exrick/x-boot
username = claims.getSubject();
代码示例来源:origin: bfwg/springboot-jwt-starter
public String getUsernameFromToken(String token) {
String username;
try {
final Claims claims = this.getAllClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
代码示例来源:origin: xkcoding/spring-boot-demo
/**
* 根据 jwt 获取用户名
*
* @param jwt JWT
* @return 用户名
*/
public String getUsernameFromJWT(String jwt) {
Claims claims = parseJWT(jwt);
return claims.getSubject();
}
代码示例来源:origin: apache/james-project
public String extractLogin(String token) throws JwtException {
Jws<Claims> jws = parseToken(token);
return jws
.getBody()
.getSubject();
}
代码示例来源:origin: javaee-samples/javaee8-samples
public JWTCredential getCredential(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
Set<String> authorities
= Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(","))
.stream()
.collect(Collectors.toSet());
return new JWTCredential(claims.getSubject(), authorities);
}
代码示例来源:origin: com.quhaodian.discover/discover-user
public static Long getMember(String token) {
Long result = null;
try {
Jws<Claims> c = Jwts.parser().setSigningKey(base64key).parseClaimsJws(token);
result = Long.parseLong(c.getBody().getSubject());
} catch (Exception e) {
}
return result;
}
内容来源于网络,如有侵权,请联系作者删除!