下面列出了org.hamcrest.collection.IsEmptyCollection#com.auth0.jwt.JWT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public User verifyToken(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(this.engine.getApiSecret());
JWTVerifier verifier =
JWT.require(algorithm).withIssuer(ISSUER).build(); // Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
var user = PersistenceManager.getInstance().getById(User.class, jwt.getSubject());
if (user == null) {
throw new NotAuthorizedException(ERROR_MESSAGE_USER_NOT_FOUND);
}
return user;
} catch (JWTVerificationException ex) {
throw new NotAuthorizedException("Invalid token", ex);
}
}
@Test
public void shouldThrowWhenThePublicKeyIsInvalid() throws Exception {
exception.expect(SignatureVerificationException.class);
exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: some-alg");
exception.expectCause(isA(InvalidKeyException.class));
CryptoHelper crypto = mock(CryptoHelper.class);
when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(String.class), any(String.class), any(byte[].class)))
.thenThrow(InvalidKeyException.class);
RSAPublicKey publicKey = mock(RSAPublicKey.class);
RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
String jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
algorithm.verify(JWT.decode(jwt));
}
@Test
public void shouldThrowOnVerifyWhenThePublicKeyIsInvalid() throws Exception {
exception.expect(SignatureVerificationException.class);
exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: some-alg");
exception.expectCause(isA(InvalidKeyException.class));
CryptoHelper crypto = mock(CryptoHelper.class);
when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(String.class), any(String.class), any(byte[].class)))
.thenThrow(InvalidKeyException.class);
ECPublicKey publicKey = mock(ECPublicKey.class);
ECPrivateKey privateKey = mock(ECPrivateKey.class);
ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey);
Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider);
String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
algorithm.verify(JWT.decode(jwt));
}
JwtBasedSamlRequestIdManager(String issuer, Algorithm algorithm,
int validSeconds, int leewaySeconds) {
this.issuer = requireNonNull(issuer, "issuer");
this.algorithm = requireNonNull(algorithm, "algorithm");
this.validSeconds = validSeconds;
this.leewaySeconds = leewaySeconds;
checkArgument(validSeconds > 0,
"invalid valid duration: " + validSeconds + " (expected: > 0)");
checkArgument(leewaySeconds >= 0,
"invalid leeway duration:" + leewaySeconds + " (expected: >= 0)");
un1 = getUniquifierPrefix();
verifier = JWT.require(algorithm)
.withIssuer(issuer)
.acceptLeeway(leewaySeconds)
.build();
}
@GetMapping(value = "/")
@ResponseBody
public String home(HttpServletRequest request, HttpServletResponse response, final Authentication authentication) throws IOException {
if (authentication!= null && authentication instanceof TestingAuthenticationToken) {
TestingAuthenticationToken token = (TestingAuthenticationToken) authentication;
DecodedJWT jwt = JWT.decode(token.getCredentials().toString());
String email = jwt.getClaims().get("email").asString();
return "Welcome, " + email + "!";
} else {
response.sendRedirect("http://localhost:8080/login");
return null;
}
}
private String getUsername(String token) {
if (StringUtil.isEmpty(token)) {
return null;
}
SessionConfig config = sessionConfig();
try {
JWTVerifier verifier = JWT.require(
Algorithm.HMAC256(config.getSecret()))
.build();
DecodedJWT jwt = verifier.verify(token);
return jwt.getSubject();
} catch (Exception e) {
return null;
}
}
@Override
public String create(String username, Map<String, Object> claims) {
JWTCreator.Builder builder = JWT.create()
.withSubject(username)
.withIssuedAt(new Date())
.withExpiresAt(DateUtil.plus(config.getExpires().toMillis()));
if (null != config.getRenewExpires() &&
config.getRenewExpires().toMillis() > 0) {
builder.withClaim(REFRESH_EXPIRES_AT,
DateUtil.plus(config.getRenewExpires().toMillis()));
}
if (null != claims && !claims.isEmpty()) {
claims.forEach((key, value) -> {
addClaim(builder, key, value);
});
}
return builder.sign(Algorithm.HMAC256(config.getSecret()));
}
/**
* 生成签名
* @param account 帐号
* @return java.lang.String 返回加密的Token
* @author Wang926454
* @date 2018/8/31 9:07
*/
public static String sign(String account, String currentTimeMillis) {
try {
// 帐号加JWT私钥加密
String secret = account + Base64ConvertUtil.decode(encryptJWTKey);
// 此处过期时间是以毫秒为单位,所以乘以1000
Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带account帐号信息
return JWT.create()
.withClaim("account", account)
.withClaim("currentTimeMillis", currentTimeMillis)
.withExpiresAt(date)
.sign(algorithm);
} catch (UnsupportedEncodingException e) {
logger.error("JWTToken加密出现UnsupportedEncodingException异常:{}", e.getMessage());
throw new CustomException("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());
}
}
public Integer verifyTokenAndGetUserId(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUSER)
.build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
Claim claim = claims.get("userId");
return claim.asInt();
} catch (JWTVerificationException exception){
// exception.printStackTrace();
}
return 0;
}
/**
* This method is used to validate the Bearer token. It validates the source and the expiration and if the token is about to expire in 30 seconds, set as invalid token
*
* @param accessToken the access token to test
* @param profile the server profile
* @param clientId the clientId used to retrieve access tokens
*
* @return true if the token is valid and false otherwise
*
* @throws JWTDecodeException if the method failed to parse the supplied token
*/
private static boolean isValidBearerToken(String accessToken, ServerProfile profile, String clientId) throws JWTDecodeException {
boolean isValid = false;
JWT jwt = JWT.decode(accessToken);
String jwtClientId = jwt.getClaim("client_id").asString();
String jwtEmailId = jwt.getClaim("email").asString();
long jwtExpiresAt = jwt.getExpiresAt().getTime() / 1000;
long difference = jwtExpiresAt - (System.currentTimeMillis() / 1000);
if (jwt != null && jwtClientId != null && jwtClientId.equals(clientId)
&& jwtEmailId != null && jwtEmailId.equalsIgnoreCase(profile.getCredential_user())
&& profile.getTokenUrl().contains(jwt.getIssuer())
&& difference >= 30) {
isValid = true;
}
return isValid;
}
@Test
public void failsWhenExpClaimInvalidOutsideCustomLeeway() {
String token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC0xMjMiXSwiZXhwIjoxNTY3MzE0MDAwLCJpYXQiOjE1NjczMTQwMDAsIm5vbmNlIjoiYTU5dms1OTIiLCJhenAiOiJ0b2tlbnMtdGVzdC0xMjMiLCJhdXRoX3RpbWUiOjE1NjczMTQwMDB9.uDn-4wtiigGddUw2kis_QyfDE3w75rWvu9NolMgD3b7l4_fedhQOk-z_mYID588ZXpnpLRKKiD5I2IFsXl7Qcc10rx1LIZxNqdzyc3VrgFf677x7fFZ4guR2WalH-zdJEluruMRdCIFQczIjXnGKPHGQ8gPH1LRozv43dl-bO2viX6MU4pTgNq3GIsU4ureyHrx1o9JSqF4b_RzuYvVWVVX7ABC2csMJP_ocVbEIQjUBhp1V7VcQY-Zgq0prk_HvY13g8FxK4KvSza637ZWAfonn599SKuy22PeMJqDfd64SbunWrt-mKBz9PHeAo9t4LJPLsAqSd3IQ2aJTsnqJRA";
Integer leeway = 120;
Date actualExp = JWT.decode(token).getExpiresAt();
// set clock to September 1, 2019 5:00:00 AM GMT
Date clock = new Date(1567314000000L);
clock.setTime(clock.getTime() + ((leeway + 1) * 1000));
IdTokenVerifier.Options options = configureOptions(token);
options.setClockSkew(leeway);
options.setClock(clock);
exception.expect(TokenValidationException.class);
exception.expectMessage(String.format("Expiration Time (exp) claim error in the ID token; current time (%d) is after expiration time (%d)",
clock.getTime() / 1000, ((actualExp.getTime() / 1000) + leeway)));
new IdTokenVerifier().verify(token, options);
}
@Bean
@Qualifier("jwk")
public JWTVerifier create(@Value("${jwt.issuer}") String issuer, @Value("${jwt.audience}") String audience)
throws JwkException, IOException {
UrlJwkProvider urlJwkProvider = new UrlJwkProvider(issuer);
RestTemplate restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(restTemplate.getForObject(issuer + "/.well-known/jwks.json", String.class));
String kid = jsonNode.get("keys").get(0).get("kid").asText();
Jwk jwk = urlJwkProvider.get(kid);
return JWT.require(Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null))
.withIssuer(issuer)
.withAudience(audience)
.build();
}
/**
* decode AccountEntity from token
* f
*
* @param token token
* @return AccountEntity
*/
public static AccountEntity decodeToken(String token, String privateSecret) {
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(privateSecret)).build();
DecodedJWT jwt = verifier.verify(token);
// check expired date
if (Calendar.getInstance().getTime().after(jwt.getExpiresAt())) {
log.error("expired token at {}", jwt.getExpiresAt());
return null;
}
return new AccountEntity(jwt.getIssuer());
} catch (JWTVerificationException e) {
log.error("invalid jwt token", e);
return null;
}
}
/**
* 生成签名,五分钟后过期
* @param userId
* @return
*/
public static String sign(String userId) {
try {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT.create()
// 将 user id 保存到 token 里面
.withAudience(userId)
// 五分钟后token过期
.withExpiresAt(date)
// token 的密钥
.sign(algorithm);
} catch (Exception e) {
return null;
}
}
@Test
public void shouldAuthenticateUsingJWKAndSeveralAllowedIssuers() throws Exception {
Jwk jwk = mock(Jwk.class);
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, new String[]{"test-issuer1", "test-issuer2"}, "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("test-issuer2")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
Authentication result = provider.authenticate(authentication);
assertThat(result, is(notNullValue()));
assertThat(result, is(not(equalTo(authentication))));
}
@Test
public void createTokenWithClaim() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("alg", "HS256");
map.put("typ", "JWT");
Date nowDate = new Date();
Date expireDate = getAfterDate(nowDate,0,0,0,2,0,0);//2小过期
Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
.withHeader(map)
/*设置 载荷 Payload*/
.withClaim("loginName", "zhuoqianmingyue")
.withIssuer("SERVICE")//签名是有谁生成 例如 服务器
.withSubject("this is test token")//签名的主题
//.withNotBefore(new Date())//该jwt都是不可用的时间
.withAudience("APP")//签名的观众 也可以理解谁接受签名的
.withIssuedAt(nowDate) //生成签名的时间
.withExpiresAt(expireDate)//签名过期的时间
/*签名 Signature */
.sign(algorithm);
Assert.assertTrue(token.length() > 0);
}
@Test
public void succeedsWithValidTokenUsingDefaultClock() {
String token = JWT.create()
.withSubject("auth0|sdk458fks")
.withAudience(AUDIENCE)
.withIssuedAt(getYesterday())
.withExpiresAt(getTomorrow())
.withIssuer("https://" + DOMAIN + "/")
.withClaim("nonce", "nonce")
.sign(Algorithm.HMAC256("secret"));
DecodedJWT decodedJWT = JWT.decode(token);
SignatureVerifier verifier = mock(SignatureVerifier.class);
when(verifier.verifySignature(token)).thenReturn(decodedJWT);
IdTokenVerifier.init("https://" + DOMAIN + "/", AUDIENCE, verifier)
.build()
.verify(token, "nonce");
}
@Test
public void shouldFailJOSEToDERConversionOnInvalidJOSESignatureLength() throws Exception {
exception.expect(SignatureVerificationException.class);
exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA");
exception.expectCause(isA(SignatureException.class));
exception.expectCause(hasMessage(is("Invalid JOSE signature format.")));
byte[] bytes = new byte[256];
new SecureRandom().nextBytes(bytes);
String signature = Base64.encodeBase64URLSafeString(bytes);
String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
ECPublicKey publicKey = (ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
ECPrivateKey privateKey = mock(ECPrivateKey.class);
ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey);
Algorithm algorithm = new ECDSAAlgorithm("ES256", "SHA256withECDSA", 128, provider);
algorithm.verify(JWT.decode(jwt));
}
@Override
public void register() {
post(mkPath(BASE_URL, "login"), (request, response) -> {
LoginRequest login = readBody(request, LoginRequest.class);
AuthenticationResponse authResponse = authenticate(login);
if (authResponse.success()) {
Algorithm algorithmHS = Algorithm.HMAC512(JWTUtilities.SECRET);
String[] roles = userRoleService
.getUserRoles(authResponse.waltzUserName())
.toArray(new String[0]);
String token = JWT.create()
.withIssuer(JWTUtilities.ISSUER)
.withSubject(authResponse.waltzUserName())
.withArrayClaim("roles", roles)
.withClaim("displayName", login.userName())
.withClaim("employeeId", login.userName())
.sign(algorithmHS);
return newHashMap("token", token);
} else {
response.status(401);
return authResponse.errorMessage();
}
}, transformer);
before(mkPath("api", "*"), filter);
}
@Test
public void shouldThrowOnVerifyWhenTheSecretIsInvalid() throws Exception {
exception.expect(SignatureVerificationException.class);
exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: some-alg");
exception.expectCause(isA(InvalidKeyException.class));
CryptoHelper crypto = mock(CryptoHelper.class);
when(crypto.verifySignatureFor(anyString(), any(byte[].class), any(String.class), any(String.class), any(byte[].class)))
.thenThrow(InvalidKeyException.class);
Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", "secret".getBytes(StandardCharsets.UTF_8));
String jwt = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M";
algorithm.verify(JWT.decode(jwt));
}
@Test
public void shouldPassECDSA256VerificationWithJOSESignature() throws Exception {
String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
Algorithm algorithm = Algorithm.ECDSA256(key);
algorithm.verify(JWT.decode(jwt));
}
@Test
public void shouldFailECDSA384VerificationOnInvalidJOSESignatureLength() throws Exception {
exception.expect(SignatureVerificationException.class);
exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA");
exception.expectCause(isA(SignatureException.class));
exception.expectCause(hasMessage(is("Invalid JOSE signature format.")));
byte[] bytes = new byte[95];
new SecureRandom().nextBytes(bytes);
String signature = Base64.encodeBase64URLSafeString(bytes);
String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC"));
algorithm.verify(JWT.decode(jwt));
}
public CompletableFuture<DecodedJWT> verify(String token) {
final DecodedJWT unverifiedJwt;
try {
unverifiedJwt = JWT.decode(token);
} catch (JWTVerificationException e) {
return CompletableFuturesExtra.exceptionallyCompletedFuture(e);
}
return getAlgorithm(unverifiedJwt.getKeyId())
.thenApply(
alg -> {
JWTVerifier verifier = JWT.require(alg).build();
return verifier.verify(token);
});
}
/**
* 解析基础信息,返回解码后的JWT
* @param jwtStr jwt
* @return DecodedJWT
*/
private static DecodedJWT parse(String jwtStr) {
Algorithm algorithm = null;
try {
algorithm = Algorithm.HMAC256(SECRET);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
return verifier.verify(jwtStr);
}
/**
* 获得Token中的信息无需secret解密也能获得
* @param token
* @param claim
* @return java.lang.String
* @author Wang926454
* @date 2018/9/7 16:54
*/
public static String getClaim(String token, String claim) {
try {
DecodedJWT jwt = JWT.decode(token);
// 只能输出String类型,如果是其他类型返回null
return jwt.getClaim(claim).asString();
} catch (JWTDecodeException e) {
logger.error("解密Token中的公共信息出现JWTDecodeException异常:{}", e.getMessage());
throw new CustomException("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
}
}
@Test
public void shouldDoRSA384SigningWithBothKeys() throws Exception {
Algorithm algorithm = Algorithm.RSA384((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
String jwt = asJWT(algorithm, RS384Header, auth0IssPayload);
String expectedSignature = "Jx1PaTBnjd_U56MNjifFcY7w9ImDbseg0y8Ijr2pSiA1_wzQb_wy9undaWfzR5YqdIAXvjS8AGuZUAzIoTG4KMgOgdVyYDz3l2jzj6wI-lgqfR5hTy1w1ruMUQ4_wobpdxAiJ4fEbg8Mi_GljOiCO-P1HilxKnpiOJZidR8MQGwTInsf71tOUkK4x5UsdmUueuZbaU-CL5kPnRfXmJj9CcdxZbD9oMlbo23dwkP5BNMrS2LwGGzc9C_-ypxrBIOVilG3WZxcSmuG86LjcZbnL6LBEfph5NmKBgQav147uipb_7umBEr1m2dYiB_9u606n3bcoo3rnsYYK_Xfi1GAEQ";
assertSignaturePresent(jwt);
assertSignatureValue(jwt, expectedSignature);
algorithm.verify(JWT.decode(jwt));
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
DecodedJWT jwt = ((UserToken)authentication).getToken();
boolean expire=jwt.getExpiresAt().before(new Date());
if(expire)
throw new TokenException("Token 已经失效");
String username = jwt.getSubject();
UserDetails user = userService.getUserLoginInfo(username);
if(user == null || user.getPassword()==null)
throw new TokenException("Token 已经失效");
String encryptSalt = user.getPassword();
try {
Algorithm algorithm = Algorithm.HMAC256(encryptSalt);
JWTVerifier verifier = JWT.require(algorithm)
.withSubject(username)
.build();
verifier.verify(jwt.getToken());
} catch (Exception e) {
throw new BadCredentialsException("Token 认证失败", e);
}
UserToken token = new UserToken(user, jwt, user.getAuthorities());
return token;
}
/**
* 创建jwt串
*
* @param map 自定义的 K, V
* @param expires 过期时间(ms)
* @return token串
* @throws JWTCreationException
*/
public String createJwt(Map<String, String> map, long expires) throws JWTCreationException {
Algorithm algorithm = Algorithm.HMAC256(env.getProperty("jwt.secret-key"));
JWTCreator.Builder builder = JWT.create()
.withIssuer(env.getProperty("jwt.issuer"))
.withSubject(env.getProperty("jwt.subject"))
.withExpiresAt(new Date(System.currentTimeMillis() + expires));
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.withClaim(entry.getKey(), entry.getValue());
}
return builder.sign(algorithm);
}
/**
* 校验token是否正确
*
* @param token Token
* @param secret 私钥
* @return boolean 是否正确
* @author Wang926454
* @date 2018/8/31 9:05
*/
public static boolean verify(String token, String secret) {
try {
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (UnsupportedEncodingException e) {
e.getMessage();
}
return false;
}
public static PreAuthenticatedAuthenticationJsonWebToken usingToken(String token) {
if (token == null) {
logger.debug("No token was provided to build {}", PreAuthenticatedAuthenticationJsonWebToken.class.getName());
return null;
}
try {
DecodedJWT jwt = JWT.decode(token);
return new PreAuthenticatedAuthenticationJsonWebToken(jwt);
} catch (JWTDecodeException e) {
logger.debug("Failed to decode token as jwt", e);
return null;
}
}