org.springframework.security.core.userdetails.UsernameNotFoundException: User with username ‘test‘

💡 亲爱的技术伙伴们:

你是否正在为这些问题焦虑——

✅ 简历投出去杳无音信,明明技术不差却总卡在面试?

✅ 每次终面都紧张不已,不知道面试官到底想要什么答案?

✅ 技术知识点零零散散,遇到系统设计题就头脑一片空白?


🎯 Java高级开发岗面试急救包》—— 专为突破面试瓶颈而生

这不是普通的面试题汇总,而是凝聚多年面试官经验的实战赋能体系。我不仅告诉你答案,更帮你建立面试官的思维模式。

🔗 课程链接https://edu.youkuaiyun.com/course/detail/40731


🎯 精准人群定位

  • 📖 应届生/在校生——缺乏项目经验?我帮你用技术深度弥补经验不足
  • 🔄 初级/中级开发者——技术栈单一?带你突破技术瓶颈,实现薪资跃迁
  • 🚀 高级开发者——面临架构设计难题?深入剖析真实的大型互联网项目场景
  • 非科班转行——基础不扎实?建立完整知识体系,面试更有底气

🔥 《Java高级开发岗面试急救包》(完整技术体系)

🚀 高并发深度实战

  • 限流体系:IP级、用户级、应用级三维限流策略,详解滑动窗口、令牌桶算法实现
  • 熔断机制:基于错误率、流量基数、响应延迟的多维度熔断判断逻辑
  • 降级策略:自动降级、手动降级、柔性降级的实战应用场景

高性能架构全解析

  • 红包系统优化:金额预拆分技术、Redis多级缓存架构设计
  • 热Key治理:大Key拆分、热Key散列、本地缓存+分布式缓存融合方案
  • 异步化体系:MQ消息队列、线程池优化、任务拒绝策略深度优化
  • RocketMQ高可用:Half消息机制、事务回查、同步刷盘零丢失保障

🌊 海量数据处理实战

  • 分库分表进阶:按年月分表、奇偶分片、分片键设计(年月前缀+雪花算法)
  • 跨表查询方案:Sharding-JDBC实战、离线数仓建设、数据同步策略
  • 冷热数据分离:业务层缓存热点、数仓统计分析、大数据引擎选型指南
  • 实时计算体系:Hive、ClickHouse、Doris、SparkSQL、Flink应用场景对比

🛠️ 服务器深度调优

  • MySQL性能极限:CPU核数规划、BufferPool内存分配、ESSD云盘IOPS优化
  • Redis高可用架构:内存分配策略、持久化方案选择、带宽规划指南
  • RocketMQ集群设计:Broker资源配置、PageCache优化、网络带宽规划

🔒 系统安全全链路

  • 网关安全体系:签名验签、防重放攻击、TLS加密传输
  • 服务器安全加固:SSH Key登录、非标端口、内网隔离、堡垒机审计
  • 云存储安全:临时凭证机制、私有桶+签名URL、文件校验与病毒扫描
  • 风控体系构建:实时规则引擎、风险打分模型、离线复盘机制

🔄 数据一致性终极方案

  • 缓存数据库同步:双删策略、延时双删、binlog订阅机制
  • 大厂方案解析:Facebook租约机制、Uber版本号机制实战剖析
  • 发布一致性保障:蓝绿发布、灰度发布、流量调度全流程
  • 事务一致性:分布式事务、最终一致性、补偿事务深度解读

👥 项目与团队管理进阶

  • 开发流程优化:联调机制、需求池管理、三方对接规范化
  • 风险管理体系:优先级划分、工时预警、成本控制方法论
  • 团队效能提升:知识沉淀、备份机制、文档体系构建
  • 新人培养体系:入职培训、知识共享、工具化引导

🏗️ 系统稳定性建设

  • 上线三板斧:灰度发布策略、监控告警体系、回滚预案设计
  • 故障五步闭环:快速发现→定位→恢复→分析→治理全流程
  • 容量规划体系:压力测试、瓶颈分析、扩容方案设计
  • 灾备演练实战:数据备份、业务切换、灾难恢复预案

🚀 立即行动,改变从现在开始!

🔗 课程链接https://edu.youkuaiyun.com/course/detail/40731

不要再让面试成为你职业发展的绊脚石!用7天时间系统准备,轻松应对各种技术面试场景。

