Как убедиться, что прокси-фильтр работает, когда запросы поступают только от одного указанного c приложения - PullRequest
0 голосов
/ 19 февраля 2020

В одном из моих приложений есть функционал для суперпользователей, позволяющий им прокси других пользователей. для этой функции в моем приложении есть прокси-фильтр, который проверяет, что если пользователь A находится в режиме прокси, он возвращает идентификатор пользователя прокси (Пользователь B) вместо обычного идентификатора пользователя (Пользователь A), пока мы не остановим прокси.

Некоторые другие приложения используют наш API для получения данных. Теперь проблема в том, что когда пользователь A находится в режиме прокси и в это время кто-то хочет получить доступ к нашему API, он возвращает данные A вместо пользователя, вошедшего в систему (пользователь B).

Как я могу изолировать прокси-фильтр, чтобы он разрешал запросы, поступающие только от нашего приложения.

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    log.debug("Inside of ProxyUserFilter.doFilter...");
    Long userId = SecurityHelper.getUserId();



        Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();

        log.debug("User id = " + userId);

        try {
            if (currentAuth != null && userId != null && userId != -1) {

                log.debug("Is User Impersonated? " + SecurityHelper.isImpersonated());
                if (SecurityHelper.isImpersonated()) {
                    Long impersonator = SecurityHelper.getImpersonatorId();
                    log.debug("Impersonator " + SecurityHelper.getImpersonatorId());
                    if (impersonator != null && impersonator != -1) {
                        Impersonation impersonation = getImpersonation(impersonator);

                        // if null comes back from DB, then proxy was stopped.
                        if (impersonation == null) {
                            log.debug("Proxy was stopped, switching back to orignal user.");
                            // finish proxy, change back to impersonator and continue filter chain

                            Authentication original = getSourceAuthentication(currentAuth);

                            if (original == null) {
                                throw new AuthenticationCredentialsNotFoundException(
                                        "Could not find original user for impersonation.");
                            }

                            // update the current context back to the original user
                            SecurityContextHolder.getContext().setAuthentication(original);

                            log.debug("Switched back to original user");
                            chain.doFilter(request, response);
                            return;
                        }
                    }
                }

                // make call to DB to get any proxy....
                Impersonation impersonation = getImpersonation(userId);
                if (impersonation != null && impersonation.getImpersonateeUsrId() != null
                        && impersonation.getImpersonateeUsrId() != -1) {
                    log.debug("Found active impersonation for " + userId);
                    Integer impersonateeUserId = impersonation.getImpersonateeUsrId();

                    UserDetails targetUserDetails = userDetailsService
                            .loadUserByUsername(impersonateeUserId.toString());
                    // targetUserDetails.getUsername();

                    GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(this.switchAuthorityRole,
                            currentAuth);

                    // get the original authorities
                    Collection<? extends GrantedAuthority> orig = targetUserDetails.getAuthorities();

                    // add the new switch user authority
                    List<GrantedAuthority> newAuths = new ArrayList<GrantedAuthority>(orig);
                    newAuths.add(switchAuthority);

                    // create authentication
                    Authentication targetUser = new UsernamePasswordAuthenticationToken(targetUserDetails,
                            targetUserDetails.getPassword(), newAuths);
                    // log.debug(targetUser.getPrincipal());

                    // switch the context to the new user
                    SecurityContextHolder.getContext().setAuthentication(targetUser);

                    log.debug("Switched to impersonatee user");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Failed to check impersonation...");
        }
        log.debug("Finished ProxyUserFilter...");

    chain.doFilter(request, response);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...