Spring Security配置loginPage后无法替换默认登录页问题求助
问题原因及修复方案
- 核心配置错误:你在表单登录配置末尾添加了
.disable()方法,直接关闭了整个表单登录功能,自定义登录页的配置完全不会生效,删除该方法即可。 - 静态资源放行规则错误:
/resources/templates/**是Thymeleaf模板的内部存储路径,不会直接对外暴露,无需放行。你需要调整规则放行static目录下的css、js等静态资源,确保页面样式正常加载。 - 登录表单参数不匹配:Spring Security默认读取请求中
username和password两个参数完成认证,你当前的登录表单输入框没有设置name属性,会导致认证时无法获取账号密码,需要补充对应属性。 - 可选配置:Spring Security默认开启CSRF防护,提交POST请求时需要携带CSRF参数,否则会返回403错误,你可以在表单中添加CSRF隐藏参数,测试阶段也可以临时关闭CSRF防护。
修改后的安全配置类
package configuration; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // 放行登录页和静态资源 .antMatchers("/login", "/*.css", "/*.js", "/static/**").permitAll() .anyRequest().authenticated() .and() // 启用表单登录,删除disable调用 .formLogin() .loginPage("/login") // 登录成功后默认跳转地址,可自行修改 .defaultSuccessUrl("/home", true) .permitAll(); // 测试阶段如果报403可临时取消下面注释关闭CSRF,生产环境建议开启 // http.csrf().disable(); } }
修改后的登录表单部分代码
<form action="/login" class="login_form" method="post"> <h1 class="form_title">Log in</h1> <!-- 开启CSRF时需要添加该隐藏参数 --> <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> <div class="form_group"> <!-- 补充name属性为username --> <input type="text" class="form_input" placeholder=" " name="username"> <label class="form_label">Login</label> </div> <div class="form_group"> <!-- 补充name属性为password --> <input type="password" class="form_input" placeholder=" " name="password"> <label class="form_label">Password</label> </div> <button type="submit" class="form_button">Log in</button> </form>
内容的提问来源于stack exchange,提问作者Serhiiqwe
相关产品推荐
相关产品推荐

