使用Spring Security实现登录失败后跳转至/login?error
解决Spring Security登录失败跳转/login?error无效的问题
看起来你遇到的问题是Spring Security登录失败后没有自动跳转到带error参数的登录页,不过手动访问能正常显示错误信息——这说明错误提示的逻辑是没问题的,问题大概率出在登录失败的跳转配置上。我来帮你梳理下可能的原因和解决办法:
检查表单登录的failureUrl配置
你需要在formLogin()的配置链中明确指定登录失败后的跳转地址。如果你的代码里没加这一步,Spring Security可能没有触发正确的跳转。修改你的configure(HttpSecurity)方法,补充failureUrl("/login?error"):@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .formLogin() // 开启表单登录配置 .loginPage("/login") // 如果使用了自定义登录页,必须指定这一项 .failureUrl("/login?error") // 关键配置:指定登录失败后的跳转地址 .permitAll(); // 允许所有用户访问登录页面 }确认登录表单的请求配置
确保你的登录表单的action属性是正确的(默认是/login,如果自定义了loginProcessingUrl要对应),并且请求方法是POST,用户名和密码的输入框name属性分别是username和password(如果没自定义参数名的话)。比如表单代码应该类似:<form action="/login" method="post"> <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <button type="submit">登录</button> </form>排查自定义认证失败处理器的干扰
如果你在配置中自定义了AuthenticationFailureHandler,那么默认的跳转逻辑会被覆盖,这时候需要在处理器里手动实现跳转逻辑:@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .failureHandler((request, response, exception) -> { // 手动跳转到带error参数的登录页 response.sendRedirect("/login?error"); }) .permitAll(); }
按照上面的步骤调整配置后,应该就能实现登录失败自动跳转到/login?error的效果了。
内容的提问来源于stack exchange,提问作者user9565299
相关产品推荐
相关产品推荐

