当前位置: 首页 > news >正文

Spring Cloud Security:Oauth2使用入门

Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2可以实现单点登录、令牌中继、令牌交换等功能,本文将对其结合Oauth2入门使用进行详细介绍。

1. OAuth2 简介

OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。

1.1. 相关名词

  • Resource owner(资源拥有者):拥有该资源的最终用户,他有访问资源的账号密码;
  • Resource server(资源服务器):拥有受保护资源的服务器,如果请求包含正确的访问令牌,可以访问资源;
  • Client(客户端):访问资源的客户端,会使用访问令牌去获取资源服务器的资源,可以是浏览器、移动设备或者服务器;
  • Authorization server(认证服务器):用于认证用户的服务器,如果客户端认证通过,发放访问资源服务器的令牌。

1.2. 四种授权模式

  • Authorization Code(授权码模式):正宗的OAuth2的授权模式,客户端先将用户导向认证服务器,登录后获取授权码,然后进行授权,最后根据授权码获取访问令牌;
  • Implicit(简化模式):和授权码模式相比,取消了获取授权码的过程,直接获取访问令牌;
  • Resource Owner Password Credentials(密码模式):客户端直接向用户获取用户名和密码,之后向认证服务器获取访问令牌;
  • Client Credentials(客户端模式):客户端直接通过客户端认证(比如client_id和client_secret)从认证服务器获取访问令牌。

其中常见的是授权码模式、密码模式;

  • 授权码模式:
    1. 客户端将用户导向认证服务器;
    2. 用户在认证服务器进行登录并授权;
    3. 认证服务器返回授权码给客户端;
    4. 客户端通过授权码和跳转地址向认证服务器获取访问令牌;
    5. 认证服务器发放访问令牌(有需要带上刷新令牌)。
  • 密码模式:
    1. 客户端从用户获取用户名和密码;
    2. 客户端通过用户的用户名和密码访问认证服务器;
    3. 认证服务器返回访问令牌(有需要带上刷新令牌)。

2. Oauth2的使用

2.1. 构建项目并添加pom文件

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId><version>2.2.0.RELEASE</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId><version>2.2.0.RELEASE</version></dependency>

2.2. 配置文件

server:port:9401spring:application:name:oauth2-service

2.3. 添加UserService

  • 实现UserDetailsService接口,用于加载用户信息
@ServicepublicclassUserServiceimplementsUserDetailsService{privateList<User>userList;@AutowiredprivatePasswordEncoderpasswordEncoder;@PostConstructpublicvoidinitData(){Stringpassword=passwordEncoder.encode("123456");userList=newArrayList<>();userList.add(newUser("zhangSan",password,AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));userList.add(newUser("liSi",password,AuthorityUtils.commaSeparatedStringToAuthorityList("client")));userList.add(newUser("pengyuyan",password,AuthorityUtils.commaSeparatedStringToAuthorityList("client")));}@OverridepublicUserDetailsloadUserByUsername(Stringusername)throwsUsernameNotFoundException{List<User>findUserList=userList.stream().filter(user->user.getUsername().equals(username)).collect(Collectors.toList());if(!CollectionUtils.isEmpty(findUserList)){returnfindUserList.get(0);}else{thrownewUsernameNotFoundException("用户名或密码错误");}}}

2.4. 认证服务器配置类

  • 使用@EnableAuthorizationServer注解开启
