Auth2.0实战案例

简介: 本项目基于Spring Boot与Spring Cloud构建,实现OAuth2四种授权模式。通过父工程统一版本管理,搭建授权服务器与资源服务器,集成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

访问资源服务

相关文章
|
测试技术
JMeter 随机数生成器详细指南:利用 Random 和 UUID 实现
在压力测试中,经常需要生成随机值来模拟用户行为。JMeter 提供了多种方式来生成随机值,本文来具体介绍一下。
|
存储 人工智能 运维
阿里云 Tair 基于 3FS 工程化落地 KVCache:企业级部署、高可用运维与性能调优实践
阿里云 Tair KVCache 团队联合硬件团队对 3FS 进行深度优化,通过 RDMA 流量均衡、小 I/O 调优及全用户态落盘引擎,提升 4K 随机读 IOPS 150%;增强 GDR 零拷贝、多租户隔离与云原生运维能力,构建高性能、高可用、易管理的 KVCache 存储底座,助力 AI 大模型推理降本增效。
|
4月前
|
人工智能 安全 前端开发
AgentScope Java v1.0 发布,让 Java 开发者轻松构建企业级 Agentic 应用
AgentScope 重磅发布 Java 版本,拥抱企业开发主流技术栈。
4042 55
|
4月前
|
JSON 安全 Java
SpringBoot鉴权
本文介绍基于Spring Security与JWT实现客户端Token认证的完整方案,涵盖登录鉴权、Token生成与验证、角色权限控制等细节。通过自定义过滤器与认证组件,结合Redis或数据库可扩展实现高效安全的无状态认证体系,适用于Spring Boot微服务架构。
|
4月前
|
存储 缓存 Java
SpringBoot自动装配机制
本章深入解析SpringBoot自动装配机制,从@SpringBootApplication注解入手,剖析其组合注解原理。重点讲解@EnableAutoConfiguration如何通过@AutoConfigurationPackage实现包扫描、通过AutoConfigurationImportSelector加载spring.factories中的自动配置类,结合@Conditional条件注解实现智能化配置。同时解析@ComponentScan组件过滤机制及自定义排除方式,揭示SpringBoot“约定优于配置”的底层实现逻辑。(238字)
|
4月前
|
关系型数据库 应用服务中间件 Nacos
Nacos配置中心
本章介绍Nacos配置中心的实现,涵盖配置管理、热更新、共享配置及优先级规则,并演示Nacos集群搭建与高可用部署,帮助掌握微服务环境下配置统一管理的核心技能。
|
4月前
|
存储 关系型数据库 索引
聚簇索引及其优缺点
聚簇索引是一种数据存储方式,InnoDB通过主键构建B+树组织数据,叶子节点即数据页。若无主键,则选非空唯一索引或隐式创建主键。辅助索引(二级索引)需两次查找:先查主键值,再查数据行。优点是查询快,尤其主键排序与范围查询;缺点是插入依赖顺序,更新主键代价高,且易引发页分裂。
|
4月前
|
SQL 存储 NoSQL
简述关系型与非关系型数据库的区别
关系型数据库基于表结构,支持SQL和事务,易于维护但读写性能差、灵活性不足;非关系型数据库格式灵活、速度快、成本低,适用于高并发场景,但缺乏SQL支持与事务机制,复杂查询较弱。
|
4月前
|
索引 关系型数据库 MySQL
MySQL索引有哪些类型
普通索引无限制;唯一索引列值唯一,可含空值;主键索引是唯一的非空索引,每表仅一个;组合索引由多列组成,提升联合查询效率;全文索引对文本分词,支持关键词搜索。
Seata AT模式的执行流程
分布式事务通过Seata实现:发起方开启全局事务,获取XID并注册分支事务;执行本地事务后上报结果;Seata根据各分支状态决定全局提交或回滚,确保数据一致性。

热门文章

最新文章