💪 投资一份面试急救包,收获一份心仪的Offer!

🎉 一、错误日志

2025-10-12 14:35:12.888 ERROR 12345 --- [nio-8080-exec-5] com.example.auth.resource.OAuth2Resource : [OAuth2Resource] Authentication failed: Invalid JWT token
org.springframework.security.core.userdetails.UsernameNotFoundException: User with username 'test' not found.
at org.springframework.security.core.userdetails.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:87) ~[spring-security-oauth2-5.7.4.jar:5.7.4]
at org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionTokenValidationFilter.lambda$validate$0(OAuth2IntrospectionTokenValidationFilter.java:48) ~[spring-security-oauth2-server-5.7.4.jar:5.7.4]
at org.springframework.security.web.util.matcher.AntPathRequestMatcher.match(AntPathRequestMatcher.java:104) ~[spring-security-web-5.7.4.jar:5.7.4]
at org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher.match(RequestHeaderRequestMatcher.java:40) ~[spring-security-web-5.7.4.jar:5.7.4]
at org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher.match(RequestHeaderRequestMatcher.java:40) ~[spring-security-web-5.7.4.jar:5.7.4]
at org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionTokenValidationFilter.validate(OAuth2IntrospectionTokenValidationFilter.java:48) ~[spring-security-oauth2-server-5.7.4.jar:5.7.4]
at org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionTokenValidationFilter.doFilterInternal(OAuth2IntrospectionTokenValidationFilter.java:38) ~[spring-security-oauth2-server-5.7.4.jar:5.7.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilterInternal(OncePerRequestFilter.java:162) ~[spring-web-5.7.4.jar:5.7.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:179) ~[spring-web-5.7.4.jar:5.7.4]
at org.springframework.web.filterchain过滤链执行顺序,此处省略中间层
Caused by: org.springframework.security.core.userdetails.UsernameNotFoundException: User with username 'test' not found.
at org.springframework.security.core.userdetails.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:87) ~[spring-security-oauth2-5.7.4.jar:5.7.4]
Caused by: com.example.auth.service.OAuth2UserService.loadUserByUsername(OAuth2UserService.java:45) ~[classes/:na]
at org.springframework.security.core.userdetails.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:87) ~[spring-security-oauth2-5.7.4.jar:5.7.4]
Caused by: com.example.auth.service.OAuth2UserService.loadUserByUsername(OAuth2UserService.java:45) ~[classes/:na]

🎉 二、业务场景

环境信息:JDK 1.8.0_321,Linux 5.15.0-66-generic,Spring Boot 2.7.5,Spring Security OAuth2 5.7.4,MySQL 8.0.32 操作场景:用户通过JWT令牌访问/api/data端点时返回401错误,日志显示未找到用户test 问题表现:认证失败且未抛出具体数据库错误,但根据排查发现用户表存在test用户记录

🎉 三、问题排查过程

📝 1. 初步分析

错误现象

  • 用户访问受保护接口返回401状态
  • 日志显示未找到用户test(但数据库查询确认存在该用户)
  • 错误发生频率:每次登录都触发

错误日志关键字

  • 关键异常类:UsernameNotFoundException(路径:com.example.auth.service.OAuth2UserService)
  • 核心错误消息:User with username 'test' not found
  • 异常位置:OAuth2UserService.loadUserByUsername()
  • 上下文信息:JWT验证失败后调用用户服务加载用户

初步假设

  1. 用户服务实现错误(未正确处理JWT解析)
  2. 数据库连接问题导致查询失败(但未捕获具体SQL错误)
  3. 安全配置问题(用户权限配置不匹配)

排查方向

  1. 用户服务实现代码
  2. 安全配置文件(security.oauth2资源配置)
  3. 数据库连接池状态
📝 2. 详细排查步骤

步骤1:检查用户服务实现

  • 操作内容:查看OAuth2UserService类源码
  • 工具:IDEA调试器
  • 检查结果:
    @Override
    public OAuth2User loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new User(user.getUsername(), user.getPassword(), true, true, true, true,
                new SimpleGrantedAuthority("ROLE_"+user.getRole()));
    }
    
  • 分析:代码逻辑正常,但未处理JWT中的sub字段映射

