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

如何在Spring Boot Security OAuth2应用中仅为指定类启用OAuth2?

解决Spring Boot 1.5.x仅对特定API启用OAuth2认证的问题

针对你的需求,我们可以通过自定义WebSecurityConfigurerAdapter和ResourceServerConfigurerAdapter来精确控制哪些路径需要OAuth2认证,哪些路径允许匿名访问。以下是具体的配置步骤:

1. 配置WebSecurity,放开非API路径的访问权限

首先创建一个Web安全配置类,继承WebSecurityConfigurerAdapter,在这里我们可以指定哪些路径不需要认证,同时确保OAuth2的认证逻辑只作用于目标API:

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 {
        // 放开所有非API路径的匿名访问,比如/login、静态资源、其他Controller的路径
        http.authorizeRequests()
                .antMatchers("/login", "/", "/home", "/public/**") // 根据你的实际路径调整
                .permitAll()
                // 目标API路径需要认证
                .antMatchers("/api/**") // 假设IShortUrlApiInterface的接口都在/api路径下,根据实际调整
                .authenticated()
                .and()
                .csrf().disable(); // 如果是REST接口,通常需要禁用CSRF
    }
}

2. 配置ResourceServer,绑定OAuth2认证到目标API

接下来创建资源服务器配置类,继承ResourceServerConfigurerAdapter,这里指定受OAuth2保护的资源路径,并配置认证规则:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 仅对目标API路径应用OAuth2认证
                .antMatchers("/api/**")
                .access("#oauth2.hasScope('read') or #oauth2.hasScope('write')") // 根据你的OAuth2 scope调整
                .and()
                .csrf().disable();
    }
}

关键注意事项

  • 路径匹配调整:请根据IShortUrlApiInterface实际的接口路径修改antMatchers里的规则,比如如果你的API路径是/shorturl/**,就把/api/**换成/shorturl/**。
  • 覆盖默认配置:Spring Boot的security.basic.enabled=false和security.ignored会被OAuth2的资源服务器配置覆盖,所以必须通过Java配置来精确控制权限。
  • 权限规则:access()里的表达式可以根据你的OAuth2需求调整,比如要求特定角色可以写成hasRole('ADMIN'),或者结合scope使用。

这样配置后,除了目标API路径之外的所有路径(比如/login)都可以匿名访问,只有IShortUrlApiInterface对应的接口会要求OAuth2认证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:37:26