OAuth2.0实战案例

简介: 本项目基于Spring Boot与Spring Cloud OAuth2实现分布式安全认证,包含授权服务器与资源服务器模块。通过配置JDBC存储客户端信息、令牌及授权码,支持授权码、简化、密码及客户端四种模式认证。集成MyBatis操作MySQL数据库,结合Spring Security完成用户身份验证与权限控制,实现安全可靠的OAuth2单点登录与资源访问。

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

访问资源服务

相关文章
|
2月前
|
运维 Linux 网络安全
Xshell-7.0.0111p安装步骤详解(附SSH连接与远程命令教程)
Xshell 7.0.0111p 是专业SSH远程终端工具,支持Linux/VPS/云服务器连接、命令执行与文件传输,适用于运维、开发及学习。安装简单,含中文向导,推荐以管理员身份运行,支持自定义安装路径与桌面快捷方式。(239字)
|
2月前
|
人工智能 自然语言处理 数据可视化
2026年新手一键部署OpenClaw(原Clawdbot)详细步骤流程
OpenClaw(前身为Clawdbot、Moltbot)是一款主流开源AI代理工具,核心优势在于能通过自然语言指令完成自动化任务,可深度适配办公、开发、团队协作等多场景,实现文件处理、日程管理、信息提取等实操功能,依托阿里云服务器部署还能实现7×24小时不间断运行。2026年,阿里云针对OpenClaw推出专属一键部署方案,通过预置专属镜像规避复杂环境配置,彻底简化部署流程,无需手动安装Node.js、Python等依赖,无需编写任何代码,全程可视化操作+复制命令,零基础新手也能在30-40分钟内完成从服务器购买到OpenClaw正常使用的全流程,真正实现“零技术门槛落地专属AI助手”。
526 4
|
9月前
|
人工智能 监控
小众赛道新机会----反向海淘
反向海淘是指海外消费者通过跨境电商或代购平台购买中国商品并寄回本地的消费模式。因其价格低、品类多、文化情感需求及社交电商推动,日益受到海外华人、留学生及追求性价比的本土消费者青睐。主要方式包括代购平台、直邮、集运转运和社交代购,代表平台有Pandabuy、AliExpress等。盈利模式涵盖商品差价、平台佣金、物流增值、广告及数据服务等。未来趋势包括AI选品、本地仓储和社交电商崛起。
|
9月前
|
Linux iOS开发 MacOS
Krita 5.2.10 (Linux, macOS, Windows) - 开源免费绘画软件
Krita 5.2.10 (Linux, macOS, Windows) - 开源免费绘画软件
376 0
Krita 5.2.10 (Linux, macOS, Windows) - 开源免费绘画软件
|
9月前
|
存储 安全 数据安全/隐私保护
SD卡无法读取怎么办?修复方法汇总
SD卡无法读取怎么办?别急,先排查设备接口、检查卡体物理损伤,尝试恢复数据再格式化修复。教你一步步解决常见问题,保护重要文件安全!
|
监控 搜索推荐 数据挖掘
多维度组织支撑:提升CRM线索客户资源分配效率
在当今商业环境中,客户关系管理(CRM)系统是企业提升销售效率和客户满意度的关键工具。其中,多维度组织支撑下的线索客户资源分配尤为重要。它通过自动化分配、个性化服务和数据分析,优化销售流程,提高转化率与客户体验。实施步骤包括建立统一平台、制定分配规则、优化跟进流程及数据驱动决策。实际案例如联想和海康威视借助CRM系统实现了全流程优化,显著提升了销售效率与业绩。这一趋势助力企业在竞争中脱颖而出,实现可持续发展。
|
小程序 前端开发 JavaScript
微信小程序|基于微信小程序的高校就业招聘系统
微信小程序|基于微信小程序的高校就业招聘系统
425 0
|
网络协议 自动驾驶 物联网
计算机网络的发展
本文概述了计算机网络从20世纪60年代的雏形到现代互联网的发展历程,包括ARPANET的创建、TCP/IP协议的标准化、DNS系统的引入、万维网的诞生、宽带和无线网络的兴起,以及移动互联网、云计算、物联网、区块链和自动驾驶技术的最新进展。
1080 1
|
Java 应用服务中间件 Maven
JavaWeb基础5——HTTP,Tomcat&Servlet
JavaWeb技术栈、HTTP、get和post区别、响应状态码、请求响应格数据式、IDEA使用Tomcat、报错解决、Servlet的体系结构、IDEA使用模板创建Servlet
JavaWeb基础5——HTTP,Tomcat&Servlet

热门文章

最新文章