OAuth2.0实战案例

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS AI 助手,专业版
简介: 本项目基于Spring Boot与Spring Cloud构建,实现OAuth2四种授权模式。通过父工程统一版本管理,分别搭建授权服务器(9001端口)与资源服务器(9002端口),集成Spring Security、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

访问资源服务

相关文章
|
开发工具 git
Git 如何将一个项目的代码放到一个新的仓库中,但不在新的仓库中显示旧的提交记录
Git 如何将一个项目的代码放到一个新的仓库中,但不在新的仓库中显示旧的提交记录
773 0
|
机器学习/深度学习 人工智能 自然语言处理
Informer:用于长序列时间序列预测的新型Transformer
Informer:用于长序列时间序列预测的新型Transformer
2521 0
Informer:用于长序列时间序列预测的新型Transformer
|
11月前
|
人工智能 JavaScript Serverless
从零开始开发 MCP Server
本文介绍如何使用Serverless Devs CLI工具从零开发并一键部署MCP Server到阿里云函数计算(FC)。首先通过初始化MCP Server项目,完成本地代码编写,利用Node.js实现一个简单的Hello World工具。接着对代码进行打包,并通过Serverless Devs工具将项目部署至云端。部署完成后,提供三种客户端接入方式:官方Client、其他本地Client及在FC上部署的Client。最后可通过内置大模型的inspector测试部署效果。Serverless Devs简化了开发流程,提升了MCP Server的构建效率。
1676 120
|
3月前
|
缓存 NoSQL Java
微服务高频面试题
本课程系统讲解微服务架构核心知识,涵盖SpringBoot与SpringCloud应用、Nacos注册与配置中心、OpenFeign远程调用、Sentinel熔断限流、Gateway网关鉴权、分布式事务Seata、RabbitMQ消息队列、Elasticsearch搜索及Redis缓存等技术,结合实战场景解析服务治理、数据同步与高并发处理方案。
|
9月前
|
JSON Java 数据库连接
IDEA的插件大总汇 (让你的工作效率大大提高!)
我是小假 期待与你的下一次相遇 ~
2802 5
visual studio 2022 社区版 c# 环境搭建及安装使用【图文解析-小白版】
这篇文章提供了Visual Studio 2022社区版C#环境的搭建和安装使用指南,包括下载、安装步骤和创建C#窗体应用程序的详细图文解析。
visual studio 2022 社区版 c# 环境搭建及安装使用【图文解析-小白版】
|
11月前
|
JavaScript 前端开发 程序员
甚至用不了五分钟就能学会vscode插件开发
本文介绍了VSCode插件的开发流程,从创建项目到最终发布。首先通过安装`yo`和`generator-code`脚手架工具初始化项目,选择JavaScript语言配置基础信息。接着,在`extension.js`中实现业务逻辑,例如将中文“变量”替换为“var”。通过F5进入调试模式验证功能。完成后使用`vsce`工具进行打包,解决可能遇到的版本不兼容或README文档问题。最后生成`.vsix`文件,可通过VSCode的“从VSIX安装”加载插件,实现开发闭环。进一步可将插件发布至官方市场供更多开发者使用。
|
Prometheus Kubernetes 负载均衡
Opentelemetry collector用法
本文详细介绍了Opentelemetry Collector的使用方法及其各个组件(receiver、processor、exporter、connector和服务配置)的功能与配置。Collector的核心组件通过官方仓库提供丰富的实现,涵盖了认证、健康监控等功能。
2225 63
Opentelemetry collector用法
|
Kubernetes 网络安全 API
在K8S中,集群内有个节点not ready,如何排查?
在K8S中,集群内有个节点not ready,如何排查?