项目场景:
想要实现 前台输入用户名密码,后台进行认证,然后登陆成功跳转功能
前提:用户名字段username,密码是pwd(问题就在这,跟往常password不同)
问题:前台输入用户名和密码之后,后台只能接收到用户名,接收不到前台输入的密码(pwd)字段
血泪教训:取名尽量还是要规范,不然会导致框架识别不到这个字段的值
问题描述
前台输入用户名和密码之后,后台只能接收到用户名,接收不到前台输入的密码(pwd)字段
可以看到,前台肯定是已经传入了参数,但是后台就是识别不到。
原因分析:
应该是speingsecurity默认识别的密码,是按照password来识别的,所以识别不到。需要通过springsecurityConfig里面的配置进行修改,覆盖默认的字段名
下面是没设置时候的代码:
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
//首页所有人都可以访问,功能页只有有权限的人才能访问
httpSecurity
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/","/index").permitAll()
.requestMatchers("/toLogin","/toLoginPage").permitAll()
.requestMatchers("/level1/**","/level2/**","/level3/**").hasRole("root")
.requestMatchers("/level2/**").hasRole("admin")
//对静态资源的过滤
.requestMatchers("/css/**","/js/**","/views/**").permitAll()
.requestMatchers("/views/login.html").permitAll()
.anyRequest().authenticated()
//没有权限默认回到登陆页面,也可以不传参数,默认是login.html页面
).formLogin(form -> form.loginPage("/toLoginPage")
//处理前端跳转页面,要跟form表单里的action相同
.loginProcessingUrl("/toLogin")
.csrf(csrf -> csrf.disable());
return httpSecurity.build();
}
可以看到,在FormLoginConfigurer.java里面,默认接收密码的参数是passwordParameter
解决方案:
通过.passwordParameter(“pwd”)通过这个指定了密码对应的参数是pwd,完成设置之后就可以看到,接收到参数了
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
//首页所有人都可以访问,功能页只有有权限的人才能访问
httpSecurity
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/","/index").permitAll()
.requestMatchers("/toLogin","/toLoginPage").permitAll()
.requestMatchers("/level1/**","/level2/**","/level3/**").hasRole("root")
.requestMatchers("/level2/**").hasRole("admin")
//对静态资源的过滤
.requestMatchers("/css/**","/js/**","/views/**").permitAll()
.requestMatchers("/views/login.html").permitAll()
.anyRequest().authenticated()
//没有权限默认回到登陆页面,也可以不传参数,默认是login.html页面
).formLogin(form -> form.loginPage("/toLoginPage")
//处理前端跳转页面,要跟form表单里的action相同
.loginProcessingUrl("/toLogin")
.passwordParameter("pwd")
.usernameParameter("username"))
.csrf(csrf -> csrf.disable());
return httpSecurity.build();
}