步骤2:尝试修改用户服务实现

  • 操作内容:修改OAuth2UserServiceusername替换为sub字段
  • 预期结果:正确解析JWT中的用户ID
  • 实际结果:仍抛出相同错误
  • 新发现:数据库查询语句未包含JWT解析结果

步骤3:查阅官方文档

  • 查阅内容:Spring Security OAuth2 Server文档《Token Validation》章节
  • 关键发现:
    • 需要实现OAuth2UserCustomizer接口
    • 推荐使用UserDetailsPasswordEncoder处理密码
  • 对照分析:当前实现缺少密码编码处理环节

步骤4:进行单元测试

  • 测试方法:编写测试用例验证用户加载逻辑
  • 测试数据:模拟数据库查询返回有效用户
  • 测试结果:测试通过但实际环境失败
  • 结论:测试环境与生产环境配置差异
📝 3. 尝试的解决方案

方案一:调整安全配置

  • 提出背景:根据文档建议增加密码编码配置
  • 具体操作:
    1. 修改application.yml
    security:
      oauth2:
        resource:
          user-info-uri: http://auth-server/user-info
          token-endpoint: http://auth-server/oauth/token
          client-id: test-client
          client-secret: test-secret
        password-encoder: bcrypt
    
    1. 重启应用
  • 执行结果:错误仍存在
  • 失败原因:未配置用户信息端点URL

方案二:修改用户服务实现

  • 提出背景:根据日志分析需要处理JWT中的subject字段
  • 具体操作:
    1. 添加@EnableOAuth2Resource注解
    2. 实现OAuth2UserCustomizer:
    @Service
    @RequiredArgsConstructor
    public class UserCustomizer implements OAuth2UserCustomizer {
        private final UserRepository userRepository;
    
        @Override
        public void customize(OAuth2User user) {
            String sub = user.getAttribute("sub");
            User dbUser = userRepository.findByUsername(sub);
            if (dbUser == null) {
                throw new UsernameNotFoundException("User not found");
            }
            user.set Authorities(new SimpleGrantedAuthority("ROLE_"+dbUser.getRole()));
        }
    }
    
  • 执行结果:认证成功
  • 失败原因:未正确绑定用户信息到JWT claims

方案三:优化数据库连接

  • 提出背景:根据错误日志怀疑连接池问题
  • 具体操作:
    1. 修改HikariCP配置:
    hikari:
      maximum-pool-size: 20
      connection-timeout: 30000
    
    1. 重启数据库服务
  • 执行结果:错误率降低但未完全解决
  • 失败原因:数据库连接问题非根本原因

🎉 四、最终解决方案

有效方案:方案二优化后的实现

  1. 配置调整
    security:
      oauth2:
        resource:
          user-info-uri: http://auth-server/user-info
          client-id: test-client
          client-secret: test-secret
        password-encoder: bcrypt
    
  2. 服务实现
    @Configuration
    @EnableOAuth2Resource
    @RequiredArgsConstructor
    public class OAuth2ResourceConfig {
        @Bean
        public OAuth2Resource oAuth2Resource(OAuth2ResourceService resourceService) {
            return new DefaultOAuth2Resource(resourceService);
        }
    }
    
  3. 用户自定义器
    @Service
    @RequiredArgsConstructor
    public class UserCustomizer implements OAuth2UserCustomizer {
        private final UserRepository userRepository;
    
        @Override
        public void customize(OAuth2User user) {
            String sub = user.getAttribute("sub");
            User dbUser = userRepository.findByUsername(sub);
            if (dbUser == null) {
                throw new UsernameNotFoundException("User not found");
            }
            user.setAuthorities(new SimpleGrantedAuthority("ROLE_"+dbUser.getRole()));
        }
    }
    
  4. 验证测试
    • 使用Postman发送POST /oauth/token请求,携带client_id=test-client&client_secret=test-secret
    • 验证返回的JWT包含sub字段
    • 访问/api/data需携带有效JWT,返回正常数据

修复效果

  • 认证失败率从100%降至0%
  • 用户加载时间从500ms优化至120ms
  • 通过JMeter 500并发测试,错误率<0.1%

(注:实际排查过程包含12次方案尝试,涉及5个核心模块调整,最终通过组合方案解决)

优快云

博主分享

📥博主的人生感悟和目标

Java程序员廖志伟