@Configuration@EnableAuthorizationServerpublicclassAuthorizationServerConfigextendsAuthorizationServerConfigurerAdapter{@AutowiredprivatePasswordEncoderpasswordEncoder;@AutowiredprivateAuthenticationManagerauthenticationManager;@AutowiredprivateUserServiceuserService;/** * 使用密码模式需要配置 */@Overridepublicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints){endpoints.authenticationManager(authenticationManager).userDetailsService(userService);}@Overridepublicvoidconfigure(ClientDetailsServiceConfigurerclients)throwsException{clients.inMemory().withClient("admin")//配置client_id.secret(passwordEncoder.encode("admin123456"))//配置client_secret.accessTokenValiditySeconds(3600)//配置访问token的有效期.refreshTokenValiditySeconds(864000)//配置刷新token的有效期.redirectUris("http://www.baidu.com")//配置redirect_uri,用于授权成功后跳转.scopes("all")//配置申请的权限范围.authorizedGrantTypes("authorization_code","password");//配置grant_type,表示授权类型}}

2.5. 资源服务器配置类

  • 使用@EnableResourceServer注解开启
@Configuration@EnableResourceServerpublicclassResourceServerConfigextendsResourceServerConfigurerAdapter{@Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests().anyRequest().authenticated().and().requestMatchers().antMatchers("/user/**");//配置需要保护的资源路径}}

2.6. SpringSecurity配置类

  • 允许认证相关路径的访问及表单登录:
@Configuration@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}@Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http.csrf().disable().authorizeRequests().antMatchers("/oauth/**","/login/**","/logout/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();}}

2.7. 创建登录接口用于测试

@RestController@RequestMapping("/user")publicclassUserController{@GetMapping("/getCurrentUser")publicObjectgetCurrentUser(Authenticationauthentication){returnauthentication.getPrincipal();}}

2.8. 登录

2.8.1. 授权码模式使用

  • 启动服务,在浏览器访问http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=normal进行登录授权

  • 输入账号密码进行登录操作:

  • 登录后进行授权操作:

  • 之后浏览器会带着授权码重定向到百度:https://www.baidu.com/?code=CKBS20&state=normal

  • 使用授权码请求http://localhost:9401/oauth/token获取访问令牌

  • 使用Basic认证通过client_idclient_secret(AuthorizationServerConfig类中做了默认配置)构造一个Authorization头信息;

  • 在body中添加以下参数信息,通过POST请求获取访问令牌;

  • 在下图接口请求头中添加访问令牌,发现已经可以成功访问。

2.8.2. 密码模式使用

  • 使用密码请求http://localhost:9401/oauth/token获取访问令牌;
  • 使用Basic认证通过client_idclient_secret构造一个Authorization头信息(略);
  • 在body中添加以下参数信息,通过POST请求获取访问令牌;
  • 再次在getCurrentUser接口请求头中添加访问令牌,发现已经可以成功访问。
http://www.cnnetsun.cn/news/1269020.html

相关文章:

  • Qwen Pixel Art保姆级教程:Gradio界面各参数含义与推荐取值范围
  • Lingbot-Depth-Pretrain-Vitl-14 实战:为C语言应用提供深度感知SDK
  • LingBot-Depth-ViT-L14开源模型实战:Python调用REST API返回base64深度图
  • 规划计时器-备份(自己看)
  • FireRed-OCR Studio惊艳效果:化学分子式+反应方程式LaTeX精准提取
  • Element UI树状下拉选择器优化技巧:解决远程搜索与本地过滤的常见问题
  • Unity UI 性能优化实战 — 不规则遮罩与引导层的高效实现
  • 为什么你的Dify搜索结果总排错?揭秘rerank_model、cross_encoder、top_k三者协同失效的致命链(附可运行配置)
  • 颠覆传统游戏体验:更好的鸣潮如何让剧情推进效率提升300%
  • 彩虹表攻击实战:从原理到破解SHA/MD5哈希的优化策略
  • Qwen-Image-Edit-2509图片编辑案例分享:看看AI如何把普通照片变成专业级作品
  • 2026年选跑腿系统,千万别信“啥都能做”,要信“啥都稳定”
  • 06-面向对象高级01
  • 实战演练:用BurpSuite绕过upload-labs前10关的5种奇葩姿势(附避坑指南)
  • SenseVoice语音识别零基础教程:从安装到API调用的完整流程
  • 智能客服Agent需求文档(PRD)实战指南:从设计到落地的关键考量
  • STC8H8K64U最小系统开发板设计与OLED驱动实践
  • 解决Overleaf两大痛点:ACM模板引用乱序+代码高亮失效的终极方案
  • TFBS4711红外模块数据收发全解析:从波形分析到代码实现
  • 信创云桌面私有化部署,如何真正实现企业核心数据不落地、防泄露?
  • 小白也能懂的Qwen3-Embedding-0.6B教程:快速搭建语义搜索服务
  • 【Android 12 AOSP实战】从零构建系统镜像:第三方APK预装与system.img定制指南
  • Windows与Linux文件互传终极指南:SSH+SCP命令详解(附常见问题排查)
  • 避坑指南:slam_karto跑通Freiburg激光数据集的全流程记录
  • 【AI】TensorFlow 框架
  • USB电压电流表嵌入式设计:双路采样与CAN/UART双总线实现
  • Jackson全局配置指南:一劳永逸解决前端Long精度问题(SpringBoot2.7+)
  • 2026年国内低泡切削油品牌TOP5盘点,谁将引领行业新标准
  • 为什么企业级智能问数离不开语义层?一文讲透准确率与泛化率
  • RPC超时原因