2.OAuth2.0实战案例

简介: 本文介绍基于Spring Boot与Spring Cloud构建OAuth2授权服务的完整流程,涵盖父工程搭建、资源服务器与授权服务器配置、四种授权模式(授权码、简化、密码、客户端)的实现与测试,结合Spring Security实现安全认证,完成分布式系统下的统一权限管理。

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

访问资源服务

相关文章
|
存储 JavaScript 前端开发
JavaScript中的localStorage
JavaScript中的localStorage
253 0
全网首发:gstreamer如何接入RTSP流(IP摄像头)的代码范例
全网首发:gstreamer如何接入RTSP流(IP摄像头)的代码范例
1162 0
|
XML 安全 Java
掌握SpringBoot单点登录精髓,一键通行多系统,轻松打造无缝用户体验新纪元!
【8月更文挑战第29天】单点登录(SSO)是一种身份认证机制,用户在多个相互信任的应用系统中只需登录一次即可访问所有系统,无需重复输入凭证。本文详细介绍如何利用Spring Security和OAuth2在SpringBoot中实现SSO,并提供示例代码。核心步骤包括:引入依赖、配置认证服务器与资源服务器、实现单点登录拦截器及完成SSO配置。通过合理配置,SSO能显著提升用户体验和系统安全性。
1335 2
|
6月前
|
SQL 运维 分布式计算
如何做好SQL质量监控
SLS推出用户级SQL质量监控功能,集成于CloudLens for SLS,提供健康分、服务指标、运行明细、SQL Pattern分析及优化建议五大维度,助力用户全面掌握SQL使用情况,提升日志分析效率与治理能力。
 如何做好SQL质量监控
|
6月前
|
NoSQL Linux 网络安全
Redis集群部署指南
本章基于CentOS7讲解Redis集群搭建,涵盖单机安装、主从复制、哨兵集群及分片集群的部署与配置,详细演示Redis高可用与分布式架构实践全过程。
|
6月前
|
程序员 微服务
SpringCloud(2024)
本系列基于传智教育·黑马程序员SpringCloud课程,系统梳理2024年核心知识点。内容分“重点掌握”(实用、高级、面试篇)与“学术涉猎”两部分,前者为核心必备,后者拓展视野,兼顾学习深度与广度,助力高效掌握微服务技术体系。
203 0
|
10月前
|
存储 人工智能 数据可视化
操作手册-0代码搭建web网站AI助手
学习制作一个“公司Web网站Ai助手”,这个助手可以通过解读知识库中的公司报告信息,来回答相关问题。
|
11月前
|
存储 文件存储 Docker
威联通 Docker 国内镜像源加速配置全攻略
本文介绍了如何在威联通NAS上配置轩辕镜像仓库以加速Docker镜像拉取。内容包括:获取免登录镜像仓库地址、配置自定义存储库、测试镜像拉取及日常使用优化建议。通过简单几步即可提升镜像下载速度与稳定性,适用于个人及企业用户。
3663 1
|
11月前
|
监控 安全 Java
SpringBoot应用-Actuator监控
Spring Boot Actuator 是 Spring Boot 提供的一个独立模块,旨在通过简单的方式提供应用程序的监控和管理功能。Actuator 内置了多种端点(Endpoints),可以用于查看应用的健康状况、配置属性、日志级别等。
1272 1
|
存储 算法 Go
Go语言实战:错误处理和panic_recover之自定义错误类型
本文深入探讨了Go语言中的错误处理和panic/recover机制,涵盖错误处理的基本概念、自定义错误类型的定义、panic和recover的工作原理及应用场景。通过具体代码示例介绍了如何定义自定义错误类型、检查和处理错误值,并使用panic和recover处理运行时错误。文章还讨论了错误处理在实际开发中的应用,如网络编程、文件操作和并发编程,并推荐了一些学习资源。最后展望了未来Go语言在错误处理方面的优化方向。
235 5