Search in sources :

Example 1 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)

Example 2 with JWTVerifier

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);
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTCreator(com.auth0.jwt.JWTCreator) NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim)

Example 3 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project libresonic by Libresonic.

the class JWTSecurityService method verify.

public static DecodedJWT verify(String jwtKey, String token) {
    Algorithm algorithm = JWTSecurityService.getAlgorithm(jwtKey);
    JWTVerifier verifier = JWT.require(algorithm).build();
    return verifier.verify(token);
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 4 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project waltz by khartec.

the class JWTAuthenticationFilter method handle.

@Override
public void handle(Request request, Response response) throws Exception {
    String authorizationHeader = request.headers("Authorization");
    if (authorizationHeader == null) {
        AuthenticationUtilities.setUserAsAnonymous(request);
    } else {
        String token = authorizationHeader.replaceFirst("Bearer ", "");
        DecodedJWT decodedToken = JWT.decode(token);
        JWTVerifier verifier = selectVerifier(decodedToken);
        DecodedJWT decodedJWT = verifier.verify(token);
        AuthenticationUtilities.setUser(request, decodedJWT.getSubject());
    }
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 5 with JWTVerifier

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

the class OAuth2AuthenticationResourceTest method verifyJwtToken.

private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerifyException {
    String cookieContent = response.getCookies().get(HttpHeaders.AUTHORIZATION).getValue();
    assertThat(cookieContent, StringStartsWith.startsWith("Bearer "));
    String jwt = cookieContent.substring(7);
    JWTVerifier jwtVerifier = new JWTVerifier("myJWT4Gr4v1t33_S3cr3t");
    Map<String, Object> mapJwt = jwtVerifier.verify(jwt);
    assertEquals(mapJwt.get("sub"), "janedoe@example.com");
    assertEquals(mapJwt.get("firstname"), "Jane");
    assertEquals(mapJwt.get("iss"), "gravitee-management-auth");
    assertEquals(mapJwt.get("sub"), "janedoe@example.com");
    assertEquals(mapJwt.get("email"), "janedoe@example.com");
    assertEquals(mapJwt.get("lastname"), "Doe");
}
Also used : Matchers.anyString(org.mockito.Matchers.anyString) JWTVerifier(com.auth0.jwt.JWTVerifier)

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)8 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)4 Algorithm (com.auth0.jwt.algorithms.Algorithm)2 IOException (java.io.IOException)2 JWTCreator (com.auth0.jwt.JWTCreator)1 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)1 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)1 NullClaim (com.auth0.jwt.impl.NullClaim)1 Claim (com.auth0.jwt.interfaces.Claim)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 DefaultRoleNotFoundException (io.gravitee.management.service.exceptions.DefaultRoleNotFoundException)1 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)1 UserNotFoundException (io.gravitee.management.service.exceptions.UserNotFoundException)1 UsernameAlreadyExistsException (io.gravitee.management.service.exceptions.UsernameAlreadyExistsException)1 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)1 User (io.gravitee.repository.management.model.User)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InvalidKeyException (java.security.InvalidKeyException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SignatureException (java.security.SignatureException)1