2.OAuth2.0实战案例

简介: 本项目基于Spring Boot与Spring Cloud OAuth2实现四种授权模式。通过搭建父工程、资源服务与授权服务模块,集成Security、MyBatis及MySQL,完成认证授权流程。配置JDBC存储客户端与令牌信息,支持授权码、简化、密码及客户端模式,实现安全的分布式权限管理。

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

访问资源服务

相关文章
|
Cloud Native Java API
Spring Boot 3.0 vs. 2.0
Spring Boot 3.0 带来革命性升级:全面支持 Java 17+ 与 Jakarta EE,引入原生编译、增强可观测性,推动云原生转型。相比 2.0,性能更强、启动更快、更现代。新项目应首选 3.0,老项目需逐步迁移,拥抱未来。
|
12月前
|
安全 Java 数据安全/隐私保护
2.OAuth2.0实战案例
本案例详解OAuth2.0四种授权模式实战:通过创建资源与授权模块,配置Spring Security与OAuth2,依次实现授权码、简化、密码及客户端模式的令牌申请与资源访问,完成全流程安全认证集成。
225 0
|
存储 SQL 算法
ClickHouse(13)ClickHouse合并树MergeTree家族表引擎之CollapsingMergeTree详细解析
CollapsingMergeTree是ClickHouse的一种表引擎,它扩展了`MergeTree`,通过折叠行来优化存储和查询效率。当`Sign`列值为1和-1的成对行存在时,该引擎会异步删除除`Sign`外其他字段相同的行,只保留最新状态。建表语法中,`sign`列必须为`Int8`类型,用来标记状态(1)和撤销(-1)。写入时,应确保状态和撤销行的对应关系以保证正确折叠。查询时,可能需要使用聚合函数如`sum(Sign * x)`配合`GROUP BY`来处理折叠后的数据。使用`FINAL`修饰符可强制折叠,但效率较低。系列文章提供了更多关于ClickHouse及其表引擎的详细解析。
877 1
|
人工智能 自然语言处理 运维
【新模型速递】PAI-Model Gallery云上一键部署Kimi K2模型
近日,月之暗面正式发布并开源 Kimi K2 模型,Kimi K2是具备更强代码能力、更擅长通用 Agent 任务的 MoE 架构基础模型,总参数 1T,在代码、Agent、数学推理任务上能力领先。阿里云 PAI-Model Gallery 已同步接入 Kimi K2 模型,提供企业级部署方案,支持开发者和企业用户云上零代码完成1000B超大参数模型的快速、高效部署。PAI-Model Gallery 同样支持 Qwen3 等大模型的训练、推理和评测。
|
安全 前端开发 Java
微服务技术系列教程(38)- SpringBoot -整合SpringSecurity
微服务技术系列教程(38)- SpringBoot -整合SpringSecurity
498 0
|
缓存 Linux
更新yum源的保姆级教程(有手就行)
更新yum源的保姆级教程(有手就行)
|
人工智能 前端开发 架构师
2025年前端局势分析,我该不该转行?
2024年,前端领域经历了快速变化,AIGC的兴起和市场HC减少使得前端工程师面临挑战。尽管AI工具如通义灵码和Cursor能高效生成代码,但AI无法完全取代前端工程师,因其缺乏逻辑、沟通和创新能力。前端工作不仅限于编码,还包括需求分析、代码评审等。未来,前端不会“死亡”,而是持续演变。面对大环境的压力,提升综合能力、拥抱变化、持续学习和保持身心健康是关键。转型方向包括升管理、做架构师或转讲师等。稳住2025年,需适应变化、不断学习并探索更多可能性。
3299 16
|
安全 Java API
springboot 单点登录实现原理
【7月更文挑战第2天】单点登录(Single Sign-On,SSO)是一种用户认证方式,用户在多个应用系统中只需要登录一次,就可以访问所有相互信任的应用系统。
927 1

热门文章

最新文章