如何使Spring security formLogin()使用自定义过滤器

时间:2017-12-31 14:48:30

标签: spring-security

我一直在努力确定一位成员已经在这里做了什么Additional parameters in Spring Security Login,但在我的情况下,我无法使表单身份验证使用过滤器: (我使用的是Spring Boot 1.5.7)

@Override
    protected void configure(HttpSecurity http) throws Exception {          
        http.csrf().disable().authorizeRequests()
                            .anyRequest().authenticated()
                            .and()                              
                            .formLogin().loginPage("/login.html")
                                        .usernameParameter("username")
                                    .passwordParameter("password").permitAll().defaultSuccessUrl("/").failureUrl("/error.html")                             
                            .and()                              
                            .logout().logoutUrl("/logout");
        http.addFilterBefore(new WebAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

始终直接传递给UserDetailsS​​ervice实现,而不通过过滤器。此外,我一直在尝试使用Bean而不是' new',但结果是一样的:

http.addFilterBefore(webAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
@Bean
public WebAuthenticationFilter webAuthenticationFilter() throws Exception {
    WebAuthenticationFilter auth = new WebAuthenticationFilter();
    auth.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
    auth.setAuthenticationManager(authenticationManagerBean());
    return auth;
}

我的自定义过滤器是UsernamePasswordAuthenticationFilter的扩展,并且在方法的覆盖中尝试验证此方法永远不会调用:

@Override
public Authentication attemptAuthentication(HttpServletRequest request,
        HttpServletResponse response) throws AuthenticationException {
    tenant = request.getParameter("selectTenant");
    System.out.println("We are here WebAuthenticationFilter");
    request.getSession().setAttribute(TENANT_KEY, tenant);      
    return super.attemptAuthentication(request, response);
}

1 个答案:

答案 0 :(得分:0)

唯一有效的解决方案是将HttpServletRequest类注入到我的UserDetailsS​​ervice实现中,所以我在这里从请求中获取新参数。

public class myImpleentUserDetailsService implements UserDetailsService (

@Autowired(required = false)
private HttpServletRequest request;

public UserDetail loadUserVyUsername(String username) throws UsernameNotFoundException{
    String myparameter = request.getParameter("myParameter");

    request.setAttribute("app-parameter", myparameter);

    user = userService.findById(username, myparameter);

...
}