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

使用Spring Security OAuth2开发REST API,如何移除Basic认证?

移除Spring Security OAuth2的Basic认证,支持请求体传参获取令牌

嘿,我来帮你搞定这个问题!你想移除Spring Security OAuth2里的Basic认证,改成直接在Postman请求体里传用户名密码拿令牌,其实只需要调整授权服务器的几个配置项就行,我给你一步步说清楚:

1. 配置授权服务器核心规则

首先,你需要一个继承AuthorizationServerConfigurerAdapter并标注@EnableAuthorizationServer的配置类(如果还没加的话),核心是开启表单认证支持,关闭Basic认证的强制要求:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final PasswordEncoder passwordEncoder; // 生产环境必须配置密码编码器

    // 构造注入依赖Bean
    public AuthorizationServerConfig(AuthenticationManager authenticationManager, 
                                     UserDetailsService userDetailsService,
                                     PasswordEncoder passwordEncoder) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
    }

    // 配置令牌端点的安全规则
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许客户端通过表单提交认证,替代Basic Auth
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()") // 允许匿名访问令牌公钥接口(按需开启)
                .checkTokenAccess("isAuthenticated()"); // 校验令牌需要身份认证
    }

    // 配置客户端信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 内存存储客户端示例,生产环境建议改用数据库存储
        clients.inMemory()
                .withClient("your-client-id") // 自定义客户端ID
                .secret(passwordEncoder.encode("your-client-secret")) // 加密后的客户端密钥
                .authorizedGrantTypes("password", "refresh_token") // 开启密码模式和刷新令牌模式
                .scopes("read", "write") // 客户端权限范围
                .resourceIds("oauth2-server") // 对应你的资源服务器ID
                .accessTokenValiditySeconds(3600) // 访问令牌有效期
                .refreshTokenValiditySeconds(86400); // 刷新令牌有效期
    }

    // 配置令牌端点的其他参数
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(new InMemoryTokenStore()) // 内存存储令牌,生产环境建议用Redis或数据库
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
}

2. 调整Spring Security主配置

还要确保Web安全配置允许令牌端点的匿名访问,避免请求被拦截:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 暴露AuthenticationManager给授权服务器使用
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 配置密码编码器(生产环境必须)
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 配置用户认证逻辑
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 内存用户示例,实际项目替换为数据库查询逻辑
        auth.inMemoryAuthentication()
                .withUser("test-user")
                .password(passwordEncoder().encode("test-pass"))
                .roles("USER");
    }

    // 配置HTTP安全规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 令牌请求为POST,关闭CSRF校验
                .authorizeRequests()
                .antMatchers("/oauth/token").permitAll() // 允许匿名访问令牌端点
                .anyRequest().authenticated(); // 其他接口需身份认证
    }
}

3. Postman请求令牌示例

现在你可以在Postman里这样发送请求获取令牌:

  • 请求方法:POST
  • 请求URL:http://localhost:8080/oauth/token
  • 请求体类型:x-www-form-urlencoded
  • 表单参数:
    • grant_type: password(固定值,指定密码模式)
    • username: 你的用户名(比如上面配置的test-user)
    • password: 你的密码(比如上面配置的test-pass)
    • client_id: your-client-id(和授权服务器配置里的一致)
    • client_secret: your-client-secret(和授权服务器配置里的一致)

发送请求后,就能拿到包含access_token的响应,无需再在请求头中添加Basic Auth信息。

关键注意事项

  • 生产环境绝对禁止使用{noop}明文密码,必须用BCryptPasswordEncoder这类加密方式处理客户端密钥和用户密码。
  • 如果你的Spring Boot版本在2.7以上,官方推荐使用Spring Authorization Server替代旧的spring-security-oauth2依赖,配置逻辑类似但细节略有不同。
  • 你已有的ResourceServer配置无需改动,只要保证资源ID和授权服务器配置的resourceIds一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:53:40