You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security 始终重定向至登录页问题求助

问题排查与解决方案

问题根源

你的SecurityConfig中配置了auth.anyRequest().authenticated(),这会强制所有请求都需要身份验证,所以即使你认为某些页面不需要登录,也会被重定向到登录页。

修正后的SecurityConfig

package com.example.DevNote.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig  {

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                        // 允许无需登录访问的端点
                        .requestMatchers("/vue/users/register", "/vue/users/login", "/api/users/register").permitAll()
                        // 其余所有请求需要身份验证
                        .anyRequest().authenticated())
                .formLogin(login -> login
                        // 指定自定义登录页面路径
                        .loginPage("/vue/users/login")
                        .permitAll())
                .logout(logout -> logout.permitAll());

        return http.build();
    }

}

关键修改说明

  • 添加requestMatchers配置,明确允许/vue/users/register、/vue/users/login和/api/users/register这三个端点无需登录即可访问。
  • 在formLogin中指定loginPage("/vue/users/login"),确保Spring Security使用你自定义的登录页面,而不是默认的登录页。

额外注意事项

  • 确保你的前端页面(register.html、login.html)放置在Spring Boot默认的静态资源目录(如src/main/resources/templates)下,这样控制器才能正确返回视图。
  • 验证API端点/api/users/register是否能正常接收POST请求,避免因跨域或其他配置问题导致访问失败。

内容的提问来源于stack exchange,提问作者Didimaox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:55:58