use of com.auth0.android.jwt.JWT in project bank-of-sirius by nginxinc.
the class JWTAuthenticator method extractClaimFromBearerToken.
Claim extractClaimFromBearerToken(final String bearerToken, final String claimName) {
final DecodedJWT jwt;
try {
jwt = verifier.verify(bearerToken);
} catch (JWTVerificationException e) {
throw new AuthenticationException("Unable to decode or verify JWT bearer token", e);
}
final Claim claim = jwt.getClaim(claimName);
if (claim.isNull()) {
throw new AuthenticationException("Unable to extract account id claim from JWT bearer token");
}
return claim;
}
use of com.auth0.android.jwt.JWT 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.android.jwt.JWT in project kikaha.rocker by jmilagroso.
the class Security method valid.
/**
* Validates token
* @param token The token string parameter.
* @param id The id string/integer parameter.
* @param claim The claim string parameter.
* @param issuer The issuer string parameter.
* @return boolean Is valid.
*/
public boolean valid(String token, String id, String claim, String issuer) {
boolean valid = false;
try {
verifier = JWT.require(algorithm).withJWTId(id).withClaim("name", claim).withIssuer(issuer).build();
DecodedJWT jwt = verifier.verify(token);
valid = true;
} catch (Exception e) {
throw new IllegalStateException(e.getLocalizedMessage());
}
return valid;
}
use of com.auth0.android.jwt.JWT in project Team_BbungCles_Devnity_BE by prgrms-web-devcourse.
the class JwtAuthenticationFilter method doFilter.
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (SecurityContextHolder.getContext().getAuthentication() == null) {
String token = getToken(request);
if (Objects.nonNull(token)) {
try {
Jwt.Claims claims = verify(token);
log.debug("Jwt parse result: {}", claims);
String email = claims.email;
Long userId = claims.userId;
GrantedAuthority authority = getAuthorities(claims);
if (Objects.nonNull(email) && !email.isEmpty() && userId != null && authority != null) {
JwtAuthenticationToken authentication = new JwtAuthenticationToken(new JwtAuthentication(token, userId, email), null, authority);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (TokenExpiredException tokenExpiredException) {
request.setAttribute("exception", AuthErrorCode.TOKEN_EXPIRED.getCode());
} catch (Exception e) {
request.setAttribute("exception", AuthErrorCode.INVALID_TOKEN.getCode());
log.warn("Jwt processing failed: {}", e.getMessage());
}
}
} else {
log.debug("SecurityContextHolder not populated with security token, as it already contained: '{}'", SecurityContextHolder.getContext().getAuthentication());
}
chain.doFilter(request, response);
}
use of com.auth0.android.jwt.JWT 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);
}
}
Aggregations