Spring Security OAuth2 统一登录

devtools/2024/9/23 9:23:20/
介绍

Spring Security OAuth2 是一个在 Spring Security 框架基础上构建的 OAuth2 授权服务器和资源服务器的扩展库。它提供了一套功能强大的工具和组件,用于实现 OAuth2 协议中的授权流程、令牌管理和访问控制。

Git地址:yunfeng-boot3-sercurity: Spring Security OAuth2 统一登录(授权码模式)

版本

SpringBoot 2.5.6

OAuth2重要角色
  • Authorization Server : 授权服务器。
  • Resource Server: 资源服务器。举例针对微服务里面各个业务子系统:用户系统、商家系统、商品系统、订单系统等等。
  • Client:客户端:浏览器、APP、小程序等等

具体实现

OAuth2 有多种授权模式。本实例中,使用授权码模式 + 授权服务器,来实现用户的认证。

主要接口:

  • 获取授权码:http://localhost:8080/auth/oauth/authorize?response_type=code&client_id=hello&redirect_uri=http://localhost:8080&scope=all
  • 获取token:http://localhost:8080/auth/oauth/token

首先,创建一个SpringBoot应用,作为授权服务器。集成SpringBoot 2.5.6 + MySQL + Spring Security + Redis。

  1. 配置AuthorizationServerConfigurerAdapter.

继承AuthorizationServerConfigurerAdapter 主要是针对授权服务器进行自定义配置。

  • 配置token的接口权限,允许进行客户端授权。每个token都是跟某一个客户端进行关联的。所以MySQL里面

需要增加一张表,并配置好需要授权的客户端记录.

表结构如下:

CREATE TABLE `oauth_client_details` (

`client_id` varchar(256) COMMENT '客户端ID',

`resource_ids` varchar(256),

`client_secret` varchar(256) COMMENT '客户端密钥',

`scope` varchar(256),

`authorized_grant_types` varchar(256) COMMENT '授权类型',

`web_server_redirect_uri` varchar(256),

`authorities` varchar(256),

`access_token_validity` int(11) COMMENT 'access_token的有效时间',

`refresh_token_validity` int(11) COMMENT 'refresh_token的有效时间',

`additional_information` varchar(4096),

`autoapprove` varchar(256) COMMENT '是否允许自动授权',

PRIMARY KEY (`client_id`) USING BTREE

) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `weef_iot_edge_shaoyifu`.`oauth_client_details` (`client_id`, `resource_ids`, `client_secret`, `scope`, `authorized_grant_types`, `web_server_redirect_uri`, `authorities`, `access_token_validity`, `refresh_token_validity`, `additional_information`, `autoapprove`) VALUES ('hello', 'order-resource', '$2a$10$Kc3YXJdKpWEtLFD.xBSlFO5.OD94MZ7zWdl9CiQ5OGlYvSuvM8qoi', 'all', 'authorization_code,password', 'http://localhost:8080', NULL, 3600, NULL, NULL, 'true');

授权服务器代码如下:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Resourceprivate DataSource dataSource;@Resourceprivate RedisConnectionFactory redisConnectionFactory;private final static String TOKEN_STORE_PREFIX = "yf-token-store";@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {// 开启/oauth/token_key验证端口无权限访问security.tokenKeyAccess("permitAll()")// 开启/oauth/check_token验证端口认证权限访问.checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.withClientDetails(clientDetailsService());}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);tokenStore.setPrefix(TOKEN_STORE_PREFIX);endpoints.tokenStore(tokenStore);}public ClientDetailsService clientDetailsService() {return new JdbcClientDetailsService(dataSource);}}

  1. 配置WebSecurityConfigurerAdapter

继承WebSecurityConfigurerAdapter,来实现用户信息的配置。这个简化实现。内置了用户名和密码。通过这个类,可以扩展到使用MySQL来时实现,用户名和密码的校验。

同时,针对Spring Security 内置登录页面。也可以通过配置这个类,实现自定义的登录页面。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("zhangsan").password(passwordEncoder().encode("123456")).roles("ADMIN").and().passwordEncoder(passwordEncoder());System.out.println(passwordEncoder().encode("123456"));}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}}

  1. 获取code:通过浏览器访问:http://localhost:8080/auth/oauth/authorize?response_type=code&client_id=hello&redirect_uri=http://localhost:8080&scope=all

登录之后,可以拿到code

  1. 调用获取token接口:


http://www.ppmy.cn/devtools/23125.html

相关文章

【Kotlin】select简介

1 前言 协程的 select 是一种用于异步操作的选择器,它允许同时等待多个挂起函数的结果,并在其中一个完成时执行相应的操作。 能够被 select 的事件都是 SelectClause,在 select.kt 中有定义,如下。 public interface SelectBuild…

Android 音视频基础知识

本系列文章会介绍两个 Android NDK Demo,拉流端会实现一个基于 FFmpeg 的视频播放器 Demo,推流端会实现一个视频直播 Demo,当然在做 Demo 之前会介绍音视频的基础知识。以下是本系列文章的目录: Android 音视频基础知识 Android 音…

源代码加密

需求背景 随着各行各业业务数据信息化发展,各类产品研发及设计等行业,都有关乎自身发展的核心数据,包括业务数据、代码数据、机密文档、用户数据等敏感信息,这些信息数据有以下共性: 属于核心机密资料,万一…

pytest测试基础

assert 验证关键字 需要pahton版本大于3.6,因为有个工具pip3;因为做了映射,所以下面命令pip3即pip pip install -U pytest -U参数可选,是如果已安装可更新。 如果上述demo变化 通过验证代码,测试环境没问题。…

AI智能绘画系统源码 智能生成思维导图 带完整的安装代码包以及搭建教程

在数字化时代,人们对于艺术创作的需求越来越多样化,而传统的绘画方式往往受限于时间和技巧。因此,开发一款能够智能生成绘画作品的系统显得尤为重要。同时,思维导图作为一种有效的知识管理工具,也受到了广泛的关注。将…

【排序算法】快速排序

快速排序(Quick Sort)是一种常用的排序算法,它采用分而治之的策略来对一个序列进行排序。快速排序的基本思想是选择一个基准元素(通常是序列中的第一个元素),然后将序列中的其他元素分为两个子序列&#xf…

Java基础--单元测试

JUnit是Java中最流行的开源单元测试框架,用于编写和运行可重复的、自动化的单元测试。JUnit极大地简化了测试用例的编写和组织,提供了丰富的断言方法、测试运行控制、测试结果报告等功能,是遵循测试驱动开发(TDD)和持续…

Qt学习笔记1.3.1 Qt Core-容器类

文章目录 简介容器类迭代器类JAVA风格迭代器STL风格迭代器隐式共享问题 foreach关键字其他容器类算法复杂度增长策略 来源: https://doc.qt.io/archives/qt-5.12/containers.html 简介 Qt库提供基于模板的通用容器类,相比STL容器类更轻量化、安全和易用。 容器类…