복붙노트

[SPRING] 스프링 보안을 사용하는 IP 필터

SPRING

스프링 보안을 사용하는 IP 필터

스프링 보안을 사용하여 IP로 내 웹 애플리케이션에 대한 사용자의 액세스를 필터링하는 방법에 대해 궁금합니다. 내가 AbstractAuthenticationProcessingFilter 또는 그와 비슷한 것을 확장하고 그것을 내 방식대로 재정의해야 하는가? 그렇다면 web.xml에서 필터 설명의 확장 및 예제에 대한 예제를 제공 할 수 있습니까? 미리 감사드립니다.

추신 내 응용 프로그램에서는 (기본 org.springframework.web.filter.DelegatingFilterProxy를 사용하는) 스프링 보안 지원도 있지만, 사용자 자격 증명뿐만 아니라 IP도 확인하고 싶습니다.

해결법

  1. ==============================

    1.이것을 할 수있는 한 가지 방법은 Spring Security의 Web Security Expressions를 사용하는 것입니다. 예 :

    이것을 할 수있는 한 가지 방법은 Spring Security의 Web Security Expressions를 사용하는 것입니다. 예 :

    <http use-expressions="true">
        <intercept-url pattern="/admin*"
            access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/>
        ...
    </http>
    
  2. ==============================

    2.Anshu의 대답은 ip로 사용자를 인증하는 좋은 방법이지만 CAS 인증에서는 작동하지 않을 수 있습니다. 필터를 사용하면이 상황에 더 적합한 다른 해결책이 있습니다.

    Anshu의 대답은 ip로 사용자를 인증하는 좋은 방법이지만 CAS 인증에서는 작동하지 않을 수 있습니다. 필터를 사용하면이 상황에 더 적합한 다른 해결책이 있습니다.

    public class IPAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
        private AuthenticationUserDetailsService<CasAssertionAuthenticationToken> authenticationUserDetailsService;
        private static Set<String> ipWhitelist;
    
        @Autowired
        private AppProperty appProperty;
    
        @PostConstruct
        public void init() {
            ipWhitelist = new HashSet<>(Arrays.asList(appProperty.getIpWhitelist()));
            setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
                @Override
                public void onAuthenticationSuccess(
                        HttpServletRequest httpServletRequest,
                        HttpServletResponse httpServletResponse,
                        Authentication authentication) throws IOException, ServletException {
                    // do nothing
                }
            });
        }
    
        public IPAuthenticationFilter() {
            super("/");
        }
    
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
                throws AuthenticationException, IOException {
            String userName = request.getHeader(appProperty.getHeaderCurUser());
            Assertion assertion = new AssertionImpl(userName);
            CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "");
            UserDetails userDetails = authenticationUserDetailsService.loadUserDetails(token);
    
            CasAuthenticationToken result = new CasAuthenticationToken(
                    "an-id-for-ip-auth",
                    userDetails,
                    request.getRemoteAddr(),
                    userDetails.getAuthorities(),
                    userDetails,
                    assertion
            );
            return result;
        }
    
        protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
            String userName = request.getHeader(appProperty.getHeaderCurUser());
            return ipWhitelist.contains(request.getRemoteAddr()) && !StringUtils.isEmpty(userName);
        }
    
        protected void successfulAuthentication(
                HttpServletRequest request,
                HttpServletResponse response,
                FilterChain chain,
                Authentication authResult) throws IOException, ServletException {
            super.successfulAuthentication(request, response, chain, authResult);
            chain.doFilter(request, response);
        }
    
        public AuthenticationUserDetailsService<CasAssertionAuthenticationToken> getAuthenticationUserDetailsService() {
            return authenticationUserDetailsService;
        }
    
        public void setAuthenticationUserDetailsService(
                AuthenticationUserDetailsService<CasAssertionAuthenticationToken> authenticationUserDetailsService) {
            this.authenticationUserDetailsService = authenticationUserDetailsService;
        }
    }
    

    다음과 같이 cas 앞에이 필터를 추가 할 수 있습니다.

    http.addFilterBefore(ipAuthenticationFilter(), CasAuthenticationFilter.class)
    
  3. from https://stackoverflow.com/questions/12786123/ip-filter-using-spring-security by cc-by-sa and MIT license