OAuth2.0实战案例

简介: 本项目基于Spring Boot与Spring Cloud构建,实现OAuth2四种授权模式。通过父工程统一版本管理,分别搭建资源服务与授权服务模块,集成MyBatis与MySQL实现用户及客户端信息持久化,完成认证授权全流程。

1.创建父工程

com.itheima

springboot_security_oauth
1.0-SNAPSHOT


org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE




Greenwich.RELEASE




org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import






spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot

true



spring-milestones
Spring Milestones
https://repo.spring.io/milestone

false



2.创建资源模块
2.1 创建工程并导入依赖

springboot_security_oauth
com.itheima
1.0-SNAPSHOT

4.0.0
oauth_source



org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-security


org.springframework.cloud
spring-cloud-starter-oauth2


mysql
mysql-connector-java
5.1.47


org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.0


2.2 创建配置文件
server:
port: 9002
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: root
main:
allow-bean-definition-overriding: true
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
2.3 创建启动类
@SpringBootApplication
@MapperScan("com.itheima.mapper")
public class OAuthSourceApplication {
public static void main(String[] args) {
SpringApplication.run(OAuthSourceApplication.class, args);
}
}
2.4 创建处理器
@RestController
@RequestMapping("/product")
public class ProductController {
@GetMapping
public String findAll(){
return "查询产品列表成功!";
}
}
3.创建授权模块
3.1 创建工程并导入依赖


springboot_security_oauth
com.itheima
1.0-SNAPSHOT

4.0.0

oauth_server



org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-security


org.springframework.cloud
spring-cloud-starter-oauth2


mysql
mysql-connector-java
5.1.47


org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.0


3.2 创建配置文件
server:
port: 9001
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: root
main:
allow-bean-definition-overriding: true # 这个表示允许我们覆盖OAuth2放在容器中的bean对象,一定要配置
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
3.3 创建启动类
@SpringBootApplication
@MapperScan("com.itheima.mapper")
public class OauthServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthServerApplication.class, args);
}
}
3.4 创建配置类
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService myCustomUserService;
@Bean
public BCryptPasswordEncoder myPasswordEncoder(){
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    //所有资源必须授权后访问
    .anyRequest().authenticated()
    .and()
    .formLogin()
    .loginProcessingUrl("/login")
    .permitAll()//指定认证页面可以匿名访问
    //关闭跨站请求防护
    .and().csrf().disable();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    //UserDetailsService类
    auth.userDetailsService(myCustomUserService)
    //加密策略
    .passwordEncoder(myPasswordEncoder());
}

//AuthenticationManager对象在OAuth2认证服务中要使用,提取放入IOC容器中
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

}
3.5 创建OAuth2授权配置类
@Configuration
@EnableAuthorizationServer
public class OauthServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private DataSource dataSource;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;

//从数据库中查询出客户端信息
@Bean
public JdbcClientDetailsService clientDetailsService() {
    return new JdbcClientDetailsService(dataSource);
}

//token保存策略
@Bean
public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource);
}

//授权信息保存策略
@Bean
public ApprovalStore approvalStore() {
    return new JdbcApprovalStore(dataSource);
}

//授权码模式专用对象
@Bean
public AuthorizationCodeServices authorizationCodeServices() {
    return new JdbcAuthorizationCodeServices(dataSource);
}

//指定客户端登录信息来源
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(clientDetailsService());
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.allowFormAuthenticationForClients();
    oauthServer.checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
    .approvalStore(approvalStore())
    .authenticationManager(authenticationManager)
    .authorizationCodeServices(authorizationCodeServices())
    .tokenStore(tokenStore());
}

}
4.测试
4.1 授权码模式测试
在地址栏访问地址
http://localhost:9001/oauth/authorize?response_type=code&client_id=heima_one
跳转到SpringSecurity默认认证页面,提示用户登录个人账户【这里是sys_user表中的数据】

登录成功后询问用户是否给予操作资源的权限,具体给什么权限。Approve是授权,Deny是拒绝。
这里我们选择read和write都给予Approve。

点击Authorize后跳转到回调地址并获取授权码

使用授权码到服务器申请通行令牌token

重启资源服务器,然后携带通行令牌再次去访问资源服务器,大功告成!

