Search in sources :

Example 51 with Algorithm

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;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashMap(java.util.HashMap) Instant(java.time.Instant) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException) OAuthResponseException(com.salesforce.einsteinbot.sdk.exception.OAuthResponseException) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 52 with Algorithm

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;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 53 with Algorithm

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);
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Example 54 with 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);
}
Also used : User(org.springframework.security.core.userdetails.User) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 55 with Algorithm

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());
}
Also used : LocalDateTime(java.time.LocalDateTime) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDto(io.metadew.iesi.server.rest.user.UserDto) IesiUserDetails(io.metadew.iesi.server.rest.configuration.security.IesiUserDetails) Algorithm(com.auth0.jwt.algorithms.Algorithm) AuthenticationResponse(io.metadew.iesi.server.rest.user.AuthenticationResponse)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)206 Test (org.junit.Test)160 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)90 JWTVerifier (com.auth0.jwt.JWTVerifier)79 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)79 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)61 Date (java.util.Date)57 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)51 RSAPublicKey (java.security.interfaces.RSAPublicKey)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)31 IOException (java.io.IOException)30 JWTCreator (com.auth0.jwt.JWTCreator)28 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 HashMap (java.util.HashMap)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 JsonObject (com.google.gson.JsonObject)15