use of com.auth0.jwt.JWTVerifier in project bank-of-sirius by nginxinc.
the class JWTVerifierGenerator method generateJWTVerifier.
@Bean(name = "verifier")
@ConditionalOnProperty(value = "jwt.account.authentication.enabled", matchIfMissing = true, havingValue = "true")
public JWTVerifier generateJWTVerifier(@Value("${PUB_KEY_PATH}") final String publicKeyPath) throws IOException {
// load public key from file
final Path publicKeyFile = Paths.get(publicKeyPath);
final String keyContents = new String(Files.readAllBytes(publicKeyFile));
try {
final String keyStr = keyContents.replaceFirst("-----BEGIN PUBLIC KEY-----", "").replaceFirst("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");
final byte[] keyBytes = Base64.getDecoder().decode(keyStr);
final KeyFactory kf = KeyFactory.getInstance("RSA");
final X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(keyBytes);
final RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
// Initialize JWT verifier.
final Algorithm algorithm = Algorithm.RSA256(publicKey, null);
final JWTVerifier verifier = JWT.require(algorithm).build();
LOGGER.debug("Generated JWT token verifier [algorithm={},publicKeyPath={}]", algorithm.getName(), publicKeyFile);
return verifier;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
final String msg = String.format("Cannot generate JWT key [path=%s]", publicKeyFile);
throw new GenerateKeyException(msg, e);
}
}
use of com.auth0.jwt.JWTVerifier in project Tbed by Hello-hao.
the class JWTUtil method checkToken.
public static JSONObject checkToken(String token) {
// 验证对象
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
JSONObject jsonObject = new JSONObject();
if (null == token) {
jsonObject.put("check", false);
return jsonObject;
}
try {
DecodedJWT verify = jwtVerifier.verify(token);
Date expiresAt = verify.getExpiresAt();
jsonObject.put("check", true);
jsonObject.put("email", verify.getClaim("email").asString());
jsonObject.put("password", verify.getClaim("password").asString());
jsonObject.put("uid", verify.getClaim("uid").asString());
} catch (TokenExpiredException e) {
e.printStackTrace();
System.out.println("token认证已过期,请重新登录获取");
jsonObject.put("check", false);
} catch (Exception e) {
e.printStackTrace();
System.out.println("token无效");
jsonObject.put("check", false);
}
return jsonObject;
}
use of com.auth0.jwt.JWTVerifier in project UPE_2021_2_Propague by netrometro.
the class TipoParaUsuarioForm method refreshToken.
@GetMapping("/token/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
try {
String refresh_token = authorizationHeader.substring(7);
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = verifier.verify(refresh_token);
String username = decodedJWT.getSubject();
Usuario usuario = servico.getUsuario(username);
String acces_token = com.auth0.jwt.JWT.create().withSubject(usuario.getEmail()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipo", usuario.getTipos().stream().map(TipoUsuario::getNome).collect(Collectors.joining())).sign(algorithm);
// response.setHeader("acces_token", token);
// response.setHeader("refresh_token", refresh_token);
Map<String, String> map = new HashMap<>();
map.put("token", acces_token);
map.put("refresh_token", refresh_token);
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), map);
} catch (Exception e) {
response.setHeader("error", e.getMessage());
response.setStatus(403);
Map<String, String> map = new HashMap<>();
map.put("error", e.getMessage());
response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), map);
}
} else {
throw new RuntimeException("Refresh token is missing");
}
}
use of com.auth0.jwt.JWTVerifier in project yyl_example by Relucent.
the class JwtDemo method main.
public static void main(String[] args) throws Exception {
long currentMillis = System.currentTimeMillis();
// JWT 生存时间(5秒)
long ttl = 5000;
// 生成JWT的时间
Date iat = new Date(currentMillis);
// 生成JWT失效时间
Date exp = new Date(currentMillis + ttl);
// 签名秘钥
String secret = "key";
// 签发人
String issuer = "root";
// 算法
Algorithm algorithm = Algorithm.HMAC256(secret);
// 本地的密码解码
JWTCreator.Builder builder = JWT.create();
// 签发时间
builder.withIssuedAt(iat);
// 签发人
builder.withIssuer(issuer);
// 过期时间
builder.withExpiresAt(exp);
// 主题
builder.withClaim("subject", "MySubject");
String token = builder.sign(algorithm);
System.out.println(token);
// 解密
JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
NullClaim nullClaim = new NullClaim();
System.out.println(claims.getOrDefault("subject", nullClaim).asString());
// 等待5秒
System.out.println("Wait 5 seconds!");
Thread.sleep(5000);
try {
// 这时候Token已经超时了,会抛出异常
verifier.verify(token);
} catch (JWTVerificationException e) {
System.err.println(e);
}
}
use of com.auth0.jwt.JWTVerifier in project cryptography by norkator.
the class JWT method verifyECDSA256Jwt.
/**
* Verify elliptic curve based JWT
*
* @param publicPem of key pair
* @param issuer party name
* @param token of created jwt
* @return DecodedJWT including claims
* @throws JWTVerificationException thrown if verification fails
*/
public static DecodedJWT verifyECDSA256Jwt(String publicPem, String issuer, final String token) throws JWTVerificationException, InvalidKeySpecException, NoSuchAlgorithmException {
ECKey publicKey = (ECKey) PEMToKey.getPemPublicKey(publicPem, "ECDSA");
Algorithm algorithm = Algorithm.ECDSA256(publicKey);
JWTVerifier verifier = com.auth0.jwt.JWT.require(algorithm).withIssuer(issuer).build();
return verifier.verify(token);
}
Aggregations