0

0

Spring Boot 中同时使用 OAuth2 和 Basic 认证

碧海醫心

碧海醫心

发布时间:2025-10-28 14:11:17

|

946人浏览过

|

来源于php中文网

原创

spring boot 中同时使用 oauth2 和 basic 认证

本文旨在解决 Spring Boot Web 应用中同时集成 OAuth2 资源服务器和 Basic 认证的问题。通过配置多个 `WebSecurityConfigurerAdapter` 实例,并自定义 `UserDetailsService`,可以实现对不同端点采用不同的认证方式,确保 `/resource` 端点受 OAuth2 保护,而 `/helloworld` 端点受 Basic 认证保护。本文将提供详细的配置示例和注意事项,帮助开发者顺利实现混合认证方案。

在 Spring Boot 应用中,同时使用 OAuth2 和 Basic 认证可能会遇到一些配置问题。默认情况下,Spring Boot 会自动配置 UserDetailsService,但当存在 OAuth2 相关配置时,自动配置可能会失效,导致 Basic 认证无法正常工作。本教程将详细介绍如何在 Spring Boot 应用中配置多个 WebSecurityConfigurerAdapter 实例,并自定义 UserDetailsService,以实现对不同端点采用不同的认证方式。

配置多个 WebSecurityConfigurerAdapter

为了实现不同端点使用不同的认证方式,我们需要创建多个 WebSecurityConfigurerAdapter 实例,并使用 @Order 注解指定它们的优先级。优先级高的配置会先执行。

@Configuration
@Order(10)
@EnableWebSecurity
public static class HelloWorldBasicSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.antMatcher("/helloworld")
            .httpBasic()
            .and()
            .authorizeRequests().antMatchers("/helloworld").authenticated();
    }
}

@Configuration
@Order(0)
@EnableWebSecurity
public static class ResourceSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Autowired
    private Environment environment;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.antMatcher("/resource")
            .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(
                opaqueToken -> opaqueToken.introspector(new DemoAuthoritiesOpaqueTokenIntrospector())))
            .authorizeRequests().antMatchers("/resource").authenticated();
    }

    private class DemoAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
        private final OpaqueTokenIntrospector delegate;

        private final String demoClientId;

        public DemoAuthoritiesOpaqueTokenIntrospector() {
            String introSpectionUri = environment
                .getProperty("spring.security.oauth2.resourceserver.opaque-token.introspection-uri");
            String clientId = environment
                .getProperty("spring.security.oauth2.resourceserver.opaque-token.client-id");
            String clientSecret = environment
                .getProperty("spring.security.oauth2.resourceserver.opaque-token.client-secret");
            demoClientId = environment.getProperty("demo.security.oauth2.credentials-grant.client-id");

            delegate = new NimbusOpaqueTokenIntrospector(introSpectionUri, clientId, clientSecret);
        }

        public OAuth2AuthenticatedPrincipal introspect(String token) {
            OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);

            return new DefaultOAuth2AuthenticatedPrincipal(principal.getName(), principal.getAttributes(),
                extractAuthorities(principal));
        }

        private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
            String userId = principal.getAttribute("client_id");

            if (demoClientId.equals(userId)) {
                return Collections.singleton(new SimpleGrantedAuthority("ROLE_oauth2"));
            }

            return Collections.emptySet();
        }
    }
}

在上面的代码中,HelloWorldBasicSecurityConfigurerAdapter 配置了 /helloworld 端点的 Basic 认证,而 ResourceSecurityConfigurerAdapter 配置了 /resource 端点的 OAuth2 资源服务器。

自定义 UserDetailsService

由于 Spring Boot 在存在 OAuth2 配置时可能会回退 UserDetailsService 的自动配置,我们需要手动定义 UserDetailsService bean。

@Bean
public UserDetailsService inMemoryUserDetailsService() {
    UserDetails demo = User.withUsername("demo").password("{noop}demo").roles("demo").build();
    return new InMemoryUserDetailsManager(demo);
}

这段代码创建了一个 InMemoryUserDetailsManager,并添加了一个用户名为 "demo",密码为 "demo",角色为 "demo" 的用户。 {noop} 前缀表示密码未加密,仅用于演示目的。在生产环境中,应该使用更安全的密码编码方式。

mallcloud商城
mallcloud商城

mallcloud商城基于SpringBoot2.x、SpringCloud和SpringCloudAlibaba并采用前后端分离vue的企业级微服务敏捷开发系统架构。并引入组件化的思想实现高内聚低耦合,项目代码简洁注释丰富上手容易,适合学习和企业中使用。真正实现了基于RBAC、jwt和oauth2的无状态统一权限认证的解决方案,面向互联网设计同时适合B端和C端用户,支持CI/CD多环境部署,并提

下载

完整配置示例

