Search in sources :

Example 11 with Tokens

use of com.auth0.Tokens in project UPE_2021_2_Propague by netrometro.

the class AuthenticationCustomFilter method successfulAuthentication.

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication autenticacao) throws IOException, ServletException {
    User user = (User) autenticacao.getPrincipal();
    Algorithm algoritmo = Algorithm.HMAC256("secret".getBytes());
    String tokenAcesso = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipos", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algoritmo);
    String tokenRefresh = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).sign(algoritmo);
    Map<String, String> tokens = new HashMap<>();
    tokens.put("token_acesso", tokenAcesso);
    tokens.put("token_refresh", tokenRefresh);
    tokens.put("email_usuario", user.getUsername());
    response.setContentType(MediaType.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 12 with Tokens

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

the class UserServiceImpl method delete.

@Override
public void delete(String id) {
    try {
        // If the users is PO of apps or apis, throw an exception
        long apiCount = apiService.findByUser(id, null, false).stream().filter(entity -> entity.getPrimaryOwner().getId().equals(id)).count();
        long applicationCount = applicationService.findByUser(id).stream().filter(app -> app.getPrimaryOwner() != null).filter(app -> app.getPrimaryOwner().getId().equals(id)).count();
        if (apiCount > 0 || applicationCount > 0) {
            throw new StillPrimaryOwnerException(apiCount, applicationCount);
        }
        Optional<User> optionalUser = userRepository.findById(id);
        if (!optionalUser.isPresent()) {
            throw new UserNotFoundException(id);
        }
        membershipService.removeMemberMemberships(MembershipMemberType.USER, id);
        User user = optionalUser.get();
        // remove notifications
        portalNotificationService.deleteAll(user.getId());
        portalNotificationConfigService.deleteByUser(user.getId());
        genericNotificationConfigService.deleteByUser(user);
        // remove tokens
        tokenService.revokeByUser(user.getId());
        // change user datas
        user.setSourceId("deleted-" + user.getSourceId());
        user.setStatus(UserStatus.ARCHIVED);
        user.setUpdatedAt(new Date());
        if (anonymizeOnDelete) {
            User anonym = new User();
            anonym.setId(user.getId());
            anonym.setCreatedAt(user.getCreatedAt());
            anonym.setUpdatedAt(user.getUpdatedAt());
            anonym.setStatus(user.getStatus());
            anonym.setSource(user.getSource());
            anonym.setLastConnectionAt(user.getLastConnectionAt());
            anonym.setSourceId("deleted-" + user.getId());
            anonym.setFirstname("Unknown");
            anonym.setLastname("");
            anonym.setLoginCount(user.getLoginCount());
            user = anonym;
        }
        userRepository.update(user);
        final UserEntity userEntity = convert(optionalUser.get(), false);
        searchEngineService.delete(userEntity, false);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to delete user", ex);
        throw new TechnicalManagementException("An error occurs while trying to delete user", ex);
    }
}
Also used : BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) StringUtils(org.apache.commons.lang3.StringUtils) UPDATE(io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE) IdentityProviderService(io.gravitee.rest.api.service.configuration.identity.IdentityProviderService) TemplateEngine(io.gravitee.el.TemplateEngine) Algorithm(com.auth0.jwt.algorithms.Algorithm) AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) PortalHook(io.gravitee.rest.api.service.notification.PortalHook) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) Collectors.toSet(java.util.stream.Collectors.toSet) ApplicationSettings(io.gravitee.rest.api.model.application.ApplicationSettings) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) JsonPathFunction(io.gravitee.el.spel.function.json.JsonPathFunction) Instant(java.time.Instant) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) Collectors(java.util.stream.Collectors) Key(io.gravitee.rest.api.model.parameters.Key) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) DatatypeConverter(javax.xml.bind.DatatypeConverter) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Pageable(io.gravitee.rest.api.model.common.Pageable) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) InitializingBean(org.springframework.beans.factory.InitializingBean) Value(org.springframework.beans.factory.annotation.Value) JWTVerifier(com.auth0.jwt.JWTVerifier) ReadContext(com.jayway.jsonpath.ReadContext) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) Query(io.gravitee.rest.api.service.search.query.Query) UuidString(io.gravitee.rest.api.service.common.UuidString) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) JsonPath(com.jayway.jsonpath.JsonPath) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MetadataPage(io.gravitee.common.data.domain.MetadataPage) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) USER(io.gravitee.repository.management.model.Audit.AuditProperties.USER) ChronoUnit(java.time.temporal.ChronoUnit) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) UserCriteria(io.gravitee.repository.management.api.search.UserCriteria) User(io.gravitee.repository.management.model.User) ACTION(io.gravitee.rest.api.service.common.JWTHelper.ACTION) QueryBuilder(io.gravitee.rest.api.service.search.query.QueryBuilder) SearchResult(io.gravitee.rest.api.service.impl.search.SearchResult) User(io.gravitee.repository.management.model.User) TechnicalException(io.gravitee.repository.exceptions.TechnicalException)

