• 17.Oauth2-微服务认证


    1.Oauth2

    OAuth 2.0授权框架支持第三方支持访问有限的HTTP服务,通过在资源所有者和HTTP服务之间进行一个批准交互来代表资源者去访问这些资源,或者通过允许第三方应用程序以自己的名义获取访问权限。

    image-20220506121118022

    为了方便理解,可以想象OAuth2.0就是在用户资源和第三方应用之间的一个中间层,它把资源和第三方应用隔开,使得第三方应用无法直接访问资源,从而起到保护资源的作用。

    为了访问这种受保护的资源,第三方应用(客户端)在访问的时候需要提供凭证。即,需要告诉OAuth2.0你是谁你要做什么。

    用户可以将用户名和密码告诉第三方应用,让第三方应用直接以你的名义去访问,也可以授权第三方应用去访问。

    例如,微信公众平台开发,在微信公众平台开发过程中当我们访问某个页面,页面可能弹出一个提示框应用需要获取我们的个人信息问是否允许,点确认其实就是授权第三方应用获取我们在微信公众平台的个人信息,这里微信网页授权就是使用的OAuth2.0。

    • 第三方应用程序(Third-party application): 又称之为客户端(client),我们自己开发的各种客户端,对我们自己的项目来说,QQ、微信、支付宝等是第三方应用程序。

    • HTTP 服务提供商(HTTP service): 我们开发的项目以及 QQ、微信、支付宝、钉钉等都可以称之为“服务提供商”。

    • 资源所有者(Resource Owner): 又称之为用户(user),拥有账号密码的人。

    • 用户代理(User Agent): 用来访问资源,比如浏览器,代替用户去访问这些资源。

    • 认证服务器(Authorization server): 即服务提供商专门用来处理认证的服务器,主要就是实现登录、授权功能。

    • 资源服务器(Resource server): 即服务提供商存放用户生成的资源的服务器,比如电商中的商品模块、订单模块等,是用来处理具体业务的服务器。

            OAuth2.0协议流程描述了四种角色之间的交互过程,如下图所示。

    image-20220506121307806

            简单说,OAuth 就是一种授权机制。数据的所有者告诉系统,同意授权第三方应用进入系统,获取这些数据。系统从而产生一个短期的进入令牌(token),用来代替密码,供第三方应用使用。

    令牌(token)与密码(password)的作用是一样的,都可以进入系统,但是有三点差异。

    • 令牌是短期的,到期会自动失效,用户自己无法修改。密码一般长期有效,用户不修改,就不会发生变化。

    • 令牌可以被数据所有者撤销,会立即失效。

    • 令牌有权限范围(scope),对于网络服务来说,只读令牌就比读写令牌更安全。密码一般是完整权限。

    上面这些设计,保证了令牌既可以让第三方应用获得权限,同时又随时可控,不会危及系统安全。这就是 OAuth 2.0 的优点。

    注意,只要知道了令牌,就能进入系统。系统一般不会再次确认身份,所以令牌必须保密,泄漏令牌与泄漏密码的后果是一样的。 这也是为什么令牌的有效期,一般都设置得很短的原因。

    1.1 开放平台

            开放平台(Open Platform)在软件行业和网络中,开放平台是指软件系统通过公开其应用程序编程接口(API)或函数(function)来使外部的程序可以增加该软件系统的功能或使用该软件系统的资源,而不需要更改该软件系统的源代码。

            在互联网时代,把网站的服务封装成一系列计算机易识别的数据接口开放出去,供第三方开发者使用,这种行为就叫做Open API,提供开放API的平台本身就被称为开放平台。

            第一种是技术性的开放,例如百度、腾讯、阿里巴巴等,例如阿里可以提供标准化的应用软件,但是数百万形形色色的卖家对于个性化要求的软件,并不是一个公司的力量可以满足的,所以就把这些需求开放给众多的第三方开发者的方式。再例如google的基于Linux平台的开源手机操作系统就被认为会很快打败Nokia塞班系统。这一种技术性开放平台虽然目前来看跟B2C企业的开放平台关系不大,但是也能从一定程度上说明开放平台是互联网企业的趋势。

            第二种开放平台是指软件系统通过公开其应用程序编程接口(API)或函数(function)来使外部的程序可以增加该软件系统的功能或使用该软件系统的资源,而不需要更改该软件系统的源代码。B2C企业开放平台又包含两种形式,A:淘宝商城、日本乐天这种纯平台的模式,即自己不碰商品的进销存,全部由入驻商家来做;B:美国亚马逊、当当网、京东商城这种“自营+联营”的模式。

    1.2 开放平台交互模型

    三个角色:

    • 资源拥有者:用户

    • 客户端:各种app、浏览器

    • 服务提供方:包含两个角色

      认证服务器

      资源服务器

    1.2.1 认证服务器

    认证服务器负责对用户进行认证,并授权给客户端权限。一般的认证都是通过对账号密码进行验证实现,而难点在于怎么进行授权。比如我们使用第三方登录 "哔哩哔哩",可以看到如使用 QQ 登录的授权页面上有 "哔哩哔哩将获取以下权限" 的字样以及权限信息

    image-20220506121520612

    认证服务器需要知道请求授权的客户端的身份以及该客户端请求的权限。常见的做法是为每一个客户端预先分配一个 id,并给每个 id 对应一个名称以及权限信息。这些信息可以写在认证服务器上的配置文件里,今后客户端每次打开授权页面的时候,客户端需要将该id发送到认证服务器,0Auth2.0就可以用来自动给客户端分配id,同时完成配置文件的自动更新。

    1.3 OAuth2 开放平台

    开放平台是由 OAuth2.0 协议发展而来的一个产品,它的作用是让客户端自己去这上面进行注册、申请,通过之后系统自动分配 客户端id ,并完成配置的自动更新。

    客户端要完成申请,通常需要申请人填写客户端程序的类型(Web、App、微信小程序、支付宝小程序等等)、企业信息、营业执照、法人信息以及想要获取权限等信息,申请需要得到得到服务提供上的审核通过之后,开发平台才会自动分配一个客户端id给客户端。

    在通过审核之后,第三方应用在进行认证时,就会想需要获取到的权限信息展示到页面上,例如哔哩哔哩获取QQ权限。授权成功之后认证服务器需要把产生的 access_token 发送给客户端,客户端才能访问具体的资源(头像、性别之类的),大致过程如下:

    • 让客户端在开放平台提交申请时候,填写一个 网址,例如:www.baidu.com,此网址主要用来获取认证码。

    • 当有用户授权成功之后,认证服务器将页面重定向到这个网址,并将生成的 access_token拼接到该网址后面,例如:www.baidu.com?access_token=123 

    • 客户端接收到access_token,之后客户端就可以拿着这个token去获取需要的数据了

    1.3.1 令牌

    传统项目向服务端请求数据,服务端需要频繁的去数据库查询用户名和密码并进行对比,判断用户名和密码正确与否,并作出相应提示,这样效率非常低下,怎么提高效率呢?Token便应运而生。

    Token是服务端生成的一串字符串,以作客户端进行请求的一个令牌,当第一次登录后,服务器生成一个Token便将此Token返回给客户端,以后客户端只需带上这个Token前来请求数据即可,无需再次带上用户名和密码。减轻服务器的压力,减少频繁的查询数据库,使服务器更加健壮。

    1.3.2 Access Token

    Access Token 是客户端访问资源服务器的令牌。拥有这个令牌代表着得到用户的授权,即具备了访问资源的权限。同时这个授权应该是临时的,只能在一定期限内使用。主要原因是因为Access Token 在使用的过程中很有可能会泄露,被不法分子利用获取我们的数据。所以Access Token应该只能在某个期限内使用,这样可以降低因 Access Token 泄露而带来的风险。

    1.4 认证模式

    OAuth2.0中定义了四种授权模式:

    • authorization code 授权码模式

    • implicit 简化模式

    • resource owner password credentials 密码模式

    • client credentials 客户端模式

    常见模式:授权码、密码模式

    1.4.1 授权码模式

    授权码模式(authorization code)是功能最完整、流程最严密的授权模式,code保证了token的安全性,即使code被拦截,由于没有secret,也是无法通过code获得token的。

    角色行为与功能
    • 资源所有者

      只需要允许或拒绝第三方应用获得授权

    • 第三方应用

      申请成为资源服务器的第三方应用

      获取资源服务器提供的资源

    • 授权服务器

      提供授权许可code、令牌token等

    • 资源服务器

      提供给第三方应用开放资源的接口

    image-20230423093957585

    时序图

    image-20230423094544416

    环境搭建

    创建父项目

    image-20220506141039544

    image-20220506141533483

    指定打包方式为pom

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <groupId>com.woniuxygroupId>
    7. <artifactId>oauth2artifactId>
    8. <version>1.0-SNAPSHOTversion>
    9. <packaging>pompackaging>
    10. project>

    创建auth-server认证服务器模块

    image-20220506141646384

    image-20220506141740947

    导入依赖

    image-20220506141849136

    导入依赖版本如下

    1. <properties>
    2. <java.version>1.8java.version>
    3. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    4. <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
    5. <spring-boot.version>2.3.7.RELEASEspring-boot.version>
    6. <spring-cloud-alibaba.version>2.2.2.RELEASEspring-cloud-alibaba.version>
    7. properties>

    oauth2依赖

    1. <dependency>
    2. <groupId>org.springframework.cloudgroupId>
    3. <artifactId>spring-cloud-starter-oauth2artifactId>
    4. <version>2.2.4.RELEASEversion>
    5. dependency>

    创建用户信息配置类

    1. import org.springframework.context.annotation.Bean;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    4. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    5. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    6. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    7. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    8. @Configuration
    9. @EnableWebSecurity
    10. public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{
    11. //密码编码器
    12. @Bean
    13. public BCryptPasswordEncoder passwordEncoder() {
    14. return new BCryptPasswordEncoder();
    15. }
    16. // 基于内存的用户信息
    17. @Override
    18. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    19. auth
    20. .inMemoryAuthentication() //内存认证
    21. .withUser("zhangsan") //用户名
    22. .password(passwordEncoder().encode("123")) //密码
    23. .authorities("ROLE_ADMIN"); //角色
    24. }
    25. }

    创建客户端配置类,配置客户端信息

    1. import org.springframework.context.annotation.Configuration;
    2. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    3. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
    4. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    5. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    6. import javax.annotation.Resource;
    7. @Configuration
    8. @EnableAuthorizationServer
    9. public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter{
    10. @Resource
    11. private BCryptPasswordEncoder passwordEncoder;
    12. @Override
    13. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    14. //配置客户端
    15. clients
    16. .inMemory() //内存方式
    17. .withClient("client") //客户端名字
    18. .secret(passwordEncoder.encode("secret")) //客户端秘钥
    19. .authorizedGrantTypes("authorization_code")//授权类型
    20. .scopes("all") //授权范围
    21. .redirectUris("http://www.baidu.com"); //回调网址,携带授权码
    22. }
    23. }

    在application.yml文件中配置以下信息

    1. server:
    2. port: 8000
    3. spring:
    4. application:
    5. name: oauth

    启动项目进行登录

    localhost:8000/login

    进入登录页面,输入账号:zhangsan,密码:123进行登录

    image-20220506143057117

    登录成功之后向服务器发送请求获取授权码,在地址栏上输入以下内容回车

    http://localhost:8080/oauth/authorize?client_id=client&response_type=code

    可以看到一个授权页面,询问用户是否进行授权

    image-20220506143330317

    授权成功之后会重定向到AuthorizationServerConfiguration配置类中指定的地址,并以参数的方式携带授权码

    通过postman发送请求向服务器获取token

    地址栏填写:http://client:secret@localhost:8000/oauth/token

    填写客户端账号密码

    image-20230831110955586

    填写授权类型、授权码,发送请求

    image-20220506145021696

    成功之后在postman上可以看到以下信息

    image-20220506145131136

    表示成功

    注意:每个授权码只能使用一次

    1.4.2 密码模式

    密码模式(Resource Owner Password Credentials Grant)中,用户向客户端提供自己的用户名和密码。客户端使用这些信息,向"服务商提供商"索要授权。

    在这种模式中,用户必须把自己的密码给客户端,但是客户端不得储存密码。这通常用在用户对客户端高度信任的情况下,比如客户端是操作系统的一部分,或者由一个著名公司出品。而认证服务器只有在其他授权模式无法执行的情况下,才能考虑使用这种模式。

    修改AuthorizationServerConfiguration配置类,添加密码模式

    1. @Override
    2. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    3. //配置客户端
    4. clients
    5. .inMemory()
    6. .withClient("client")
    7. .secret(passwordEncoder.encode("secret"))
    8. .authorizedGrantTypes("authorization_code","password") //添加密码授权模式
    9. .scopes("all") //授权范围
    10. .redirectUris("http://www.woniuxy.com");
    11. }

    在postman中新开一个请求,地址栏中填写:http://localhost:8080/oauth/token

    密码授权模式要求以请求头的方式提交客户端账号密码,并且需要对账号密码进行base64加密,因此选择Authorization选项卡,设置TYPE为"Basic Auth",并填写客户端账号密码

    image-20220506151829604

    在请求体中设置授权类型、用户账号密码参数

    image-20220506151940710

    发送请求测试

    image-20220506152019225

    可以发现此时并不支持密码模式,即使在AuthorizationServerConfiguration配置类中指定了密码模式。

    原因是此时代码中缺少对密码模式的支持,在oauth2中需要添加AuthenticationManager对象对密码模式进行支持。

    在WebSecurityConfiguration配置类中配置 AuthenticationManager

    1. // 配置 AuthenticationManager(密码模式需要该对象进行账号密码校验)
    2. @Bean
    3. @Override
    4. public AuthenticationManager authenticationManagerBean() throws Exception {
    5. return super.authenticationManagerBean();
    6. }

    在AuthorizationServerConfiguration类中注入AuthenticationManager,并重写以下方法

    1. // 认证管理器
    2. @Autowired
    3. private AuthenticationManager authenticationManager;
    4. //配置使用的 AuthenticationManager 实现用户认证的功能
    5. @Override
    6. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    7. endpoints.authenticationManager(authenticationManager);
    8. }

    重启项目再次发送请求获取token

    image-20220506152551071

    整合JWT

    导入了oauth2依赖就自动导入的JWT相关依赖,因此不用单独导入JWT,只需要进行设置就行

    创建TokenConfiguration配置类

    1. import org.springframework.context.annotation.Bean;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.security.oauth2.provider.token.TokenStore;
    4. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
    5. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
    6. @Configuration
    7. public class TokenConfiguration {
    8. // 密码
    9. private static String SIGNING_KEY="www.woniuxy.com";
    10. // token转换器
    11. @Bean
    12. public JwtAccessTokenConverter accessTokenConverter() {
    13. JwtAccessTokenConverter jwtAccessTokenConverter =
    14. new JwtAccessTokenConverter();
    15. jwtAccessTokenConverter.setSigningKey(SIGNING_KEY);
    16. return jwtAccessTokenConverter;
    17. }
    18. // 令牌存储策略:jwt方式
    19. @Bean
    20. public TokenStore tokenStore(){
    21. return new JwtTokenStore(accessTokenConverter());
    22. }
    23. }

    在AuthorizationServerConfiguration配置类中注入相关对象

    1. @Resource
    2. private TokenStore tokenStore;
    3. @Resource
    4. private JwtAccessTokenConverter jwtAccessTokenConverter;
    5. @Resource
    6. private ClientDetailsService clientDetailsService;

    在AuthorizationServerConfiguration配置类中编写token服务方法,该方法主要用来设置

    1. private AuthorizationServerTokenServices tokenServices(){
    2. // 创建服务对象
    3. DefaultTokenServices services = new DefaultTokenServices();
    4. // 设置客户端详情服务
    5. services.setClientDetailsService(clientDetailsService);
    6. // 支持刷新令牌
    7. services.setSupportRefreshToken(true);
    8. // 不重复使用refreshtoken,每次刷新之后只能用新的refreshtoken才能继续刷新
    9. services.setReuseRefreshToken(false);
    10. // 设置令牌存储策略
    11. services.setTokenStore(tokenStore);
    12. // 设置令牌增强
    13. TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    14. tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
    15. services.setTokenEnhancer(tokenEnhancerChain);
    16. // 设置令牌过期时间
    17. services.setAccessTokenValiditySeconds(600);
    18. services.setRefreshTokenValiditySeconds(6000);
    19. return services;
    20. }

    修改configure(AuthorizationServerEndpointsConfigurer endpoints)方法,添加token服务

    1. //配置使用的 AuthenticationManager 实现用户认证的功能
    2. @Override
    3. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    4. endpoints
    5. .authenticationManager(authenticationManager) // 认证管理器
    6. .tokenServices(tokenServices()); // 配置token服务
    7. }

    重启项目发送请求获取token

    image-20220506160230848

    如果想要获取到refreshtoken,可以修改AuthorizationServerConfiguration配置类,添加refresh_token授权方式

    1. @Override
    2. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    3. //配置客户端
    4. clients
    5. .inMemory()
    6. .withClient("client")
    7. .secret(passwordEncoder.encode("secret"))
    8. .authorizedGrantTypes("authorization_code","password","refresh_token")
    9. .scopes("all")
    10. .redirectUris("http://www.woniuxy.com");
    11. }

    重启项目测试

    image-20220506161053399

    image-20220506161135294

    整合数据库(user)

    建表SQL

    1. create database sc default character set=utf8;
    2. DROP TABLE IF EXISTS `perms`;
    3. CREATE TABLE `perms` (
    4. `id` int(11) DEFAULT NULL,
    5. `name` varchar(20) DEFAULT NULL
    6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    7. INSERT INTO `perms` VALUES (3001,'user:add'),(3002,'user:del'),(3003,'user:find'),(3004,'user:update'),(3005,'goods:add'),(3006,'goods:find'),(3007,'goods:del'),(3008,'goods:update');
    8. DROP TABLE IF EXISTS `role`;
    9. CREATE TABLE `role` (
    10. `id` int(11) DEFAULT NULL,
    11. `name` varchar(20) DEFAULT NULL
    12. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    13. INSERT INTO `role` VALUES (2001,'ROLE_ADMIN'),(2002,'ROLE_USER');
    14. DROP TABLE IF EXISTS `role_perms`;
    15. CREATE TABLE `role_perms` (
    16. `rid` int(11) DEFAULT NULL,
    17. `pid` int(11) DEFAULT NULL
    18. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    19. INSERT INTO `role_perms` VALUES (2001,3001),(2001,3003),(2001,3004),(2002,3005),(2002,3006),(2002,3007),(2002,3008);
    20. DROP TABLE IF EXISTS `user`;
    21. CREATE TABLE `user` (
    22. `id` int(11) DEFAULT NULL,
    23. `username` varchar(20) DEFAULT NULL,
    24. `password` varchar(64) DEFAULT NULL
    25. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    26. INSERT INTO `user` VALUES (1001,'zhangsan','$2a$10$pINVnd8.cXScFXCxI2x4cem4fOexA2J5TNY/Mx2CjN6mJuYGBNG0m'),(1002,'wangwu','wangwu');
    27. DROP TABLE IF EXISTS `user_role`;
    28. CREATE TABLE `user_role` (
    29. `uid` int(11) DEFAULT NULL,
    30. `rid` int(11) DEFAULT NULL
    31. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    32. INSERT INTO `user_role` VALUES (1001,2001),(1002,2002),(1003,2002);

    auth-server的pom.xml中引入mybatis

    1. org.mybatis.spring.boot
    2. mybatis-spring-boot-starter
    3. 2.1.4

    在application.yml中配置mybatis参数

    1. mybatis:
    2. type-aliases-package: com.woniuxy.authserver.entity
    3. mapper-locations: classpath:/mapper/*.xml

    创建Perms、Role、User实体类,注意:实体类必须实现序列化接口,不然运行过程中可能会报Failed to find access token for token错误

    1. import lombok.Data;
    2. @Data
    3. public class Perms implements Serializable {
    4. private static final long serialVersionUID = 1L;
    5. private int id;
    6. private String name;
    7. }
    1. import lombok.Data;
    2. import java.util.List;
    3. @Data
    4. public class Role implements Serializable {
    5. private static final long serialVersionUID = 1L;
    6. private int id;
    7. private String name;
    8. private List perms;
    9. }
    1. import lombok.AllArgsConstructor;
    2. import lombok.Data;
    3. import lombok.NoArgsConstructor;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.springframework.security.core.GrantedAuthority;
    6. import org.springframework.security.core.authority.SimpleGrantedAuthority;
    7. import org.springframework.security.core.userdetails.UserDetails;
    8. import java.io.Serializable;
    9. import java.util.ArrayList;
    10. import java.util.Collection;
    11. import java.util.List;
    12. @Slf4j
    13. @Data
    14. @NoArgsConstructor
    15. @AllArgsConstructor
    16. public class User implements UserDetails, Serializable {
    17. private static final long serialVersionUID = 1L;
    18. private int id;
    19. private String username;
    20. private String password;
    21. private List roles;
    22. // 返回当前用户的所有角色、权限信息
    23. @Override
    24. public Collectionextends GrantedAuthority> getAuthorities() {
    25. log.debug("获取用户角色权限信息");
    26. // 新建集合
    27. List grantedAuthorities = new ArrayList<>();
    28. // 遍历role
    29. for(Role role : this.roles){
    30. // 放入角色信息
    31. grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    32. // 遍历当前角色的所有权限信息
    33. for(Perms perms : role.getPerms()){
    34. grantedAuthorities.add(new SimpleGrantedAuthority(perms.getName()));
    35. }
    36. }
    37. log.debug(grantedAuthorities.toString());
    38. return grantedAuthorities;
    39. }
    40. // 获取用户名
    41. @Override
    42. public String getUsername() {
    43. return this.username;
    44. }
    45. // 账号是否过期 true表示未过期 false表示过期
    46. @Override
    47. public boolean isAccountNonExpired() {
    48. return true;
    49. }
    50. // 账号是否被锁定 true表示未锁定 false表示锁定
    51. @Override
    52. public boolean isAccountNonLocked() {
    53. return true;
    54. }
    55. // 凭证是否过期 true表示未过期 false表示过期
    56. @Override
    57. public boolean isCredentialsNonExpired() {
    58. return true;
    59. }
    60. // 用户是否被禁用 true表示未禁用 false表示禁用
    61. @Override
    62. public boolean isEnabled() {
    63. return true;
    64. }
    65. }

    创建UerMapper接口

    1. import com.woniuxy.springsecurity.entity.User;
    2. import org.apache.ibatis.annotations.Mapper;
    3. @Mapper
    4. public interface UserMapper {
    5. public User findByName(String username);
    6. }

    在resources目录下创建mapper文件夹,并在该文件夹下创建Mapper文件

    image-20220416173702294

    1. "1.0" encoding="UTF-8" ?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3. <mapper namespace="com.woniuxy.authserver.mapper.UserMapper" >
    4. <select id="findByName" resultMap="user_map">
    5. select * from user where username = #{username}
    6. select>
    7. <resultMap id="user_map" type="User">
    8. <id column="id" property="id">id>
    9. <result column="username" property="username">result>
    10. <result column="password" property="password">result>
    11. <collection property="roles" ofType="Role" column="id" select="findRolesByUid">collection>
    12. resultMap>
    13. <select id="findRolesByUid" resultMap="role_map">
    14. select r.id,r.name from user_role ur,role r where ur.rid = r.id and ur.uid = #{id}
    15. select>
    16. <resultMap id="role_map" type="Role">
    17. <id column="id" property="id">id>
    18. <result column="name" property="name">result>
    19. <collection property="perms" ofType="Perms" column="id" select="findPermsByRid">collection>
    20. resultMap>
    21. <select id="findPermsByRid" resultType="Perms">
    22. select p.id,p.name from role_perms rp,perms p where rp.pid = p.id and rp.rid = #{rid}
    23. select>
    24. mapper>

    创建CustomUserDetailsServiceImpl类实现UserDetailsService接口

    1. import com.woniuxy.authserver.entity.User;
    2. import com.woniuxy.authserver.mapper.UserMapper;
    3. import org.springframework.security.core.userdetails.UserDetails;
    4. import org.springframework.security.core.userdetails.UserDetailsService;
    5. import org.springframework.security.core.userdetails.UsernameNotFoundException;
    6. import org.springframework.stereotype.Service;
    7. import javax.annotation.Resource;
    8. @Service
    9. public class CustomUserDetailsServiceImpl implements UserDetailsService {
    10. @Resource
    11. private UserMapper userMapper;
    12. @Override
    13. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    14. //1.查询用户
    15. User user = userMapper.findByName(username);
    16. //2.判断
    17. if (user == null) throw new UsernameNotFoundException("用户不存在");
    18. //3.返回用户信息
    19. return user;
    20. }
    21. }

    在配置类WebSecurityConfiguration中注入UserDetailsService对象,并修改configure(AuthenticationManagerBuilder auth)反方指定用户信息从数据库中获取

    1. @Resource
    2. private UserDetailsService userDetailsService;
    3. @Override
    4. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    5. //auth
    6. //.inMemoryAuthentication() //内存认证
    7. //.withUser("zhangsan") //用户名
    8. //.password(passwordEncoder().encode("123")) //密码
    9. //.authorities("ROLE_ADMIN"); //角色
    10. auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    11. }

    重启auth-server服务,进行认证

    封装用户id

    在生成token时可以将用户id封装到token中,以便后期使用

    修改TokenConfiguration类中的accessTokenConverter()方法,在创建转换器时重写enhance方法

    1. // token转换器
    2. @Bean
    3. public JwtAccessTokenConverter accessTokenConverter() {
    4. JwtAccessTokenConverter jwtAccessTokenConverter =
    5. new JwtAccessTokenConverter(){
    6. @Override
    7. public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    8. final Map map = new HashMap<>();
    9. // 从认证对象中得到用户信息
    10. User user = (User) authentication.getUserAuthentication().getPrincipal();
    11. // 将用户id放到token中
    12. map.put("uid", user.getId());
    13. ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(map);
    14. // 返回
    15. return super.enhance(accessToken, authentication);
    16. }
    17. };
    18. jwtAccessTokenConverter.setSigningKey(SIGNING_KEY);
    19. return jwtAccessTokenConverter;
    20. }

    利用postman进行测试

    image-20220726160937503

    返回的结果中可以看到用户id,token中也包含了用户id

    检验token是否过期

    在org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint类中定义了校验token的接口/oauth/check_token,该接口可以用来校验token是否合法、是否过期、是否是伪造的

    1. @RequestMapping(value = "/oauth/check_token")
    2. @ResponseBody
    3. public Map checkToken(@RequestParam("token") String value) {
    4. OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
    5. if (token == null) {
    6. throw new InvalidTokenException("Token was not recognised");
    7. }
    8. if (token.isExpired()) {
    9. throw new InvalidTokenException("Token has expired");
    10. }
    11. OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());
    12. Map response = (Map)accessTokenConverter.convertAccessToken(token, authentication);
    13. // gh-1070
    14. response.put("active", true); // Always true if token exists and not expired
    15. return response;
    16. }

    只是该接口oauth2默认情况下是不对外公开的,如果要使用该接口那就必须手动配置开启,在AuthorizationServerConfiguration配置类中重写以下方法

    1. //设置 /oauth/check_token 端点,通过认证后可访问。
    2. //该端点对应 CheckTokenEndpoint类,用于校验访问令牌的有效性。
    3. //在客户端访问资源服务器时,会在请求中带上访问令牌。
    4. //在资源服务器收到客户端的请求时,会使用请求中的访问令牌,找授权服务器确认该访问令牌的有效性。
    5. @Override
    6. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    7. // 默认是denyAll():拒绝所有
    8. oauthServer.checkTokenAccess("permitAll()");
    9. }

    checkTokenAccess常用值有三种:

    • denyAll():拒绝所有请求,不开放该接口

    • isAuthenticated():只对完成认证之后的请求开放

    • permitAll():对所有请求开放

    测试:登录成功之后在Postman中发送请求进行测试

    接口url:http://localhost:8080/oauth/check_token

    image-20220726114103407

    返回的结果中包含了用户的用户名、权限等信息,还包括了token是否可用的信息

    如果返回以下信息表示token已经过期

    image-20230831142542647

    而如果返回以下信息表示token非法

    image-20230831142606770

    通过refresh_token获取新token

    获取token和刷新token使用的是同一个接口,所以地址栏url还是

    http://local:8080/oauth/token

    只是grant_type需要换成refresh_token,然后将之前的refresh token作为参数传递给后台

    image-20220507100748397

    还是需要将客户端id、密码以base64编码放到请求头中

    image-20220507100833359

    发送请求得到结果

    image-20220507101406277

    根据结果可以知道,token和refresh_token都会自动刷新,这样做的好处是当token过期时通过程序调用刷新接口,获取到新的token和refresh_token,实现自动续期。

    refresh_token如果过期会得到以下结果

    image-20220726115252787

    refresh_token过期就需要重新登录

    1.5 资源服务器

    创建resource子模块,导入相关依赖

    image-20220507112247458

    设置父子关系

    创建OAuth2ResourceServerConfig配置类

    1. import org.springframework.context.annotation.Configuration;
    2. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    3. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    4. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    5. @Configuration
    6. @EnableResourceServer
    7. public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
    8. @Override
    9. public void configure(HttpSecurity http) throws Exception {
    10. http.authorizeRequests()
    11. // 设置请求,需要认证后访问
    12. .anyRequest().authenticated();
    13. }
    14. }

    创建controller

    1. import org.springframework.web.bind.annotation.RequestMapping;
    2. import org.springframework.web.bind.annotation.RestController;
    3. @RestController
    4. @RequestMapping("/resource")
    5. public class ResourceController {
    6. @RequestMapping("/info")
    7. public String info(){
    8. return "success";
    9. }
    10. }

    配置application.yml

    1. server:
    2. port: 8001
    3. spring:
    4. application:
    5. name: resource
    6. security:
    7. oauth2:
    8. # OAuth2 Client 配置,对应 OAuth2ClientProperties 类
    9. client:
    10. client-id: client
    11. client-secret: secret
    12. # OAuth2 Resource 配置,对应 ResourceServerProperties 类
    13. resource:
    14. token-info-uri: http://127.0.0.1:8000/oauth/check_token # 获得 Token 信息的 URL
    15. # 访问令牌获取 URL,自定义的
    16. access-token-uri: http://127.0.0.1:8000/oauth/token
    17. management:
    18. endpoints:
    19. web:
    20. exposure:
    21. include: '*'

    启动resource资源服务器

    先进行认证,得到token和refresh_token

    localhost:8000/oauth/token

    image-20220507115312984

    然后将得到的token放到请求资源服务器的请求头中

    image-20220507115927410

    发送请求后可以发现报500错误,查看resource控制台可以发现以下信息

    org.springframework.web.client.HttpClientErrorException$Forbidden: 403 : [{"timestamp":"2022-05-07T03:40:14.063+00:00","status":403,"error":"Forbidden","message":"","path":"/oauth/check_token"}]

    根据信息提示:没有权限访问 /oauth/check_token,该URL是认证服务器用来校验token是否合法的接口。资源服务器在接收到请求时会获取到token,然后调用认证服务器的/oauth/check_token接口去检验token,但是此时认证服务器还没有开放该端口(默认关闭),所以造成了403无法访问。

    到认证服务器的AuthorizationServerConfiguration配置类中开启/oauth/check_token

    1. //设置 /oauth/check_token 端点,通过认证后可访问。
    2. //该端点对应 CheckTokenEndpoint类,用于校验访问令牌的有效性。
    3. //在客户端访问资源服务器时,会在请求中带上访问令牌。
    4. //在资源服务器收到客户端的请求时,会使用请求中的访问令牌,找授权服务器确认该访问令牌的有效性。
    5. @Override
    6. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    7. // 默认是denyAll():拒绝所有
    8. oauthServer.checkTokenAccess("isAuthenticated()");
    9. }

    重启认证服务器

    重新进行认证得到token,然后用新的token再访问资源服务器

    image-20220507120732391

    看到success表明成功

    角色权限管理

    在资源服务器主启动类上添加@EnableGlobalMethodSecurity注解,开启spring security权限注解的支持

    1. import org.springframework.boot.SpringApplication;
    2. import org.springframework.boot.autoconfigure.SpringBootApplication;
    3. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    4. @SpringBootApplication
    5. @EnableGlobalMethodSecurity(prePostEnabled = true)
    6. public class ResourceApplication {
    7. public static void main(String[] args) {
    8. SpringApplication.run(ResourceApplication.class, args);
    9. }
    10. }

    在resource/info接口方法上添加注解@PreAuthorize并指定角色或权限

    1. @RequestMapping("/info")
    2. @PreAuthorize("hasRole('USER')")
    3. public String info(){
    4. return "success";
    5. }

    利用postman再次访问该接口

    image-20220507150406869

    得到不允许访问的结果,表明角色权限管理生效

    1.6 整合数据库(client)

    建表SQL

    1. CREATE TABLE `clientdetails` (
    2. `appId` VARCHAR(128) NOT NULL,
    3. `resourceIds` VARCHAR(256) DEFAULT NULL,
    4. `appSecret` VARCHAR(256) DEFAULT NULL,
    5. `scope` VARCHAR(256) DEFAULT NULL,
    6. `grantTypes` VARCHAR(256) DEFAULT NULL,
    7. `redirectUrl` VARCHAR(256) DEFAULT NULL,
    8. `authorities` VARCHAR(256) DEFAULT NULL,
    9. `access_token_validity` INT(11) DEFAULT NULL,
    10. `refresh_token_validity` INT(11) DEFAULT NULL,
    11. `additionalInformation` VARCHAR(4096) DEFAULT NULL,
    12. `autoApproveScopes` VARCHAR(256) DEFAULT NULL,
    13. PRIMARY KEY (`appId`)
    14. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    15. CREATE TABLE `oauth_access_token` (
    16. `token_id` VARCHAR(256) DEFAULT NULL,
    17. `token` BLOB,
    18. `authentication_id` VARCHAR(128) NOT NULL,
    19. `user_name` VARCHAR(256) DEFAULT NULL,
    20. `client_id` VARCHAR(256) DEFAULT NULL,
    21. `authentication` BLOB,
    22. `refresh_token` VARCHAR(256) DEFAULT NULL,
    23. PRIMARY KEY (`authentication_id`)
    24. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    25. CREATE TABLE `oauth_approvals` (
    26. `userId` VARCHAR(256) DEFAULT NULL,
    27. `clientId` VARCHAR(256) DEFAULT NULL,
    28. `scope` VARCHAR(256) DEFAULT NULL,
    29. `status` VARCHAR(10) DEFAULT NULL,
    30. `expiresAt` TIMESTAMP NULL DEFAULT NULL,
    31. `lastModifiedAt` TIMESTAMP NULL DEFAULT NULL
    32. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    33. CREATE TABLE `oauth_client_details` (
    34. `client_id` VARCHAR(128) NOT NULL,
    35. `resource_ids` VARCHAR(256) DEFAULT NULL,
    36. `client_secret` VARCHAR(256) DEFAULT NULL,
    37. `scope` VARCHAR(256) DEFAULT NULL,
    38. `authorized_grant_types` VARCHAR(256) DEFAULT NULL,
    39. `web_server_redirect_uri` VARCHAR(256) DEFAULT NULL,
    40. `authorities` VARCHAR(256) DEFAULT NULL,
    41. `access_token_validity` INT(11) DEFAULT NULL,
    42. `refresh_token_validity` INT(11) DEFAULT NULL,
    43. `additional_information` VARCHAR(4096) DEFAULT NULL,
    44. `autoapprove` VARCHAR(256) DEFAULT NULL,
    45. PRIMARY KEY (`client_id`)
    46. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    47. CREATE TABLE `oauth_client_token` (
    48. `token_id` VARCHAR(256) DEFAULT NULL,
    49. `token` BLOB,
    50. `authentication_id` VARCHAR(128) NOT NULL,
    51. `user_name` VARCHAR(256) DEFAULT NULL,
    52. `client_id` VARCHAR(256) DEFAULT NULL,
    53. PRIMARY KEY (`authentication_id`)
    54. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    55. CREATE TABLE `oauth_code` (
    56. `code` VARCHAR(256) DEFAULT NULL,
    57. `authentication` BLOB
    58. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    59. CREATE TABLE `oauth_refresh_token` (
    60. `token_id` VARCHAR(256) DEFAULT NULL,
    61. `token` BLOB,
    62. `authentication` BLOB
    63. ) ENGINE=INNODB DEFAULT CHARSET=utf8;

    在表 oauth_client_details 中增加一条客户端配置记录,在填入时可以按照AuthorizationServerConfiguration配置类中的客户端配置进行配置

    配置的效果如下:

    image-20220507161710501

    注:各字段解释说明

    • client_id:客户端标识

    • client_secret:客户端安全码。注意安全码不能是明文需要加密,此处可以写一段程序,然后使用BCryptPasswordEncoder为客户端安全码加密,得到加密之后的安全码,再写入到数据库中,例如:

    • System.out.println(new BCryptPasswordEncoder().encode("secret"));

    • scope:客户端授权范围

    • authorized_grant_types:客户端授权类型,支持多种类型,多种类型之间用逗号隔开

    • web_server_redirect_uri:服务器回调地址

    创建实体类User、Role、Perms

    在auth-server模块的pom.xml中引入mybatis相关依赖

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-jdbcartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>mysqlgroupId>
    7. <artifactId>mysql-connector-javaartifactId>
    8. dependency>
    9. <dependency>
    10. <groupId>org.springframework.bootgroupId>
    11. <artifactId>spring-boot-configuration-processorartifactId>
    12. <optional>trueoptional>
    13. dependency>

    application.yml文件中添加数据库相关配置

    1. server:
    2. port: 8000
    3. spring:
    4. application:
    5. name: oauth
    6. datasource:
    7. type: com.zaxxer.hikari.HikariDataSource
    8. driver-class-name: com.mysql.cj.jdbc.Driver
    9. jdbc-url: jdbc:mysql://localhost:3306/sc?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    10. username: root
    11. password: root
    12. hikari:
    13. minimum-idle: 5
    14. maximum-pool-size: 10
    15. auto-commit: true #自动提交
    16. pool-name: MYHIKARICP
    17. connection-test-query: SELECT 1 #测试是否能连接上数据库的SQL语句
    18. main:
    19. #true,后定义的bean会覆盖之前定义的相同名称的bean,生成dataSource替换掉原生的dataSource
    20. allow-bean-definition-overriding: true

    创建数据库配置类DataSourceConfiguration,主要配置用到的数据源,用HikariCP连接池的数据源替换到spring内置的数据源。

    1. import org.springframework.boot.context.properties.ConfigurationProperties;
    2. import org.springframework.boot.jdbc.DataSourceBuilder;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.context.annotation.Primary;
    6. import javax.sql.DataSource;
    7. @Configuration
    8. public class DataSourceConfiguration {
    9. @Bean
    10. @Primary
    11. //根据application.yml中的配置信息创建dataSource
    12. @ConfigurationProperties(prefix = "spring.datasource")
    13. //import javax.sql.DataSource;
    14. public DataSource dataSource() {
    15. //创建dataSource
    16. return DataSourceBuilder.create().build();
    17. }
    18. }

    在TokenConfiguration配置类中把token存储策略改成JDBC方式,将jwt存放到数据库中DataSource

    1. @Resource
    2. private DataSource dataSource;
    3. // 令牌存储策略:jwt方式
    4. @Bean
    5. public TokenStore tokenStore(DataSource dataSource){
    6. //return new JwtTokenStore(accessTokenConverter());
    7. return new JdbcTokenStore(dataSource);
    8. }

    修改AuthorizationServerConfiguration配置类,添加ClientDetailsService clientDetailsService(DataSource dataSource)方法,让程序通过DataSource从数据库中获取到客户端信息

    1. @Bean
    2. public ClientDetailsService clientDetailsService(DataSource dataSource) {
    3. //在数据库中去获取客户端信息(oauth_client_details表)
    4. return new JdbcClientDetailsService(dataSource);
    5. }

    修改configure(ClientDetailsServiceConfigurer clients)方法指定到数据库获取客户端信息

    1. @Override
    2. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    3. //配置客户端
    4. //clients
    5. //.inMemory() //内存方式
    6. //.withClient("client") //客户端名字
    7. //.secret(passwordEncoder.encode("secret")) //客户端秘钥
    8. //.authorizedGrantTypes("authorization_code","password","refresh_token")
    9. //.scopes("all") //授权范围
    10. //.redirectUris("http://www.woniuxy.com"); //回调网址
    11. clients.withClientDetails(clientDetailsService);
    12. }

    完成之后重启项目,再次进行认证测试

    正常情况下,测试完毕之后会在数据库的oauth_access_token 表中会增加一个记录,这个记录就是浏览器获取到的token和refresh token

    image-20220509101431817

    角色、权限管理测试

    在resource服务的controller中添加以下方法

    1. @RequestMapping("/message")
    2. @PreAuthorize("hasRole('ADMIN')")
    3. public String message(){
    4. return "message";
    5. }
    6. @RequestMapping("/data")
    7. @PreAuthorize("hasAuthority('user:add')")
    8. public String data(){
    9. return "data";
    10. }
    11. @RequestMapping("/test")
    12. @PreAuthorize("hasAuthority('user:del')")
    13. public String test(){
    14. return "test";
    15. }

    启动resource服务,通过postman分别测试info、message、data、test接口,如果只有message、data接口可以访问,那么说明角色、权限管理成功。

  • 相关阅读:
    说说你知道的关于BeanFactory和FactoryBean的区别
    <<Java>> Thread 类的基本用法
    黑客(网络安全)技术自学30天
    进程和线程ID
    算法提升(二) 异或法
    使用命令行创建仓库
    R语言caret机器学习(三):数据预处理下集
    基于模板匹配的手写字体数字识别-含Matlab代码
    【leetcode周赛总结】LeetCode第 81 场双周赛(6.25)
    数据库原理与应用——引言(二)
  • 原文地址:https://blog.csdn.net/LB_bei/article/details/132607336