下面是完整的配置示例,包括 DemoApplication.java、DemoSecurityConfiguration.java 和 application.yaml。

DemoApplication.java

@SpringBootApplication
@RestController
public class DemoApplication {

    @PreAuthorize("hasRole('demo')")
    @GetMapping("/helloworld")
    public String hello() {
        return "Hello World!";
    }

    @PreAuthorize("hasRole('oauth2')")
    @GetMapping("/resource")
    public String resource() {
        return "Protected resource";
    }

    public static void main(String... args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

DemoSecurityConfiguration.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;


import java.util.Collection;
import java.util.Collections;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DemoSecurityConfiguration {

    @Bean
    public UserDetailsService inMemoryUserDetailsService() {
        UserDetails demo = User.withUsername("demo").password("{noop}demo").roles("demo").build();
        return new InMemoryUserDetailsManager(demo);
    }

    @Configuration
    @Order(10)
    public static class HelloWorldBasicSecurityConfigurerAdapter {

        @Bean
        public SecurityFilterChain filterChainHelloWorld(HttpSecurity http) throws Exception {
            http
                .securityMatcher("/helloworld")
                .authorizeHttpRequests(authz -> authz
                    .anyRequest().authenticated()
                )
                .httpBasic();
            return http.build();
        }
    }

    @Configuration
    @Order(0)
    public static class ResourceSecurityConfigurerAdapter {
        @Autowired
        private Environment environment;

        @Bean
        public SecurityFilterChain filterChainResource(HttpSecurity http) throws Exception {
            http
                .securityMatcher("/resource")
                .authorizeHttpRequests(authz -> authz
                    .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
            return http.build();
        }

        @Bean
        public OpaqueTokenIntrospector introspector() {
            return new DemoAuthoritiesOpaqueTokenIntrospector(environment);
        }

        private static class DemoAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
            private final OpaqueTokenIntrospector delegate;

            private final String demoClientId;

            public DemoAuthoritiesOpaqueTokenIntrospector(Environment environment) {
                String introSpectionUri = environment
                    .getProperty("spring.security.oauth2.resourceserver.opaque-token.introspection-uri");
                String clientId = environment
                    .getProperty("spring.security.oauth2.resourceserver.opaque-token.client-id");
                String clientSecret = environment
                    .getProperty("spring.security.oauth2.resourceserver.opaque-token.client-secret");
                demoClientId = environment.getProperty("demo.security.oauth2.credentials-grant.client-id");

                delegate = new NimbusOpaqueTokenIntrospector(introSpectionUri, clientId, clientSecret);
            }

            public OAuth2AuthenticatedPrincipal introspect(String token) {
                OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);

                return new DefaultOAuth2AuthenticatedPrincipal(principal.getName(), principal.getAttributes(),
                    extractAuthorities(principal));
            }

            private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
                String userId = principal.getAttribute("client_id");

                if (demoClientId.equals(userId)) {
                    return Collections.singleton(new SimpleGrantedAuthority("ROLE_oauth2"));
                }

                return Collections.emptySet();
            }
        }
    }

}

application.yaml

spring:
  security:
    basic:
      enabled: true
    user:
      name: demo
      password: demo
      roles: demo
    oauth2:
      resourceserver:
        opaque-token:
          introspection-uri: "https://...oauth2"
          client-id: "abba"
          client-secret: "secret"

demo:
  security:
    oauth2:
      credentials-grant:
        client-id: "rundmc"

注意事项

  • 密码编码: 在生产环境中,不要使用 {noop} 编码方式。应该使用更安全的密码编码方式,如 BCryptPasswordEncoder。
  • 角色权限: 确保用户具有访问相应端点所需的角色权限。
  • 配置优先级: @Order 注解的优先级顺序很重要,需要根据实际需求进行调整。
  • Spring Boot 版本: 不同版本的 Spring Boot 在配置方式上可能存在差异,请参考官方文档。
  • SecurityFilterChain: 使用 Spring Security 5.7+ 版本时,推荐使用 SecurityFilterChain bean 的方式配置HttpSecurity。

总结

通过配置多个 WebSecurityConfigurerAdapter 实例,并自定义 UserDetailsService,可以在 Spring Boot 应用中同时使用 OAuth2 和 Basic 认证,实现对不同端点采用不同的认证方式。 确保 /resource 端点受 OAuth2 保护,而 /helloworld 端点受 Basic 认证保护。本教程提供了一个完整的配置示例,并列出了注意事项,希望能帮助开发者顺利实现混合认证方案。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

156

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

88

2026.01.26

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

139

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

408

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

73

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

147

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

271

2025.12.24

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

32

2026.02.11

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

3

2026.03.11

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.3万人学习

C# 教程
C# 教程

共94课时 | 11.1万人学习

Java 教程
Java 教程

共578课时 | 80.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号