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

问题描述 投票:0回答:1

我一直在努力确定一个成员已经在这里做了什么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);
}
spring-security
1个回答
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);

...
}
© www.soinside.com 2019 - 2024. All rights reserved.