本文整理汇总了Java中io.jsonwebtoken.Claims类的典型用法代码示例。如果您正苦于以下问题:Java Claims类的具体用法?Java Claims怎么用?Java Claims使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Claims类属于io.jsonwebtoken包,在下文中一共展示了Claims类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createRefreshToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
public JwtToken createRefreshToken(UserContext userContext) {
if (StringUtils.isBlank(userContext.getTenantId()))
throw new IllegalArgumentException("Cannot create JWT Token without tenantId");
if (StringUtils.isBlank(userContext.getOrgId()))
throw new IllegalArgumentException("Cannot create JWT Token without orgId");
DateTime currentTime = new DateTime();
Claims claims = Jwts.claims().setSubject(userContext.getOrgId());
claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
claims.put("tenant", userContext.getTenantId());
String token = Jwts.builder()
.setClaims(claims)
.setIssuer(settings.getTokenIssuer())
.setId(UUID.randomUUID().toString())
.setIssuedAt(currentTime.toDate())
.setExpiration(currentTime.plusMinutes(settings.getRefreshTokenExpTime()).toDate())
.signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
.compact();
return new AccessJwtToken(token, claims);
}
示例2: getConnUser
import io.jsonwebtoken.Claims; //导入依赖的package包/类
public static RequestUserDTO getConnUser(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token == null) {
token = getTokenFromCookis(request);
}
if (token != null) {
// 解析 Token
Claims claims = Jwts.parser().setSigningKey(SECRET)
.parseClaimsJws(token).getBody();
return new RequestUserDTO(
claims.get("DomainId", String.class),
claims.get("UserId", String.class),
claims.get("OrgUnitId", String.class));
}
return new RequestUserDTO();
}
示例3: doFilter
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
throw new ServletException("Missing or invalid Authorization header.");
}
final String token = authHeader.substring(7); // The part after "Bearer "
try {
final Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
}
catch (final SignatureException e) {
throw new ServletException("Invalid token.");
}
chain.doFilter(req, res);
}
示例4: authenticate
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
final JwtToken token = (JwtToken) authentication.getCredentials();
final Claims claims = jwt.validate(token);
final String userId = claims.getSubject();
final String email = claims.get("mail", String.class);
@SuppressWarnings("unchecked")
final List<String> scopes = (List<String>) claims.get("scopes", List.class);
final List<GrantedAuthority> auths = scopes.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
final JwtUserDetails user = new JwtUserDetails(userId, email, auths);
return new JwtAuthentication(token, user);
}
示例5: sign_token_with_KMS_and_verify
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@Test
public void sign_token_with_KMS_and_verify() throws Exception {
String[] params = {
"--region", TEST_AWS_REGION,
"--key", TEST_AWS_KEY_ARN,
"--username", "userXYZ",
"--journey", "SUM,UPR",
};
GenerateTokenApp.main(params);
String jwtToken = getTokenFromStdout();
System.out.println("jwt: "+jwtToken);
KMSDecrypt kmsDecrypt = new KMSDecrypt(KMS_CLIENT, Collections.singleton(TEST_AWS_KEY_ARN));
Claims claims = new JWTDecoder(kmsDecrypt).decodeAndVerify(jwtToken);
assertThat(claims.get("usr"), is("userXYZ"));
}
示例6: getEnterpriseToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
/**
* Get the enterprise token witch can used to invoke admin api,such as managing departments and groups
*
* @param enterpriseId Your enterprise id
* @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60)
* @return Detailed user access information
* @throws YfyException
*/
public YfyAuthFinish getEnterpriseToken(long enterpriseId, int expirationTimeSeconds) throws YfyException {
Claims claims = new DefaultClaims();
claims.put("yifangyun_sub_type", "enterprise");
claims.setSubject(String.valueOf(enterpriseId));
claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds));
claims.setIssuedAt(new Date());
claims.setId(getGeneratedJwtId(16));
final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact();
return YfyRequestUtil.doPostInAuth(
requestConfig,
YfyAppInfo.getHost().getAuth(),
"oauth/token",
new HashMap<String, String>() {{
put("grant_type", "jwt");
put("assertion", compactJws);
}},
YfyAuthFinish.class);
}
示例7: refreshAuthenticationToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
/**
* Clients should call this in order to refresh a JWT.
*
* @param request the request from the client.
* @return the JWT with an extended expiry time if the client was authenticated, a 400 Bad Request otherwise.
*/
@RequestMapping(value = "/refresh", method = RequestMethod.GET)
public ResponseEntity<?> refreshAuthenticationToken(HttpServletRequest request) {
final String authorizationHeader = request.getHeader("Authorization");
final Claims claims = jwtUtils.validateTokenAndGetClaims(authorizationHeader);
final String username = jwtUtils.getUsernameFromTokenClaims(claims);
final JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);
if (jwtUtils.canTokenBeRefreshed(claims, new Date(user.getLastPasswordResetDate()))) {
final String refreshedToken = jwtUtils.refreshToken(authorizationHeader);
return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
} else {
return ResponseEntity.badRequest().body(null);
}
}
示例8: getCaptcha
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@GetMapping("/specials/captcha")
public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
Claims claims = (Claims) request.getAttribute(AppConstants.CLAIMS);
// 缓存验证码数值
CaptchaGenerator instance = CaptchaGenerator.INSTANCE;
BufferedImage bi = instance.genImage();
specialService.saveCaptcha(claims, instance.getCaptcha());
// 输出验证码图片
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/JPEG");
ImageIO.write(bi, "JPEG", response.getOutputStream());
response.getOutputStream().flush();
}
示例9: parseTokenFromBase64EncodedString
import io.jsonwebtoken.Claims; //导入依赖的package包/类
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@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 String keyId = claims.get(KEY_ID_CLAIM, String.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);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
示例10: createJwtToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@Override
public String createJwtToken(Authentication authentication, int minutes) {
Claims claims = Jwts.claims()
.setId(String.valueOf(IdentityGenerator.generate()))
.setSubject(authentication.getName())
.setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000))
.setIssuedAt(new Date());
String authorities = authentication.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.map(String::toUpperCase)
.collect(Collectors.joining(","));
claims.put(AUTHORITIES, authorities);
return Jwts.builder()
.setClaims(claims)
.signWith(HS512, secretkey)
.compact();
}
示例11: authenticate
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey());
String orgId = jwsClaims.getBody().getSubject();
String tenantId = jwsClaims.getBody().get("tenant", String.class);
List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
List<GrantedAuthority> authorities = scopes.stream()
.map(authority -> new SimpleGrantedAuthority(authority))
.collect(Collectors.toList());
UserContext context = UserContext.create(tenantId, orgId, authorities);
return new JwtAuthenticationToken(context, context.getAuthorities());
}
示例12: executeSignOut
import io.jsonwebtoken.Claims; //导入依赖的package包/类
@Override
public JsonResult executeSignOut(HttpServletRequest request, HttpServletResponse response) {
JsonResult result = new JsonResult();
Cookie tokenCookie = CookieUtil.getCookieByName(request, AppConstants.ACCESS_TOKEN);
if (tokenCookie != null) {
Claims requestClaims = JwtTokenUtil.getClaims(tokenCookie.getValue(), appProperties.getJwtSecretKey());
// 清除缓存
String cacheKey = AppConstants.CACHE_ACCESS_TOKEN + requestClaims.getAudience();
byteRedisClient.del(cacheKey);
}
// 清除Cookie
CookieUtil.removeCookie(AppConstants.ACCESS_TOKEN, "lovexq.net", response);
CookieUtil.removeCookie(AppConstants.USER_NAME, "lovexq.net", response);
return result;
}
示例13: getAudienceFromToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
public String getAudienceFromToken(String token) {
String audience;
try {
final Claims claims = getClaimsFromToken(token);
audience = (String) claims.get(CLAIM_KEY_AUDIENCE);
} catch (Exception e) {
audience = null;
}
return audience;
}
示例14: getAudienceFromToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
/**
* @param token
* @return
*/
public String getAudienceFromToken ( String token ) {
String audience;
try {
final Claims claims = getClaimsFromToken( token );
audience = ( String ) claims.get( CLAIM_KEY_AUDIENCE );
} catch ( Exception e ) {
audience = null;
}
return audience;
}
示例15: getClaimsFromToken
import io.jsonwebtoken.Claims; //导入依赖的package包/类
private Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}