OAuth2.0实战案例

简介: 本项目基于Spring Boot与Spring Cloud构建OAuth2安全认证系统,包含授权服务器与资源服务器。通过配置JDBC存储客户端信息与Token,实现授权码、简化、密码及客户端四种模式认证。集成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

访问资源服务

相关文章
|
1天前
|
云安全 人工智能 算法
以“AI对抗AI”,阿里云验证码进入2.0时代
三层立体防护,用大模型打赢人机攻防战
1278 1
|
9天前
|
编解码 人工智能 自然语言处理
⚽阿里云百炼通义万相 2.6 视频生成玩法手册
通义万相Wan 2.6是全球首个支持角色扮演的AI视频生成模型,可基于参考视频形象与音色生成多角色合拍、多镜头叙事的15秒长视频,实现声画同步、智能分镜,适用于影视创作、营销展示等场景。
680 4
|
1天前
|
机器学习/深度学习 安全 API
MAI-UI 开源:通用 GUI 智能体基座登顶 SOTA!
MAI-UI是通义实验室推出的全尺寸GUI智能体基座模型,原生集成用户交互、MCP工具调用与端云协同能力。支持跨App操作、模糊语义理解与主动提问澄清,通过大规模在线强化学习实现复杂任务自动化,在出行、办公等高频场景中表现卓越,已登顶ScreenSpot-Pro、MobileWorld等多项SOTA评测。
460 2
|
2天前
|
人工智能 Rust 运维
这个神器让你白嫖ClaudeOpus 4.5,Gemini 3!还能接Claude Code等任意平台
加我进AI讨论学习群,公众号右下角“联系方式”文末有老金的 开源知识库地址·全免费
|
1天前
|
存储 弹性计算 安全
阿里云服务器4核8G收费标准和活动价格参考:u2a实例898.20元起,计算型c9a3459.05元起
现在租用阿里云服务器4核8G价格是多少?具体价格及配置详情如下:云服务器ECS通用算力型u2a实例,配备4核8G配置、1M带宽及40G ESSD云盘(作为系统盘),其活动价格为898.20元/1年起;此外,ECS计算型c9a实例4核8G配置搭配20G ESSD云盘,活动价格为3459.05元/1年起。在阿里云的当前活动中,4核8G云服务器提供了多种实例规格供用户选择,不同实例规格及带宽的组合将带来不同的优惠价格。本文为大家解析阿里云服务器4核8G配置的实例规格收费标准与最新活动价格情况,以供参考。
222 150
|
9天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:七十、小树成林,聚沙成塔:随机森林与大模型的协同进化
随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并结合它们的预测结果来提高准确性和稳定性。其核心思想包括两个随机性:Bootstrap采样(每棵树使用不同的训练子集)和特征随机选择(每棵树分裂时只考虑部分特征)。这种方法能有效处理大规模高维数据,避免过拟合,并评估特征重要性。随机森林的超参数如树的数量、最大深度等可通过网格搜索优化。该算法兼具强大预测能力和工程化优势,是机器学习中的常用基础模型。
350 164