Search in sources :

Example 96 with User

use of com.auth0.flickr2.domain.User in project hopsworks by logicalclocks.

the class JWTHelper method renewServiceToken.

/**
 * Helper method to generate one-time tokens for service JWT renewal and renew the
 * master service JWT
 * @param token2renew Service JWT to renew
 * @param oneTimeRenewalToken Valid one-time token associated with the master token to be renewed.
 *                            One time tokens are generated once a service is logged-in and every time
 *                            it renews its master token
 * @param user Logged in user
 * @param remoteHostname Hostname of the machine the service runs
 * @return Renewed master service JWT and five one-time tokens used to renew it
 * @throws JWTException
 * @throws NoSuchAlgorithmException
 */
public ServiceJWTDTO renewServiceToken(JsonWebTokenDTO token2renew, String oneTimeRenewalToken, Users user, String remoteHostname) throws JWTException, NoSuchAlgorithmException {
    if (Strings.isNullOrEmpty(oneTimeRenewalToken)) {
        throw new VerificationException("Service renewal token cannot be null or empty");
    }
    if (user == null) {
        DecodedJWT decodedJWT = jwtController.decodeToken(oneTimeRenewalToken);
        throw new VerificationException("Could not find user associated with JWT with ID: " + decodedJWT.getId());
    }
    LocalDateTime now = DateUtils.getNow();
    Date expiresAt = token2renew.getExpiresAt() != null ? token2renew.getExpiresAt() : DateUtils.localDateTime2Date(now.plus(settings.getServiceJWTLifetimeMS(), ChronoUnit.MILLIS));
    Date notBefore = token2renew.getNbf() != null ? token2renew.getNbf() : DateUtils.localDateTime2Date(now);
    List<String> userRoles = userController.getUserRoles(user);
    Pair<String, String[]> renewedTokens = jwtController.renewServiceToken(oneTimeRenewalToken, token2renew.getToken(), expiresAt, notBefore, settings.getServiceJWTLifetimeMS(), user.getUsername(), userRoles, SERVICE_RENEW_JWT_AUDIENCE, remoteHostname, settings.getJWTIssuer(), settings.getJWTSigningKeyName(), false);
    int expLeeway = jwtController.getExpLeewayClaim(jwtController.decodeToken(renewedTokens.getLeft()));
    JWTResponseDTO renewedServiceToken = new JWTResponseDTO(renewedTokens.getLeft(), expiresAt, notBefore, expLeeway);
    return new ServiceJWTDTO(renewedServiceToken, renewedTokens.getRight());
}
Also used : LocalDateTime(java.time.LocalDateTime) VerificationException(io.hops.hopsworks.jwt.exception.VerificationException) ServiceJWTDTO(io.hops.hopsworks.api.user.ServiceJWTDTO) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 97 with User

use of com.auth0.flickr2.domain.User in project hopsworks by logicalclocks.

the class ServiceJWTKeepAlive method doRenew.

