use of com.auth0.jwt.Algorithm in project einstein-bot-sdk-java by forcedotcom.
the class JwtBearerOAuth method getToken.
@Override
public String getToken() {
Optional<String> token = cache.flatMap(c -> c.get(getCacheKey()));
if (token.isPresent()) {
logger.debug("Found cached OAuth token.");
return token.get();
}
logger.debug("Did not find OAuth token in cache. Will retrieve from OAuth server.");
Instant now = Instant.now();
String jwt = null;
try {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("alg", "RS256");
Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
jwt = JWT.create().withHeader(headers).withAudience(loginEndpoint).withExpiresAt(Date.from(now.plus(jwtExpiryMinutes, ChronoUnit.MINUTES))).withIssuer(connectedAppId).withSubject(userId).sign(algorithm);
logger.debug("Generated jwt: {} ", jwt);
} catch (JWTCreationException exception) {
// Invalid Signing configuration / Couldn't convert Claims.
throw new RuntimeException(exception);
}
String response = webClient.post().uri("/services/oauth2/token").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).body(BodyInserters.fromFormData("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer").with("assertion", jwt)).retrieve().bodyToMono(String.class).block();
String oAuthToken = null;
try {
ObjectNode node = new ObjectMapper().readValue(response, ObjectNode.class);
oAuthToken = node.get("access_token").asText();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
IntrospectionResult iResult = introspector.introspect(oAuthToken);
if (!iResult.isActive()) {
throw new RuntimeException("OAuth token is not active.");
}
Instant expiry = Instant.ofEpochSecond(iResult.getExp());
long ttl = Math.max(0, Instant.now().until(expiry, ChronoUnit.SECONDS) - 300);
if (cache.isPresent()) {
cache.get().set(getCacheKey(), oAuthToken, ttl);
}
return oAuthToken;
}
use of com.auth0.jwt.Algorithm in project seckill by yt-King.
the class JWTUtils method verify.
/**
* 校验token是否正确
* @param token 密钥
* @param password 用户的密码
* @return 是否正确
*/
public static boolean verify(String token, String username, String password) {
Algorithm algorithm = Algorithm.HMAC256(password);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
DecodedJWT jwt = verifier.verify(token);
return true;
}
use of com.auth0.jwt.Algorithm in project seckill by yt-King.
the class JWTUtils method sign.
/**
* 生成签名
* @param username 用户名
* @param password 用户的密码
* @return 加密的token
*/
public static String sign(String username, String password) {
// 设置过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 加密密码
Algorithm algorithm = Algorithm.HMAC256(password);
// 附带username信息
return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
}
use of com.auth0.jwt.Algorithm in project Gestion_Employee_SpringBoot_Angular by ibrahimesseddyq.
the class AuthFilter method successfulAuthentication.
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
User user = (User) authentication.getPrincipal();
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
String accessToken = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 6 * 60 * 60 * 1000)).withIssuer(request.getRequestURI().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
String refreshToken = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 8 * 60 * 60 * 1000)).withIssuer(request.getRequestURI().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
// response.setHeader("access_token",accessToken);
// response.setHeader("refresh_token",refreshToken);
Map<String, String> tokens = new HashMap<>();
tokens.put("access_token", accessToken);
tokens.put("refresh_token", refreshToken);
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
use of com.auth0.jwt.Algorithm in project iesi by metadew.
the class JwtService method generateAuthenticationResponse.
public AuthenticationResponse generateAuthenticationResponse(Authentication authentication) {
Algorithm algorithm = Algorithm.HMAC256(secret);
LocalDateTime now = LocalDateTime.now(clock);
LocalDateTime expiresAt = now.plus(accessTokenExpiryDate, ChronoUnit.SECONDS);
String token = JWT.create().withIssuer(ISSUER).withSubject(authentication.getName()).withIssuedAt(Timestamp.valueOf(now)).withExpiresAt(Timestamp.valueOf(expiresAt)).withClaim("uuid", ((IesiUserDetails) authentication.getPrincipal()).getId().toString()).sign(algorithm);
UserDto userDto = userService.get(((IesiUserDetails) authentication.getPrincipal()).getId()).orElseThrow(() -> new UsernameNotFoundException(String.format("Cannot find user %s (%s)", ((IesiUserDetails) authentication.getPrincipal()).getId().toString(), ((IesiUserDetails) authentication.getPrincipal()).getUsername())));
return new AuthenticationResponse(token, ChronoUnit.SECONDS.between(now, expiresAt), userDto.getRoles());
}
Aggregations