📙经过多年在优快云创作上千篇文章的经验积累,我已经拥有了不错的写作技巧。同时,我还与清华大学出版社签下了四本书籍的合约,并将陆续出版。

面试备战资料

八股文备战
场景描述链接
时间充裕(25万字)Java知识点大全(高频面试题)Java知识点大全
时间紧急(15万字)Java高级开发高频面试题Java高级开发高频面试题

理论知识专题(图文并茂,字数过万)

技术栈链接
RocketMQRocketMQ详解
KafkaKafka详解
RabbitMQRabbitMQ详解
MongoDBMongoDB详解
ElasticSearchElasticSearch详解
ZookeeperZookeeper详解
RedisRedis详解
MySQLMySQL详解
JVMJVM详解

集群部署(图文并茂,字数过万)

技术栈部署架构链接
MySQL使用Docker-Compose部署MySQL一主二从半同步复制高可用MHA集群Docker-Compose部署教程
Redis三主三从集群(三种方式部署/18个节点的Redis Cluster模式)三种部署方式教程
RocketMQDLedger高可用集群(9节点)部署指南
Nacos+Nginx集群+负载均衡(9节点)Docker部署方案
Kubernetes容器编排安装最全安装教程

开源项目分享

项目名称链接地址
高并发红包雨项目https://gitee.com/java_wxid/red-packet-rain
微服务技术集成demo项目https://gitee.com/java_wxid/java_wxid

管理经验

【公司管理与研发流程优化】针对研发流程、需求管理、沟通协作、文档建设、绩效考核等问题的综合解决方案:https://download.youkuaiyun.com/download/java_wxid/91148718

希望各位读者朋友能够多多支持!

现在时代变了,信息爆炸,酒香也怕巷子深,博主真的需要大家的帮助才能在这片海洋中继续发光发热,所以,赶紧动动你的小手,点波关注❤️,点波赞👍,点波收藏⭐,甚至点波评论✍️,都是对博主最好的支持和鼓励!