Example 13 with Tokens

use of com.auth0.Tokens in project DragonProxy by DragonetMC.

the class LoginChainDecoder method decode.

/**
 * decode the chain data in Login packet for MCPE Note: the credit of this
 * function goes to Nukkit development team
 */
public void decode() {
    Map<String, List<String>> map = gson.fromJson(new String(this.chainJWT, StandardCharsets.UTF_8), new TypeToken<Map<String, List<String>>>() {
    }.getType());
    if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty())
        return;
    List<DecodedJWT> chainJWTs = new ArrayList<>();
    // Add the JWT tokens to a chain
    for (String token : map.get("chain")) chainJWTs.add(JWT.decode(token));
    DecodedJWT clientJWT = null;
    if (this.clientDataJWT != null) {
        clientJWT = JWT.decode(new String(this.clientDataJWT, StandardCharsets.UTF_8));
        chainJWTs.add(clientJWT);
    }
    // first step, check if the public provided key can decode the received chain
    try {
        ECPublicKey prevPublicKey = null;
        for (DecodedJWT jwt : chainJWTs) {
            JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
            String encodedPublicKey = null;
            ECPublicKey publicKey = null;
            if (payload.has("identityPublicKey")) {
                encodedPublicKey = payload.get("identityPublicKey").getAsString();
                publicKey = (ECPublicKey) EC_KEY_FACTORY.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedPublicKey)));
            }
            // Trust the root ca public key and use it to verify the chain
            if (ENCODED_ROOT_CA_KEY.equals(encodedPublicKey) && payload.has("certificateAuthority") && payload.get("certificateAuthority").getAsBoolean()) {
                prevPublicKey = publicKey;
                continue;
            }
            // This will happen if the root ca key we have does not match the one presented by the client chain
            if (prevPublicKey == null)
                throw new NullPointerException("No trusted public key found in chain, is the client logged in or cracked");
            // Throws a SignatureVerificationException if the verification failed
            Algorithm.ECDSA384(prevPublicKey, null).verify(jwt);
            // Verification was successful since no exception was thrown
            // Set the previous public key to this one so that it can be used
            // to verify the next JWT token in the chain
            prevPublicKey = publicKey;
        }
        // The for loop successfully verified all JWT tokens with no exceptions thrown
        this.loginVerified = true;
        Logger.getLogger(this.getClass().getSimpleName()).info("The LoginPacket has been successfully verified for integrity");
    } catch (Exception e) {
        this.loginVerified = false;
        Logger.getLogger(this.getClass().getSimpleName()).info("Failed to verify the integrity of the LoginPacket");
        e.printStackTrace();
    }
    // This is in its own for loop due to the possibility that the chain verification failed
    for (DecodedJWT jwt : chainJWTs) {
        JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
        // Get the information we care about - The UUID and display name
        if (payload.has("extraData") && !payload.has("certificateAuthority")) {
            extraData = payload.get("extraData").getAsJsonObject();
            if (extraData.has("displayName"))
                this.username = extraData.get("displayName").getAsString();
            if (extraData.has("identity"))
                this.clientUniqueId = UUID.fromString(extraData.get("identity").getAsString());
            break;
        }
    }
    // debug purpose
    if (log_profiles_files) {
        try {
            BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".rawChainJTW"));
            writer1.write(getChainJWT());
            writer1.close();
            BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + ".rawClientDataJTW"));
            writer.write(getClientDataJWT());
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // debug purpose
        int index = 0;
        for (DecodedJWT jwt : chainJWTs) {
            JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + "_" + index + ".decodedChain"));
                writer.write(payload.toString());
                writer.close();
                index++;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    // client data & skin
    if (clientJWT != null) {
        this.clientData = gson.fromJson(new String(Base64.getDecoder().decode(clientJWT.getPayload()), StandardCharsets.UTF_8), JsonObject.class);
        // debug purpose
        if (log_profiles_files) {
            try {
                BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".decodedData"));
                writer1.write(this.clientData.toString());
                writer1.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if (this.clientData.has("ClientRandomId"))
            this.clientId = this.clientData.get("ClientRandomId").getAsLong();
        if (this.clientData.has("SkinData") && this.clientData.has("SkinId")) {
            this.skin = new Skin(this.clientData.get("SkinData").getAsString(), this.clientData.get("SkinId").getAsString());
            if (this.clientData.has("CapeData"))
                this.skin.setCape(this.skin.new Cape(Base64.getDecoder().decode(this.clientData.get("CapeData").getAsString())));
        } else
            this.skin = Skin.DEFAULT_SKIN_STEVE;
        if (this.clientData.has("SkinGeometryName"))
            this.skinGeometryName = this.clientData.get("SkinGeometryName").getAsString();
        if (this.clientData.has("SkinGeometry"))
            this.skinGeometry = Base64.getDecoder().decode(this.clientData.get("SkinGeometry").getAsString());
    }
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) BufferedWriter(java.io.BufferedWriter) ECPublicKey(java.security.interfaces.ECPublicKey) TypeToken(com.google.gson.reflect.TypeToken) ArrayList(java.util.ArrayList) List(java.util.List) Skin(org.dragonet.common.data.entity.Skin) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 14 with Tokens