4.2 简化模式测试
在地址栏访问地址
http://localhost:9001/oauth/authorize?response_type=token&client_id=heima_one
由于上面用户已经登录过了,所以无需再次登录,其实和上面是有登录步骤的,这时,浏览器直接返回了token

直接访问资源服务器

4.3 密码模式测试
申请token

访问资源服务器

4.4 客户端模式测试
申请token

访问资源服务

相关文章
|
5月前
|
人工智能 自然语言处理 数据可视化
企业如何把AI智能客服系统用好(2026年2月最新)
2026年,智能客服已成企业服务升级必选项。它不再仅答预设问题,更能理解上下文、识别情绪、预测需求。瓴羊Quick Service依托通义千问大模型,融合规则引擎与业务系统,支持“人机协同、场景先行、知识进化、数据驱动”,助力企业降本增效、提升体验。(239字)
|
22天前
|
人工智能 自然语言处理 安全
Claude Code 全攻略:命令大全+三种模式+记忆体系+实战工作流完整手册
Claude Code 是当前最流行的终端级 AI 编程助手,能够直接在命令行中完成代码生成、项目理解、文件修改、命令执行、错误修复等全流程开发工作。它不依赖图形界面、不占用额外资源,却能深度理解项目结构,自动生成规范代码,大幅提升研发效率。
2718 3
|
7月前
|
存储 弹性计算 缓存
企业用户怎么选择云服务器?不同体量企业的阿里云产品选配指南教程
在企业上云过程中,云服务器的选型直接影响业务稳定性、运维效率与成本控制。阿里云针对不同体量企业的业务需求、预算规模及技术能力,提供了差异化的实例规格、付费模式与配置方案。本教程结合今年阿里云最新实例迭代、地域资源分布及付费政策,从 “小型企业 - 中型企业 - 大型企业” 三个维度,提供适配的选型逻辑与实操建议,帮助企业以最优成本获取匹配资源。
|
3月前
|
存储 人工智能 自然语言处理
让你的 Claude Code 拥有长久记忆能力
Claude-Mem 是专为 Claude Code 设计的开源持久记忆插件:自动捕获工具操作、生成语义摘要、跨会话智能注入上下文;支持自然语言搜索、可视化界面、隐私控制与全文检索,让 AI 真正“记住项目、越用越懂你”。(239字)
1941 1
|
3月前
|
中间件 测试技术 API
值得收藏,一些好用的Claude Code提示词!
值得收藏,一些好用的Claude Code提示词!
|
8月前
|
弹性计算 Cloud Native C++
云原生时代,如何用一行命令将开发环境部署到云端?
你是否也曾苦恼于本地开发环境的种种困境?配置复杂、性能瓶颈、团队协作环境不统一……本文将介绍一种革命性的解决方案:Dev Containers,并手把手教你如何借助容器技术,实现开发环境的秒级搭建与云端部署,真正做到“一次配置,处处运行”。
|
7月前
|
缓存 Dubbo Java
什么是API网关
API网关是一种架构思想,用于统一接收外部请求并转发至后端服务,实现协议转换、路由、鉴权、限流、熔断降级等功能。通过网关,可简化客户端调用,提升系统安全性与可维护性。常见实现如Kong、Zuul、Spring Cloud Gateway等,广泛应用于微服务架构中,支持异步处理、全链路监控与多维度流量控制。
|
8月前
|
弹性计算 安全
阿里云无影云电脑官网链接整理,个人版、企业版和商业版产品入口整理
阿里云无影官网提供无影云电脑企业版、个人版、商业版入口,涵盖产品介绍、官方下载及管理登录页面。用户可通过wuying.com或阿里云官网访问,实现高效安全的云端办公。
|
存储 人工智能 搜索推荐
炸裂!!!Deepseek接入个人知识库,回答速度飞起来,确实可以封神了
高效管理知识、快速获取信息成为提升工作效率的关键。无论是做技术的同学还是普通的上班族,在日常积累了大量的知识数据和内容。项目文档、会议记录到技术手册、业务流程,这些信息如同宝藏一般,等待着被高效利用。然而,面对海量的数据,如何快速准确地获取到自己想要的内容,成为了提升工作效率的关键挑战。这时,一个高效的知识库就显得尤为重要。今天,就给大家详细介绍如何利用DeepSeek和Cherry-Studio,搭建属于自己的高效专属知识库,让你在信息的海洋中如鱼得水。
1456 1

热门文章

最新文章