복붙노트

[SPRING] java config에 http 보안 필터 추가

SPRING

java config에 http 보안 필터 추가

나는 봄에 웹 보안을 추가하려고하지만 필터가 특정 것에 적용되는 것을 원하지 않는다. 어떻게 자바에서 그 일을합니까?

그리고 아마도 맞춤 필터를 만들었으므로 더 좋은 방법이있을 수 있습니다. 그러나 이것이 의존성으로 인해 인스턴스화 할 수있는 유일한 방법입니다.

전반적으로, 내가하고 싶은 것은 이것입니다 :

/ resources / ** 필터를 통과해서는 안되며, / login (POST)은 필터를 통과해서는 안되며, 그 외 모든 것은 필터를 통과해야한다.

봄을 통해 발견 된 여러 가지 예를 통해 나는 이것을 시작 할 수 있었지만 분명히 효과가 없다.

@Configuration
@EnableWebSecurity
@Import(MyAppConfig.class)
public class MySecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        webSecurity.ignoring().antMatchers("/resources/**");
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/login").permitAll();

        httpSecurity.httpBasic();
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    @Autowired
    public TokenFilterSecurityInterceptor<TokenInfo> tokenInfoTokenFilterSecurityInterceptor(MyTokenUserInfoCache userInfoCache, ServerStatusService serverStatusService, HttpSecurity httpSecurity) throws Exception
    {
        TokenService<TokenInfo> tokenService = new TokenServiceImpl(userInfoCache);
        TokenFilterSecurityInterceptor<TokenInfo> tokenFilter = new TokenFilterSecurityInterceptor<TokenInfo>(tokenService, serverStatusService, "RUN_ROLE");
        httpSecurity.addFilter(tokenFilter);
        return tokenFilter;
    }
}

해결법

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

    1.URL을 무시하는 모든 Spring Security에 관심이 있습니까? 아니면 특정 필터가 요청을 무시하기를 원하십니까? 모든 Spring Security가 요청을 무시하기를 원하면 다음을 사용하여 수행 할 수 있습니다 :

    URL을 무시하는 모든 Spring Security에 관심이 있습니까? 아니면 특정 필터가 요청을 무시하기를 원하십니까? 모든 Spring Security가 요청을 무시하기를 원하면 다음을 사용하여 수행 할 수 있습니다 :

    @Configuration
    @EnableWebSecurity
    @Import(MyAppConfig.class)
    public class MySecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private MyTokenUserInfoCache userInfoCache;
        @Autowired
        private ServerStatusService serverStatusService;
    
        @Override
        public void configure(WebSecurity webSecurity) throws Exception
        {
            webSecurity
                .ignoring()
                    // All of Spring Security will ignore the requests
                    .antMatchers("/resources/**")
                    .antMatchers(HttpMethod.POST, "/login");
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .addFilter(tokenInfoTokenFilterSecurityInterceptor())
                .authorizeRequests()
                    // this will grant access to GET /login too do you really want that?
                    .antMatchers("/login").permitAll()
                    .and()
                .httpBasic().and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    
        @Bean
        public TokenFilterSecurityInterceptor<TokenInfo> tokenInfoTokenFilterSecurityInterceptor() throws Exception
        {
            TokenService<TokenInfo> tokenService = new TokenServiceImpl(userInfoCache);
            return new TokenFilterSecurityInterceptor<TokenInfo>(tokenService, serverStatusService, "RUN_ROLE");
        }
    }
    

    특정 필터 만 특정 요청을 무시하도록하려면 다음과 같이 할 수 있습니다.

    @Configuration
    @EnableWebSecurity
    @Import(MyAppConfig.class)
    public class MySecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private MyTokenUserInfoCache userInfoCache;
        @Autowired
        private ServerStatusService serverStatusService;
    
        @Override
        public void configure(WebSecurity webSecurity) throws Exception
        {
            webSecurity
                .ignoring()
                    // ... whatever is here is ignored by All of Spring Security
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .addFilter(tokenInfoTokenFilterSecurityInterceptor())
                .authorizeRequests()
                    // this will grant access to GET /login too do you really want that?
                    .antMatchers("/login").permitAll()
                    .and()
                .httpBasic().and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    
        @Bean
        public TokenFilterSecurityInterceptor<TokenInfo> tokenInfoTokenFilterSecurityInterceptor() throws Exception
        {
            TokenService<TokenInfo> tokenService = new TokenServiceImpl(userInfoCache);
            TokenFilterSecurityInterceptor tokenFilter new TokenFilterSecurityInterceptor<TokenInfo>(tokenService, serverStatusService, "RUN_ROLE");
    
    
            RequestMatcher resourcesMatcher = new AntPathRequestMatcher("/resources/**");
            RequestMatcher posLoginMatcher = new AntPathRequestMatcher("/login", "POST");
            RequestMatcher ignored = new OrRequestMatcher(resourcesMatcher, postLoginMatcher);
            return new DelegateRequestMatchingFilter(ignored, tokenService);
        }
    }
    
    
    public class DelegateRequestMatchingFilter implements Filter {
        private Filter delegate;
        private RequestMatcher ignoredRequests;
    
        public DelegateRequestMatchingFilter(RequestMatcher matcher, Filter delegate) {
            this.ignoredRequests = matcher;
            this.delegate = delegate;
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
             HttpServletRequest request = (HttpServletRequest) req;
             if(ignoredRequests.matches(request)) {
                 chain.doFilter(req,resp,chain);
             } else {
                 delegate.doFilter(req,resp,chain);
             }
        }
    }
    
  2. ==============================

    2.1 봄 보안의 xml 설정에서 나는 사용한다.

    1 봄 보안의 xml 설정에서 나는 사용한다.

    <http pattern="/resources/**" security="none"/> 
    
    <http use-expressions="true">
    <intercept-url pattern="/login" access="permitAll"/> 
    </http>    
    

    보안 검사에서 검색 할 수 있습니다.

    2 그런 다음 봄 구성에 mvc : resource 태그를 추가하십시오.

    <mvc:resources mapping="/resource/**" location="/resource/"/>
    

    중요 :이 구성은 url이 발송자 서블릿에 의해 처리되는 경우에만 작동합니다. 즉, web.xml에서

       <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping> 
    
  3. from https://stackoverflow.com/questions/19917671/add-http-security-filter-in-java-config by cc-by-sa and MIT license