private void doRenew(boolean force) throws JWTException, InterruptedException {
    String masterToken = settings.getServiceMasterJWT();
    if (Strings.isNullOrEmpty(masterToken)) {
        throw new JWTException("Master token is empty!");
    }
    LocalDateTime now = DateUtils.getNow();
    DecodedJWT masterJWT = jwtController.decodeToken(masterToken);
    if (force || maybeRenewMasterToken(masterJWT, now)) {
        String[] renewalTokens = settings.getServiceRenewJWTs();
        List<String> masterJWTRoles = getJWTRoles(masterJWT);
        String user = masterJWT.getSubject();
        backOff.reset();
        int renewIdx = 0;
        while (renewIdx < renewalTokens.length) {
            String oneTimeToken = renewalTokens[renewIdx];
            Date notBefore = DateUtils.localDateTime2Date(now);
            LocalDateTime expiresAt = now.plus(settings.getServiceJWTLifetimeMS(), ChronoUnit.MILLIS);
            try {
                Pair<String, String[]> renewedTokens = jwtController.renewServiceToken(oneTimeToken, masterToken, DateUtils.localDateTime2Date(expiresAt), notBefore, settings.getServiceJWTLifetimeMS(), user, masterJWTRoles, SERVICE_RENEW_JWT_AUDIENCE, hostname, settings.getJWTIssuer(), settings.getJWTSigningKeyName(), force);
                LOGGER.log(Level.FINEST, "New master JWT: " + renewedTokens.getLeft());
                updateTokens(renewedTokens);
                LOGGER.log(Level.FINEST, "Invalidating JWT: " + masterToken);
                jwtController.invalidateServiceToken(masterToken, settings.getJWTSigningKeyName());
                break;
            } catch (JWTException | NoSuchAlgorithmException ex) {
                renewIdx++;
                Long backoffTimeout = backOff.getBackOffInMillis();
                if (backoffTimeout != -1) {
                    LOGGER.log(Level.WARNING, "Failed to renew service JWT, retrying in " + backoffTimeout + " ms");
                    TimeUnit.MILLISECONDS.sleep(backoffTimeout);
                } else {
                    backOff.reset();
                    throw new JWTException("Cannot renew service JWT");
                }
            }
        }
        LOGGER.log(Level.FINE, "Successfully renewed service JWT");
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) JWTException(io.hops.hopsworks.jwt.exception.JWTException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 98 with User

use of com.auth0.flickr2.domain.User in project hopsworks by logicalclocks.

the class JupyterJWTManager method recover.

protected void recover() {
    LOG.log(INFO, "Starting Jupyter JWT manager recovery");
    List<MaterializedJWT> failed2recover = new ArrayList<>();
    // Get state from the database
    for (MaterializedJWT materializedJWT : materializedJWTFacade.findAll4Jupyter()) {
        LOG.log(Level.FINEST, "Recovering Jupyter JWT " + materializedJWT.getIdentifier());
        // First lookup project and user in db
        Project project = projectFacade.find(materializedJWT.getIdentifier().getProjectId());
        Users user = userFacade.find(materializedJWT.getIdentifier().getUserId());
        if (project == null || user == null) {
            LOG.log(Level.WARNING, "Tried to recover " + materializedJWT.getIdentifier() + " but could not find " + "either Project or User");
            failed2recover.add(materializedJWT);
            continue;
        }
        // Get Jupyter configuration from db
        String hdfsUsername = hdfsUsersController.getHdfsUserName(project, user);
        JupyterProject jupyterProject = jupyterFacade.findByUser(hdfsUsername);
        if (jupyterProject == null) {
            LOG.log(Level.FINEST, "There is no Jupyter configuration persisted for " + materializedJWT.getIdentifier());
            failed2recover.add(materializedJWT);
            continue;
        }
        // Check if Jupyter is still running
        if (!jupyterManager.ping(jupyterProject)) {
            LOG.log(Level.FINEST, "Jupyter server is not running for " + materializedJWT.getIdentifier() + " Skip recovering...");
            failed2recover.add(materializedJWT);
            continue;
        }
        JupyterSettings jupyterSettings = jupyterSettingsFacade.findByProjectUser(project, user.getEmail());
        Path tokenFile = constructTokenFilePath(jupyterSettings);
        String token = null;
        JupyterJWT jupyterJWT = null;
        CidAndPort pidAndPort = new CidAndPort(jupyterProject.getCid(), jupyterProject.getPort());
        try {
            token = FileUtils.readFileToString(tokenFile.toFile());
            DecodedJWT decodedJWT = jwtController.verifyToken(token, settings.getJWTIssuer());
            jupyterJWT = new JupyterJWT(project, user, DateUtils.date2LocalDateTime(decodedJWT.getExpiresAt()), pidAndPort);
            jupyterJWT.token = token;
            jupyterJWT.tokenFile = tokenFile;
            LOG.log(Level.FINE, "Successfully read existing JWT from local filesystem");
        } catch (IOException | JWTException | JWTDecodeException ex) {
            LOG.log(Level.FINE, "Could not recover Jupyter JWT from local filesystem, generating new!", ex);
            // JWT does not exist or it is not valid any longer
            // We should create a new one
            String[] audience = new String[] { "api" };
            LocalDateTime expirationDate = LocalDateTime.now().plus(settings.getJWTLifetimeMs(), ChronoUnit.MILLIS);
            String[] userRoles = usersController.getUserRoles(user).toArray(new String[1]);
            try {
                Map<String, Object> claims = new HashMap<>(3);
                claims.put(Constants.RENEWABLE, false);
                claims.put(Constants.EXPIRY_LEEWAY, settings.getJWTExpLeewaySec());
                claims.put(Constants.ROLES, userRoles);
                token = jwtController.createToken(settings.getJWTSigningKeyName(), false, settings.getJWTIssuer(), audience, DateUtils.localDateTime2Date(expirationDate), DateUtils.localDateTime2Date(DateUtils.getNow()), user.getUsername(), claims, SignatureAlgorithm.valueOf(settings.getJWTSignatureAlg()));
                jupyterJWT = new JupyterJWT(project, user, expirationDate, pidAndPort);
                jupyterJWT.token = token;
                jupyterJWT.tokenFile = tokenFile;
                jwtTokenWriter.writeToken(settings, jupyterJWT);
                LOG.log(Level.FINE, "Generated new Jupyter JWT cause could not recover existing");
            } catch (IOException recIOEx) {
                LOG.log(Level.WARNING, "Failed to recover Jupyter JWT for " + materializedJWT.getIdentifier() + ", generated new valid JWT but failed to write to local filesystem. Invalidating new token!" + " Continue recovering...");
                if (token != null) {
                    try {
                        jwtController.invalidate(token);
                    } catch (InvalidationException jwtInvEx) {
                    // NO-OP
                    }
                }
                failed2recover.add(materializedJWT);
                continue;
            } catch (GeneralSecurityException | JWTException jwtEx) {
                LOG.log(Level.WARNING, "Failed to recover Jupyter JWT for " + materializedJWT.getIdentifier() + ", tried to generate new token and it failed as well. Could not recover! Continue recovering...");
                // Did our best, it's good to know when you should give up
                failed2recover.add(materializedJWT);
                continue;
            }
        }
        addToken(jupyterJWT);
    }
    // Remove from the database entries that we failed to recover
    for (MaterializedJWT failedRecovery : failed2recover) {
        materializedJWTFacade.delete(failedRecovery.getIdentifier());
    }
    LOG.log(INFO, "Finished Jupyter JWT recovery");
}
Also used : Path(java.nio.file.Path) LocalDateTime(java.time.LocalDateTime) JWTException(io.hops.hopsworks.jwt.exception.JWTException) ArrayList(java.util.ArrayList) JupyterProject(io.hops.hopsworks.persistence.entity.jupyter.JupyterProject) Users(io.hops.hopsworks.persistence.entity.user.Users) IOException(java.io.IOException) MaterializedJWT(io.hops.hopsworks.persistence.entity.airflow.MaterializedJWT) JupyterProject(io.hops.hopsworks.persistence.entity.jupyter.JupyterProject) Project(io.hops.hopsworks.persistence.entity.project.Project) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) JupyterSettings(io.hops.hopsworks.persistence.entity.jupyter.JupyterSettings) InvalidationException(io.hops.hopsworks.jwt.exception.InvalidationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Map(java.util.Map) HashMap(java.util.HashMap)

Example 99 with User

use of com.auth0.flickr2.domain.User in project Toy by gmoon92.

the class JwtUtils method generate.

public String generate(User user) {
    try {
        ZonedDateTime today = ZonedDateTime.now();
        String token = JWT.create().withIssuer(apiVersion).withClaim("username", user.getUsername()).withClaim("role", user.getRole().name()).withIssuedAt(Date.from(today.toInstant())).withExpiresAt(Date.from(today.plusDays(DAY_OF_EXPIRATION).toInstant())).sign(algorithm);
        return String.format("%s %s", AuthenticationSchema.BEARER.getName(), token);
    } catch (JWTCreationException e) {
        throw new JWTCreationException("Invalid Signing configuration or Couldn't convert Claims.", e);
    }
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException)

Example 100 with User

use of com.auth0.flickr2.domain.User in project Toy by gmoon92.

the class JwtVerifyFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String token = getToken(request);
    try {
        User user = jwtUtils.decode(token);
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    } catch (JWTVerificationException e) {
        SecurityContextHolder.clearContext();
        getAuthenticationEntryPoint().commence(request, response, new JwtVerifyException(e));
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JwtVerifyException(com.gmoon.resourceserver.jwt.exception.JwtVerifyException) User(com.gmoon.resourceserver.user.User) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)64 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)60 IOException (java.io.IOException)51 Test (org.junit.Test)46 JWT (com.auth0.jwt.JWT)42 Instant (java.time.Instant)39 java.util (java.util)37 Duration (java.time.Duration)36 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)35 Maps (io.gravitee.common.util.Maps)34 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)34 User (io.gravitee.repository.management.model.User)33 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)32 UserRepository (io.gravitee.repository.management.api.UserRepository)30 io.gravitee.rest.api.model (io.gravitee.rest.api.model)30 JWTVerifier (com.auth0.jwt.JWTVerifier)28 MetadataPage (io.gravitee.common.data.domain.MetadataPage)28 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)28 Membership (io.gravitee.repository.management.model.Membership)28 UserStatus (io.gravitee.repository.management.model.UserStatus)28