Search in sources :

Example 46 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project Minecraft-Server-WebStore by Ba1oretto.

the class JwtUtils method verity.

/**
 * 校验token
 * @return boolean
 */
public static boolean verity() {
    HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
    // 从请求头部中获取token信息
    String token = request.getHeader(HEADER_KEY);
    if (StringUtils.isBlank(token)) {
        return false;
    }
    if (!token.startsWith(PREFIX)) {
        CommonUtils.throwRuntimeException(StatusEnum.WRONG_PREFIX);
    }
    token = token.replace(PREFIX, "");
    try {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        if (null == jwt) {
            return false;
        }
        // 判断过期时间
        long time = (jwt.getExpiresAt().getTime() - System.currentTimeMillis());
        // 有效期只有不到60分钟,需要刷新token了
        if (REFRESH_TIME > time) {
            String newToken = createToken(jwt.getClaim(UUID).asString());
            // 将新的token放入响应请求头中
            SpringContextUtils.getHttpServletResponse().setHeader(HEADER_KEY, newToken);
        }
        return true;
    } catch (Exception e) {
        log.error("token verified error, {}", e.getMessage());
    }
    return false;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 47 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project openware by open-inc.

the class UserService method jwtToUser.

public User jwtToUser(String token) {
    if (jwtVerifier == null)
        return null;
    try {
        DecodedJWT userJWT = jwtVerifier.verify(token);
        Claim userid = userJWT.getClaim("uid");
        if (!userid.isNull())
            return getUserByUID(userid.asString());
        Claim username = userJWT.getClaim("username");
        if (!username.isNull())
            return getUserByUsername(username.asString());
        Claim usermail = userJWT.getClaim("usermail");
        if (!usermail.isNull())
            return getActiveUsers().stream().filter(new Predicate<User>() {

                @Override
                public boolean test(User t) {
                    return t.getEmail().toLowerCase().equals(usermail.asString().toLowerCase());
                }
            }).findFirst().get();
        return null;
    } catch (JWTVerificationException e) {
        return null;
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) User(de.openinc.model.user.User) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) Predicate(java.util.function.Predicate)

Example 48 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project foundation-java by soffalabs.

the class DefaultJwtProcessor method decode.

@Override
public Optional<Authentication> decode(String token, ClaimsExtractor claimsExtractor) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(config.getSecret());
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(config.getIssuer()).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> baseClaims = jwt.getClaims();
        Map<String, Object> claims = new HashMap<>();
        for (Map.Entry<String, Claim> entry : baseClaims.entrySet()) {
            claims.put(entry.getKey(), entry.getValue().asString());
        }
        return Optional.of(claimsExtractor.extractInfo(new Jwt(token, jwt.getSubject(), claims)));
    } catch (Exception e) {
        LOG.error(e);
        return Optional.empty();
    }
}
Also used : HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Map(java.util.Map) HashMap(java.util.HashMap) Claim(com.auth0.jwt.interfaces.Claim)

Example 49 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project wikidata-query-rdf by wikimedia.

the class TimeLimitedAccessTokenFactoryUnitTest method timeControlledVerifier.

private JWTVerifier timeControlledVerifier(long verifyAtEpochSecond) {
    Clock jwtClock = mock(Clock.class);
    when(jwtClock.getToday()).thenReturn(Date.from(Instant.ofEpochSecond(verifyAtEpochSecond)));
    return ((JWTVerifier.BaseVerification) JWT.require(algo)).build(jwtClock);
}
Also used : Clock(com.auth0.jwt.interfaces.Clock)

Example 50 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method create.

/**
 * Allows to complete the creation of a user which is pre-created.
 * @param registerUserEntity a valid token and a password
 * @return the user
 */
@Override
public UserEntity create(final RegisterUserEntity registerUserEntity) {
    checkUserRegistrationEnabled();
    try {
        final String jwtSecret = environment.getProperty("jwt.secret");
        if (jwtSecret == null || jwtSecret.isEmpty()) {
            throw new IllegalStateException("JWT secret is mandatory");
        }
        final Map<String, Object> claims = new JWTVerifier(jwtSecret).verify(registerUserEntity.getToken());
        final NewUserEntity newUserEntity = new NewUserEntity();
        newUserEntity.setUsername(claims.get(Claims.SUBJECT).toString());
        newUserEntity.setEmail(claims.get(Claims.EMAIL).toString());
        newUserEntity.setFirstname(claims.get(Claims.FIRSTNAME).toString());
        newUserEntity.setLastname(claims.get(Claims.LASTNAME).toString());
        newUserEntity.setPassword(registerUserEntity.getPassword());
        LOGGER.debug("Create an internal user {}", newUserEntity);
        Optional<User> checkUser = userRepository.findByUsername(newUserEntity.getUsername());
        if (checkUser.isPresent() && StringUtils.isNotBlank(checkUser.get().getPassword())) {
            throw new UsernameAlreadyExistsException(newUserEntity.getUsername());
        }
        User user = convert(newUserEntity);
        user.setId(UUID.toString(UUID.random()));
        // Encrypt password if internal user
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        // Set date fields
        user.setUpdatedAt(new Date());
        user = userRepository.update(user);
        auditService.createPortalAuditLog(Collections.singletonMap(USER, user.getUsername()), User.AuditEvent.USER_CREATED, user.getUpdatedAt(), null, user);
        return convert(user, true);
    } catch (Exception ex) {
        LOGGER.error("An error occurs while trying to create an internal user with the token {}", registerUserEntity.getToken(), ex);
        throw new TechnicalManagementException(ex.getMessage(), ex);
    }
}
Also used : UsernameAlreadyExistsException(io.gravitee.management.service.exceptions.UsernameAlreadyExistsException) User(io.gravitee.repository.management.model.User) JWTVerifier(com.auth0.jwt.JWTVerifier) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UsernameAlreadyExistsException(io.gravitee.management.service.exceptions.UsernameAlreadyExistsException) DefaultRoleNotFoundException(io.gravitee.management.service.exceptions.DefaultRoleNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) IOException(java.io.IOException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)115 Algorithm (com.auth0.jwt.algorithms.Algorithm)104 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)100 Test (org.junit.Test)42 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)30 IOException (java.io.IOException)23 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)18 RSAPublicKey (java.security.interfaces.RSAPublicKey)15 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)14 Claim (com.auth0.jwt.interfaces.Claim)10 Date (java.util.Date)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HashMap (java.util.HashMap)8 ECKey (java.security.interfaces.ECKey)7 ServletException (javax.servlet.ServletException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)5 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)5 URL (java.net.URL)5 KeyFactory (java.security.KeyFactory)5