给 Spring security 添加过滤器实现多租户

luc*_*uca 5 java spring spring-mvc spring-security multi-tenant

我需要更新我的 Spring Security 配置以引入多租户管理(我获取每个 Web 请求的 URL,并通过配置文件检索正确的架构)。所以我在我的 spring 安全配置中添加了一个过滤器(因为使用处理程序,登录页面没有正确的架构,因为处理程序是在 spring 安全之后调用的),但现在我捕获了 URL,设置了架构,但页面仍然是空的并且没有'不重定向到登录页面,如果我写 /login 也不会出现 HTML 页面。

这是我配置 spring 安全性的方式:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private RoleServices roleServices;
    @Autowired
    private CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth)throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
        .passwordEncoder(passwordEncoder())
        .usersByUsernameQuery("select username,password,enabled from user where username=?")
        .authoritiesByUsernameQuery("select u.username, CONCAT('ROLE_' , r.role) from user u inner join role r on u.idRole = r.idRole where lower(u.username) = lower(?)");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
        //Spring Security ignores request to static resources such as CSS or JS files.
        .ignoring()
        .antMatchers("/static/**","/users/{\\d+}/password/recover","/users/{\\d+}/token/{\\d+}/password/temporary")
        .antMatchers(HttpMethod.PUT,"/users/{\\d+}/token/{\\d+}/password/temporary");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<Role> roles=roleServices.getRoles();
        //Retrieve array of roles(only string field without id)
        String[] rolesArray = new String[roles.size()];
        int i=0;
        for (Role role:roles){
            rolesArray[i++] = role.getRole();
        }

        http
           .authorizeRequests() //Authorize Request Configuration
           .anyRequest().hasAnyRole(rolesArray)//.authenticated()
        .and()//Login Form configuration for all others
           .formLogin()
           .loginPage("/login").successHandler(customSuccessHandler)
        //important because otherwise it goes in a loop because login page require authentication and authentication require login page
           .permitAll()
        .and()
           .exceptionHandling().accessDeniedPage("/403")
        .and()
           .logout()
           .logoutSuccessUrl("/login?logout")
           .deleteCookies("JSESSIONID", "JSESSIONID")
           .invalidateHttpSession(true)
           .permitAll()
        .and()
           .sessionManagement().invalidSessionUrl("/login")
        .and()
           .addFilterAfter(new MultiTenancyInterceptor(), BasicAuthenticationFilter.class);

            }
        }
Run Code Online (Sandbox Code Playgroud)

MultiTenancyInterceptor在设置租户的地方添加了过滤器

@Component
public class MultiTenancyInterceptor extends OncePerRequestFilter   {

    @Override
    public void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain)
            throws IOException, ServletException {  
        String url = request.getRequestURL().toString();
        URI uri;
        try {
            uri = new URI(url);
            String domain = uri.getHost();
            if(domain!=null){
                TenantContext.setCurrentTenant(domain);
            }   
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }   
}
Run Code Online (Sandbox Code Playgroud)

但是当我编写登录页面的控制器时,没有收到调用:

@Override
@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String loginPage(){
    return "login";
}
Run Code Online (Sandbox Code Playgroud)

你看到我的configure方法有错误吗?如果您需要更多信息,我可以添加其他类。谢谢 PS:我注意到doFilter每个页面请求都会调用两次

luc*_*uca 0

在dur的建议之后我添加了代码

filterChain.doFilter(request, response);
Run Code Online (Sandbox Code Playgroud)

在过滤方法的最后