Search in sources :

Example 1 with JWTVerifier

use of com.auth0.jwt.interfaces.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.interfaces.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.interfaces.JWTVerifier in project snow-owl by b2ihealthcare.

the class IdentityPlugin method configureJWT.

@VisibleForTesting
/*package*/
void configureJWT(ApplicationContext services, final IdentityProvider identityProvider, final IdentityConfiguration conf) throws MalformedURLException {
    RSAKeyProvider rsaKeyProvider = createRSAKeyProvider(conf);
    Algorithm algorithm;
    if (!Strings.isNullOrEmpty(conf.getJws())) {
        algorithm = SUPPORTED_JWS_ALGORITHMS.getOrDefault(conf.getJws(), this::throwUnsupportedJws).apply(conf, rsaKeyProvider);
    } else {
        IdentityProvider.LOG.warn("'identity.jws' configuration is missing, disabling JWT authorization token signing and verification.");
        algorithm = null;
    }
    JWTGenerator generator;
    JWTVerifier verifier;
    if (algorithm == null) {
        // both signing and verification is disabled
        generator = JWT_GENERATOR_DISABLED;
        verifier = JWT_VERIFIER_DISABLED;
    } else if (rsaKeyProvider != null && rsaKeyProvider.getPrivateKey() == null) {
        generator = JWT_GENERATOR_DISABLED;
        verifier = createJWTVerifier(algorithm, conf);
    } else {
        generator = new DefaultJWTGenerator(algorithm, conf);
        verifier = createJWTVerifier(algorithm, conf);
    }
    // always configure a JWTGenerator, a JWTVerifier and an AuthorizationHeader verifier
    services.registerService(JWTGenerator.class, generator);
    services.registerService(JWTVerifier.class, verifier);
    services.registerService(AuthorizationHeaderVerifier.class, new AuthorizationHeaderVerifier(verifier, identityProvider, conf.getEmailClaimProperty(), conf.getPermissionsClaimProperty()));
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 4 with JWTVerifier

use of com.auth0.jwt.interfaces.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 5 with JWTVerifier

use of com.auth0.jwt.interfaces.JWTVerifier in project cu-kfs by CU-CommunityApps.

the class CuCapAssetInventoryServerAuthFilter method isAuthorized.

private boolean isAuthorized(HttpServletRequest request) {
    String cognitoIdToken = request.getHeader(CuCamsConstants.CapAssetApi.COGNITO_ID_TOKEN);
    PublicKey cognitoUserPoolPublicKey = getCognitoUserPoolPublicKey();
    if (ObjectUtils.isNull(cognitoUserPoolPublicKey)) {
        return false;
    }
    String cognitoUserPoolIssuerUrl = getConfigurationService().getPropertyValueAsString(CuCamsConstants.CapAssetApi.ConfigurationProperties.COGNITO_USER_POOL_ISSUER_URL);
    Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) cognitoUserPoolPublicKey, null);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(cognitoUserPoolIssuerUrl).withClaim(CuCamsConstants.CapAssetApi.TOKEN_USE, CuCamsConstants.CapAssetApi.ID).build();
    DecodedJWT jwt = verifier.verify(cognitoIdToken);
    String email = jwt.getClaim(CuCamsConstants.CapAssetApi.EMAIL).asString();
    LOG.info("CapAssetInventory Authorized {}", email);
    return true;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)12 Algorithm (com.auth0.jwt.algorithms.Algorithm)8 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)8 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)2 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)2 IOException (java.io.IOException)2 JWTCreator (com.auth0.jwt.JWTCreator)1 BaseVerification (com.auth0.jwt.JWTVerifier.BaseVerification)1 SignatureVerificationException (com.auth0.jwt.exceptions.SignatureVerificationException)1 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)1 NullClaim (com.auth0.jwt.impl.NullClaim)1 Claim (com.auth0.jwt.interfaces.Claim)1 Clock (com.auth0.jwt.interfaces.Clock)1 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 RequestValidationException (com.messagebird.exceptions.RequestValidationException)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