2.OAuth2.0实战案例

简介: 本文介绍基于Spring Boot与Spring Cloud OAuth2搭建授权认证系统的过程,涵盖父工程创建、资源服务与授权服务配置,并实现授权码、简化、密码及客户端四种模式的测试流程,完成安全访问控制。

1.创建父工程

<groupId>com.itheima</groupId>
<artifactId>springboot_security_oauth</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.3.RELEASE</version>
  <relativePath/>
</parent>
<properties>
  <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<repositories>
  <repository>
    <id>spring-snapshots</id>
    <name>Spring Snapshots</name>
    <url>https://repo.spring.io/snapshot</url>
    <snapshots>
      <enabled>true</enabled>
    </snapshots>
  </repository>
  <repository>
    <id>spring-milestones</id>
    <name>Spring Milestones</name>
    <url>https://repo.spring.io/milestone</url>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
  </repository>
</repositories>

2.创建资源模块

2.1 创建工程并导入依赖

<parent>
  <artifactId>springboot_security_oauth</artifactId>
  <groupId>com.itheima</groupId>
  <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>oauth_source</artifactId>
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
  </dependency>
</dependencies>

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 创建工程并导入依赖

<parent>
  <artifactId>springboot_security_oauth</artifactId>
  <groupId>com.itheima</groupId>
  <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>oauth_server</artifactId>
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
  </dependency>
</dependencies>

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

访问资源服务

目录
相关文章
|
3月前
|
机器学习/深度学习 计算机视觉 网络架构
YOLO26改进 - 注意力机制 |融合HCF-Net维度感知选择性整合模块DASI 增强小目标显著性
本文介绍将HCF-Net中的维度感知选择性融合(DASI)模块集成至YOLO26检测头,通过通道分区与Sigmoid自适应加权,融合高/低维及当前层特征,显著提升红外小目标检测精度,在SIRST数据集上超越主流方法。(239字)
|
4月前
|
人工智能 安全 前端开发
写单元测试太痛苦?教你用DeepSeek/通义千问一键生成高质量测试代码
单元测试难写且枯燥?本文分享一套经过验证的AI生成指令,将DeepSeek/通义千问化身为10年经验的测试专家。支持自动Mock、全场景覆盖和参数化测试,让代码质量保障从"体力活"变成高效的"指挥活"。
924 3
|
4月前
|
应用服务中间件 测试技术 数据库
0-1教程 ChatGPT Apps Store应用提交教程——和MCP开发部署
本文以“A2Z Bill Agent”为例,详细介绍如何提交应用至ChatGPT App Store。涵盖准备App图标、MCP服务器配置、域名验证、测试用例编写、截图要求等全流程,助开发者高效完成上架。
0-1教程 ChatGPT Apps Store应用提交教程——和MCP开发部署
|
弹性计算 Linux Windows
【阿里云幻兽帕鲁】搭建 密码 存档 使用 费用 常见问题合集
幻兽帕鲁作为一款爆火的游戏,在进行多人游戏时,需要搭建服务器。本文章汇总了在阿里云上搭建幻兽帕鲁服务器时可能会遇到部署问题、配置选择问题、运行问题等,以便用户快速参考和解决搭建和运行中的挑战。
16169 0
|
自然语言处理 NoSQL Redis
短链平台设计
一种生产环境可用的短链生成方法,将长度较长、难以识别的长链转换成长度可控的短链,点击短链再跳转回长链的方法
766 0
|
4月前
|
负载均衡 应用服务中间件 Nacos
Nacos配置中心
本文详细介绍Nacos作为配置中心的实现原理与实战步骤,涵盖配置管理、热更新、共享配置优先级及集群搭建,帮助微服务应用实现配置动态化、高可用部署。
211 4
|
3月前
|
人工智能 自然语言处理 Cloud Native
阿里云开发者必读:2026年 Copilot 和 Cursor 的平替推荐排行榜 (Java与云原生专版)
随着 Qwen-2.5-Coder 等国产开源模型的爆发,国内 AI 编程工具已在性能上对标甚至反超国际竞品。对于深耕国内业务、尤其是使用 Java/Go 技术栈和阿里云设施的企业而言,寻找 Copilot 和 Cursor 的平替推荐 已不再是“降级替代”,而是“体验升级”。
阿里云开发者必读:2026年 Copilot 和 Cursor 的平替推荐排行榜 (Java与云原生专版)
|
4月前
|
Java Spring
什么是WebFlux
Spring WebFlux 是 Spring Framework 5 引入的响应式Web框架,支持非阻塞、事件驱动的编程模型,适用于高并发场景,可运行于 Netty、Undertow 等服务器,提供注解式和函数式编程接口。
87 2
|
4月前
|
JSON Dubbo Java
Feign远程调用
本章介绍如何使用Feign替代RestTemplate实现更优雅的HTTP跨服务调用。通过引入Feign,结合注册中心与注解声明,解决硬编码、可读性差等问题,并支持日志、连接池等自定义配置。同时提出继承与抽取两种最佳实践,推荐将Feign客户端抽离为独立模块,提升代码复用性与维护性,助力微服务架构优化。
149 0
Feign远程调用

热门文章

最新文章