Spring Security 分布式认证

本文介绍了使用JWT和RSA进行分布式认证的原理,并详细阐述了如何在Spring Security中配置JWT和RSA,包括公共模块、认证模块和资源模块的实现。通过创建独立的认证模块进行用户校验和生成token,资源模块负责验证token的有效性,实现无状态的认证过程。
摘要由CSDN通过智能技术生成

相关介绍

1)JWT
JWT:全称 JSON Web Token,是一个分布式身份校验方案,可生产 token,也可解析 token
JWT生成的 token 由三部分组成:

  • 头部:主要设置一些规范信息,签名部分的编码格式就在头部声明
  • 载荷:token 中存放有效信息的部分。比如用户名、角色、过期时间等,切记不要放密码,会泄露
  • 签名:将头部与载荷分别采用base64编码后,用“.”相连,再加入盐,最后使用头部声明的编码类型进行编码,就得到了签名。

2)RSA 非对称加密
基本原理:同时生成两把密钥(公钥和私钥),私钥隐秘保存,公钥可发放给信任的客户端

  • 私钥加密:持有私钥或公钥可解密
  • 公钥加密:持有私钥才可解密

优点:安全,难以破解
缺点:算法耗时,但可以接受

3)项目说明
在这里插入图片描述

以下只贴关键代码,需要完整代码见本文末尾 github 链接

公共模块

1)首先创建一个父工程,把其中 src 目录删除,添加 pom 依赖,主要添加 springboot 依赖


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

2)在该工程下创建子模块----公共模块
该模块放了一些 JWT 和 RSA 的工具类,因此需要加入 jwt 和 json 相关的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springsecurity_jwt_parent</artifactId>
        <groupId>com.xiao</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>common_module</artifactId>


    <dependencies>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.1</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.1</version>
            <scope>runtime</scope>
        </dependency>

        &l
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值