需求说明
使用SpingBoot+SpringSecurity的项目中,默认的登录处理url是/login,现在因为项目的部署的要求,需求修改成类似这样的二级目录:/some-path/login
一般来说,这样的需求是在SpringSecurity的一个Config类里面配置的:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private LoginFilter userAuthenticationFilterBean() throws Exception { LoginFilter userAuthenticationFilter = new LoginFilter(); userAuthenticationFilter.setFilterProcessesUrl("/some-path/login"); // 自定义登录处理的url userAuthenticationFilter.setAuthenticationManager(super.authenticationManager()); //登录成功的处理 userAuthenticationFilter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandler); //登录失败的处理 userAuthenticationFilter.setAuthenticationFailureHandler(loginFailureHandler); return userAuthenticationFilter; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { // 其他配置没有写,省略 httpSecurity .authorizeRequests() .antMatchers("/some-path/login") // 允许访问不拦截 .permitAll().and() .addFilterAt(userAuthenticationFilterBean(), UsernamePasswordAuthenticationFilter.class) // 用户登录拦截 .authorizeRequests(); } }
但是发现问题,就是并不生效。
经过排查和踩坑,发现还有几个注意事项,现在分享出来,节约各位的时间!
- 需要关闭formLogin,formLogin是spring security自带的form提交登录信息的处理,我们使用springboot,一般来说是使用ajax API请求来处理登录的
- 第二个注意事项是(这个是自己和同事探索出来的):二级目录不能使用-这种特殊字符,如果实在有需要,可以用_代替,例如:"/some-path/login" 改成 "/some_path/login"
所以正确的config应该是:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private LoginFilter userAuthenticationFilterBean() throws Exception { LoginFilter userAuthenticationFilter = new LoginFilter(); userAuthenticationFilter.setFilterProcessesUrl("/some_path/login"); // 自定义登录处理的url userAuthenticationFilter.setAuthenticationManager(super.authenticationManager()); //登录成功的处理 userAuthenticationFilter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandler); //登录失败的处理 userAuthenticationFilter.setAuthenticationFailureHandler(loginFailureHandler); return userAuthenticationFilter; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .antMatchers("/some_path/login") // 允许访问不拦截 .permitAll().and() .formLogin().disable() // 关闭formLogin .addFilterAt(userAuthenticationFilterBean(), UsernamePasswordAuthenticationFilter.class) // 用户登录拦截 .authorizeRequests(); } }
文章评论