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

开发模式下Spring Security自动认证用户免输凭证方案咨询

在开发环境下自动认证Spring Security保护的REST API(无需登录页)

完全可行,而且不需要修改现有控制器代码,通过标记@Profile("dev")的专属配置类就能实现开发环境的自动登录,具体实现步骤如下:

1. 给原有生产环境配置添加非dev环境限制

修改原WebSecurityConfig,加上@Profile("!dev")注解,确保它只在非开发环境生效:

package com.example.demo;

// Imports...

@Configuration
@EnableWebSecurity
@Profile("!dev") // 仅在非dev环境启用此配置
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((requests) -> requests
                        .anyRequest().authenticated()
                )
                .formLogin((form) -> form
                        .loginPage("/login")
                        .permitAll()
                )
                .logout((logout) -> logout.permitAll());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}

2. 创建开发环境专属的Security配置类

新建DevWebSecurityConfig类,标记@Profile("dev"),通过自定义过滤器自动填充认证信息:

package com.example.demo;

import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.context.annotation.Bean;
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.web.SecurityFilterChain;
import org.springframework.web.filter.GenericFilterBean;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
import java.util.List;

@Configuration
@EnableWebSecurity
@Profile("dev") // 仅在dev环境生效
public class DevWebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(requests -> requests
                        .anyRequest().authenticated()
                )
                // 禁用开发环境不需要的表单登录和登出逻辑
                .formLogin(form -> form.disable())
                .logout(logout -> logout.disable())
                // 添加自动登录过滤器,在用户名密码认证过滤器前执行
                .addFilterBefore(devAutoLoginFilter(), org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 自定义过滤器:自动为未认证请求填充开发用户信息
    private GenericFilterBean devAutoLoginFilter() {
        return new GenericFilterBean() {
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                // 仅当当前无认证信息时自动填充
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 构造开发环境默认用户,可根据需求调整用户名和权限
                    UserDetails devUser = User.withUsername("dev-user")
                            .password("") // 开发环境无需真实密码
                            .authorities(List.of(new SimpleGrantedAuthority("ROLE_USER")))
                            .build();
                    Authentication auth = new UsernamePasswordAuthenticationToken(devUser, null, devUser.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
                chain.doFilter(request, response);
            }
        };
    }
}

3. 激活开发环境Profile

通过以下任意方式激活dev profile:

  • 在application.properties中添加:
    spring.profiles.active=dev
    
  • 启动应用时添加JVM参数:-Dspring.profiles.active=dev
  • 在IDE的启动配置中设置Active Profiles为dev

效果验证

启动应用后直接访问/接口,会自动返回Hello dev-user,无需跳转登录页;切换到非dev环境时,原有表单登录逻辑正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:47:04