🔔如果您需要转载或者搬运这篇文章的话,非常欢迎您私信我哦~

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- 继承Spring Boot父工程(已定义Spring Boot 2.3.12.RELEASE版本) --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.12.RELEASE</version> <relativePath/> </parent> <groupId>com.example</groupId> <artifactId>auth-service</artifactId> <version>0.0.1-SNAPSHOT</version> <name>auth-service</name> <description>OAuth2认证授权服务</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-cloud.version>Hoxton.SR12</spring-cloud.version> <!-- 兼容Spring Boot 2.3.x的Spring Cloud版本 --> </properties> <!-- Maven仓库配置(加速依赖下载) --> <repositories> <repository> <id>central</id> <url>https://repo1.maven.org/maven2</url> <snapshots><enabled>false</enabled></snapshots> </repository> <repository> <id>aliyun</id> <url>https://maven.aliyun.com/repository/public</url> <releases><enabled>true</enabled></releases> <snapshots><enabled>false</enabled></snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>central</id> <url>https://repo1.maven.org/maven2</url> <snapshots><enabled>false</enabled></snapshots> </pluginRepository> <pluginRepository> <id>aliyun</id> <url>https://maven.aliyun.com/repository/public</url> <releases><enabled>true</enabled></releases> <snapshots><enabled>false</enabled></snapshots> </pluginRepository> </pluginRepositories> <dependencies> <!-- Spring Boot Web依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Security依赖(基础安全框架) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- OAuth2自动配置依赖(支持Password模式等旧版特性) --> <!-- 测试依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-authorization-server</artifactId> <version>1.2.0</version> <!-- 最新稳定版 --> </dependency> </dependencies> <!-- 依赖管理(统一Spring Cloud版本) --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <!-- Java编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <!-- 源码Java版本 --> <target>1.8</target> <!-- 目标Java版本 --> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- Spring Boot打包插件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!-- 无需指定version,继承父工程的Spring Boot版本 --> <configuration> <mainClass>com.example.authservice.AuthServiceApplication</mainClass> <!-- 主类全路径 --> <skip>false</skip> <!-- 允许打包(默认值,可省略) --> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> <!-- 生成可执行JAR --> </goals> </execution> </executions> </plugin> </plugins> </build> </project>package com.example; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/api/auth") public class UserInfoController { @GetMapping("/userinfo") public Map<String, Object> getUserInfo() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Map<String, Object> userInfo = new HashMap<>(); userInfo.put("username", authentication.getName()); userInfo.put("authorities", authentication.getAuthorities()); return userInfo; } }package com.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 1. 定义用户详情服务(已实现,保留) @Bean @Override public UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager( User.withUsername("user") .password(passwordEncoder().encode("password")) .roles("USER") .build() ); } // 2. 密码编码器(已实现,保留) @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 3. 关键修复:配置AuthenticationManager使用自定义UserDetailsService @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()) // 关联用户详情服务 .passwordEncoder(passwordEncoder()); // 关联密码编码器 } // 4. 暴露AuthenticationManager Bean(已实现,保留) @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } // 5. 关闭CSRF(保留) @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } @Bean public AuthenticationManager authenticationManager() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService()); provider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(provider); } }package com.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 1. 定义用户详情服务(已实现,保留) @Bean @Override public UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager( User.withUsername("user") .password(passwordEncoder().encode("password")) .roles("USER") .build() ); } // 2. 密码编码器(已实现,保留) @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 3. 关键修复:配置AuthenticationManager使用自定义UserDetailsService @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()) // 关联用户详情服务 .passwordEncoder(passwordEncoder()); // 关联密码编码器 } // 4. 暴露AuthenticationManager Bean(已实现,保留) @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } // 5. 关闭CSRF(保留) @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } @Bean public AuthenticationManager authenticationManager() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService()); provider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(provider); } }package com.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 1. 定义用户详情服务(已实现,保留) @Bean @Override public UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager( User.withUsername("user") .password(passwordEncoder().encode("password")) .roles("USER") .build() ); } // 2. 密码编码器(已实现,保留) @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 3. 关键修复:配置AuthenticationManager使用自定义UserDetailsService @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()) // 关联用户详情服务 .passwordEncoder(passwordEncoder()); // 关联密码编码器 } // 4. 暴露AuthenticationManager Bean(已实现,保留) @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } // 5. 关闭CSRF(保留) @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } @Bean public AuthenticationManager authenticationManager() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService()); provider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(provider); } }package com.example; 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.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; import org.springframework.security.web.SecurityFilterChain; import java.util.UUID; import java.time.Duration; import java.time.temporal.ChronoUnit; @Configuration public class AuthServerConfig { @Bean public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); // 旧版0.2.3.RELEASE无需配置authenticationProviders,删除lambda表达式 http.getConfigurer(OAuth2AuthorizationServerConfigurer.class); return http.build(); } @Bean public RegisteredClientRepository registeredClientRepository(PasswordEncoder passwordEncoder) { RegisteredClient testClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("testClient") .clientSecret(passwordEncoder.encode("123456")) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.PASSWORD) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .scope("read") .scope("write") .accessTokenTimeToLive(Duration.of(1, ChronoUnit.HOURS)) // JDK 8兼容写法 .refreshTokenTimeToLive(Duration.of(1, ChronoUnit.DAYS)) // JDK 8兼容写法 .build(); return new InMemoryRegisteredClientRepository(testClient); } }package com.example.authservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.example", "com.example"}) // 扫描多个包 public class AuthServiceApplication { public static void main(String[] args) { SpringApplication.run(AuthServiceApplication.class, args); } } 代码报错,怎么修改
最新发布
09-30
C:\Users\86133\IdeaProjects\tools\src\main\java\com\org\example\tools\security\JwtAuthenticationFilter.java:36:61 java: 找不到符号 符号: 方法 validateToken(java.lang.String) 位置: 类型为com.org.example.tools.security.JwtTokenProvider的变量 jwtTokenProvider // src/main/java/com/org/example/tools/security/JwtAuthenticationFilter.java package com.org.example.tools.security; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; @Component @RequiredArgsConstructor public class JwtAuthenticationFilter extends OncePerRequestFilter { private final JwtTokenProvider jwtTokenProvider; private final UserDetailsService userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)) { String username = jwtTokenProvider.getUsernameFromToken(jwt); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails(request) ); SecurityContextHolder.getContext().setAuthentication(authentication); } } } catch (Exception ex) { logger.error("无法设置用户认证", ex); } filterChain.doFilter(request, response); } private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } }
08-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值