本文整理匯總了Java中io.jsonwebtoken.Jwts類的典型用法代碼示例。如果您正苦於以下問題:Java Jwts類的具體用法?Java Jwts怎麽用?Java Jwts使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Jwts類屬於io.jsonwebtoken包,在下文中一共展示了Jwts類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: Verify
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
public static boolean Verify(String jwt, String type) throws Exception {
try{
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY))
.parseClaimsJws(jwt).getBody();
//verifica se o issuer é igual ao type
return claims.getIssuer().equals(type);
} catch (ExpiredJwtException | MalformedJwtException | SignatureException
| UnsupportedJwtException | IllegalArgumentException e) {
System.out.println(e.getMessage());
return false;
}
}
示例2: doFilter
import io.jsonwebtoken.Jwts; //導入依賴的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 ")) {
ExceptionUtils.createUnauthorizedException("Missing or invalid Authorization header.", res);
return;
}
try {
final String token = authHeader.substring(7); // The part after "Bearer "
final Claims claims =
Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
} catch (final Exception e) {
ExceptionUtils.createUnauthorizedException("Invalid token", res);
return;
}
chain.doFilter(req, res);
}
示例3: getConnUser
import io.jsonwebtoken.Jwts; //導入依賴的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();
}
示例4: encode
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
public static String encode(String subject, ArrayList<String> roles) {
// prepare expiration date according to application properties
Date expDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(expDate);
int unit;
switch (applicationProperties.getTokenExpiration().getUnit()) {
case "SECOND":
unit = Calendar.SECOND;
break;
case "MINUTE":
unit = Calendar.MINUTE;
break;
default:
unit = Calendar.HOUR;
}
calendar.add(unit, applicationProperties.getTokenExpiration().getValue());
expDate = calendar.getTime();
return Jwts.builder().setSubject(subject).claim("roles", roles).setIssuedAt(new Date()).setExpiration(expDate)
.signWith(SignatureAlgorithm.HS256, key).compact();
}
示例5: authenticate
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
@Override
public JwtToken authenticate(Authentication authentication) throws AuthenticationException {
JwtToken token = (JwtToken) authentication;
if (token.getPrincipal() instanceof String) {
try {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws((String) token.getPrincipal())
.getBody();
UserDetails user = handler.parseClaims(claims);
return new JwtToken(user, claims, user.getAuthorities());
} catch (ClaimJwtException ex) {
throw new BadCredentialsException("JWT error", ex);
}
} else {
return null;
}
}
示例6: preHandle
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object) throws Exception {
String authHeader = request.getHeader("authorization");
if (!"OPTIONS".equals(request.getMethod())) {
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
throw new JwtAuthException();
}
String token = authHeader.substring(7);
try {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
AuthContext.addClaims(claims);
} catch (Exception e) {
LOG.error("JWT parse error.", e);
throw new JwtAuthException(e);
}
}
return true;
}
示例7: createRefreshToken
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
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(AppConfig.prop.getProperty("security.tokenIssuer"))
.setId(UUID.randomUUID().toString())
.setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
.setExpiration(Date.from(currentTime
.plusMinutes(Long.parseLong(AppConfig.prop.getProperty("security.refreshTokenExpTime")))
.atZone(ZoneId.systemDefault()).toInstant()))
.signWith(SignatureAlgorithm.HS512, AppConfig.prop.getProperty("security.tokenSigningKey"))
.compact();
return new AccessJwtToken(token, claims);
}
示例8: parseTokenFromBase64EncodedString
import io.jsonwebtoken.Jwts; //導入依賴的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);
}
}
示例9: generateNewDeploymentToken
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private static void generateNewDeploymentToken(File tokenFile) throws IOException {
deploymentHash = Util.computeSHA256(serverID);
JSONObject root = new JSONObject();
root.put("timestamp", System.currentTimeMillis());
root.put("hash", deploymentHash);
String jwt = Jwts.builder()
.setPayload(root.toJSONString())
.signWith(SignatureAlgorithm.ES384, configuration.getServerPrivateKey())
.compact(); // Sign and build the JWT
Util.putFileContents(jwt, tokenFile);
logger.info("Generated new deployment token.");
}
示例10: getAuthentication
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
public static Authentication getAuthentication(HttpServletRequest request) {
// 從Header中拿到token
String token = request.getHeader(HEADER_STRING);
if (token == null) {
token = getTokenFromCookis(request);
}
if (token != null && !token.isEmpty()) {
// 解析 Token
Claims claims = Jwts.parser().setSigningKey(SECRET)
.parseClaimsJws(token).getBody();
// 獲取用戶名
String user = claims.get("UserId").toString();
// 獲取權限(角色)
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
// 返回驗證令牌
return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
}
return null;
}
示例11: generate
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
@Override
public TokenDto generate(final String username, final String password) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
throw new BadCredentialsException("Input data can't be empty.");
}
final User user = userService.findByUsername(username);
validateInputPassword(user.getPassword(), password);
final Map<String, Object> tokenData = new HashMap<>();
tokenData.put("username", user.getUsername());
tokenData.put("password", user.getPassword());
tokenData.put("create_date", LocalDateTime.now());
final JwtBuilder jwtBuilder = Jwts.builder();
jwtBuilder.setClaims(tokenData);
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, expirationTime);
jwtBuilder.setExpiration(calendar.getTime());
final String token = jwtBuilder.signWith(SignatureAlgorithm.HS512, secretKey).compact();
return new TokenDto(token, mapper.map(user, UserDto.class));
}
示例12: getEnterpriseToken
import io.jsonwebtoken.Jwts; //導入依賴的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);
}
示例13: getUserToken
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
/**
* Get the user token witch can used to invoke personal api,such as get folder information
*
* @param userId The user you want to operate with
* @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60)
* @return Detailed user access information
* @throws YfyException
*/
public YfyAuthFinish getUserToken(long userId, int expirationTimeSeconds) throws YfyException {
Claims claims = new DefaultClaims();
claims.put("yifangyun_sub_type", "user");
claims.setSubject(String.valueOf(userId));
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);
}
示例14: addAuthentication
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
static void addAuthentication(HttpServletResponse response, String username) {
// 生成JWT
String JWT = Jwts.builder()
// 保存權限(角色)
.claim("authorities", "READ")
// 用戶名寫入標題
.setSubject(username)
// 有效期設置
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
// 簽名設置
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
// 將 JWT 寫入 body
try {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print("{\"token\":\"" + JWT + "\"}");
} catch (IOException e) {
e.printStackTrace();
}
}
示例15: addAuthentication
import io.jsonwebtoken.Jwts; //導入依賴的package包/類
void addAuthentication(HttpServletResponse response, String username, Collection<? extends GrantedAuthority> authorities) throws IOException {
List<String> roles = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
Claims claims = Jwts.claims()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + expirationTime * 60 * 1000));
claims.put(ROLE_KEY, roles.stream().collect(Collectors.joining(ROLE_DELIMITER)));
String JWT = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
response.addHeader(headerString, headerStartWith + JWT);
JwtAuthenticatedUser user = new JwtAuthenticatedUser(username, roles);
PrintWriter printWriter = response.getWriter();
printWriter.print(mapper.writeValueAsString(user));
printWriter.flush();
}