use of com.auth0.Tokens 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 15 with Tokens

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

the class TimeLimitedAccessTokenFactory method decide.

<T> T decide(String token, Supplier<T> good, Supplier<T> bad) {
    if (token == null) {
        return bad.get();
    }
    DecodedJWT decoded;
    try {
        decoded = verifier.verify(token);
    } catch (JWTVerificationException e) {
        return bad.get();
    }
    Claim claim = decoded.getClaim(USERNAME);
    if (claim.isNull()) {
        throw new IllegalStateException(("All valid jwt tokens must have a username claim"));
    }
    if (bannedUsernames.contains(claim.asString())) {
        return bad.get();
    }
    return good.get();
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)13 HashMap (java.util.HashMap)8 Test (org.junit.jupiter.api.Test)7 Algorithm (com.auth0.jwt.algorithms.Algorithm)6 TokenHolder (com.auth0.json.auth.TokenHolder)4 TokenRequest (com.auth0.net.TokenRequest)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 Date (java.util.Date)4 JWT (com.auth0.jwt.JWT)3 JWTVerifier (com.auth0.jwt.JWTVerifier)3 ServiceAuthorizationException (com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)3 AccountBO (com.nexblocks.authguard.service.model.AccountBO)3 User (org.springframework.security.core.userdetails.User)3 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)2 Claim (com.auth0.jwt.interfaces.Claim)2 JsonPath (com.jayway.jsonpath.JsonPath)2 ReadContext (com.jayway.jsonpath.ReadContext)2 JwtConfig (com.nexblocks.authguard.service.config.JwtConfig)2 StrategyConfig (com.nexblocks.authguard.service.config.StrategyConfig)2 AuthResponseBO (com.nexblocks.authguard.service.model.AuthResponseBO)2