【Spring Security】基于SpringBoot3.3.4版本整合JWT的使用教程

摘要

Spring Boot框架版本在持续迭代中,Spring相关组件也在不断更新,JDK版本的发布频率也更加的频繁。做为一名持续学习的开发者,紧跟技术时代潮流,持续学习新技术,持续更新自己的技能储备,是往前冲锋的必备能力和品质。希望大家跟我一样,保持对技术的渴望,保持学习的激情,一起努力吧。

JWT也是现在前后端分离主流的身份认证载体,在本文中,我们会循序渐进从Spring Boot框架起步,一步步整合JWT,使用RSA公钥、私钥对JWT进行签名和验签,一点点揭开Spring Security的神秘面纱。

现在微服务开发主流的是Spring Boot框架,要开发一个微服务,其中一个非常重要的环节就是登录认证,Spring Boot针对登录认证原生有一套解决方案,对应的组件是Spring Security。接下来,让我们一步步在最新的框架版本中一起学习如何使用Spring Security完成后端微服务的登录认证吧。

本文选择目前Spring Boot最新版本3.3.4,里面使用的Spring Security版本是6.3.3OpenJDK也选择最新的一个LTS版本21IDE也选择IntelliJ IDEA目前最新的社区版本2024.2.3

本地开发环境说明

开发用到的主要框架、工具版本如下

开发依赖 版本
Spring Boot 3.3.4
Spring Security 6.3.3
nimbus-jose-jwt 9.41.1
JDK 21
IntelliJ IDEA 2024.2.3

先快速完整一个微服务的搭建

pom.xml依赖

核心内容如下

<?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>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.4</version>
        <relativePath/>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wen3.framework-demo</groupId>
    <artifactId>wen3-framework-springsecurity-demo</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

启动类

package com.wen3.security.springsecurity;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author tangheng
 */
@SpringBootApplication
public class DemoSpringSecurityApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(DemoSpringSecurityApplication.class, args);
    }
}

修改tomcat默认端口

server:
  port: 8081

这样就完成了一个最简单的Spring Boot 3.3.4版本的微服务搭建,接下来我们一点点增加内容

增加Spring Security依赖

核心内容如下

<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>
</dependencies>

简单介绍下Spring Security涉及的一些概念

为了方便大家对Spring Security有一些基本了解,把涉及的一些重要概念单独拿出来讲解一下,希望对大家理解Spring Security的流程有些帮助。

加密器

  • 主要用于用户密码的加密。
  • 接口: org.springframework.security.crypto.password.PasswordEncoder
  • 常用的实现类: org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
  • BCryptPasswordEncoder使用了较复杂的加密算法,每次生成的加密串都不一样,大大提高了破解难度

UserDetailsService接口

  • 接口: org.springframework.security.core.userdetails.UserDetailsService
  • 主要用于用户信息获取,根据账号查找用户信息,然后交由调用者进行密码等重要信息的匹配,通常需要自己实现这个接口,一般从数据库获取用户信息

AuthenticationProvider接口

  • 接口: org.springframework.security.authentication.AuthenticationProvider
  • 对用户信息进行校验,校验通过后提供用户凭证Authentication,对校验过程提供丰富的扩展支持
  • 常用的实现类: org.springframework.security.authentication.dao.DaoAuthenticationProvider
  • 这个实现类会从UserDetailsServic获取用户信息

AuthenticationManager接口

  • 接口: org.springframework.security.authentication.AuthenticationManager
  • 认证管理器,对Authentication进行认证
  • 默认是创建org.springframework.security.authentication.ProviderManager实例,然后ProviderManager再去找AuthenticationProvider,然后AuthenticationProviderUsernamePasswordAuthenticationToken进行认证

增加JWT依赖

<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>com.nimbusds</groupId>
        <artifactId>nimbus-jose-jwt</artifactId>
        <version>9.41.1</version>
    </dependency>
</dependencies>

为什么选择nimbus-jose-jwt这个开源库呢?

  • 因为在Spring Security的其它组件中,使用的也是这个JWT库,比如spring-security-oauth2-authorization-server
  • 为了与Spring Boot框架体系保持一致,在讲解Spring Security与JWT整合的时候,我们也首选nimbus-jose-jwt开源库
  • nimbus-jose-jwt开源库也使用当前最新版本9.41.1

新增启动配置类

了解完了Spring Security的几个核心概念,我们开始编写代码,先编写一个启动配置类,用于配置Spring Security,如下

package com.wen3.security.springsecurity.autoconfigure;

import com.wen3.security.springsecurity.filter.JwtFilter;
import com.wen3.security.springsecurity.filter.JwtTokenAuthenticationFilter;
import com.wen3.security.springsecurity.filter.LoginAuthenticationFilter;
import com.wen3.security.springsecurity.service.DemoDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto
Spring Boot 3.3.4 版本与 Elasticsearch 8.15.1 的集成主要是通过 Spring Data Elasticsearch 这一库来实现的。这个库允许你在 Spring Boot 应用中轻松地操作 Elasticsearch 数据库,无需手动配置大量的连接细节。 以下是整合的基本步骤: 1. **添加依赖**:在你的 `pom.xml` 或者 `build.gradle` 文件中添加对 Spring Data Elasticsearch 和 Elasticsearch 客户端的依赖。例如: ```xml <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>4.6.0</version> <!-- 注意此处版本对应实际项目需求 --> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>8.15.1</version> <!-- Elasticsearch客户端版本 --> </dependency> ``` 2. **配置**:在 `application.properties` 或者 `application.yml` 中配置 Elasticsearch 的连接信息,如 URL、认证等: ```properties spring.data.elasticsearch.cluster-name=your-cluster-name spring.data.elasticsearch.nodes=http://localhost:9200 spring.data.elasticsearch.username=elastic spring.data.elasticsearch.password=changeit ``` 3. **创建Repository**:为了操作 Elasticsearch 中的数据,你需要定义一个 Repository 接口,它会自动生成 CRUD 方法。比如: ```java public interface MyElasticsearchRepository extends ElasticsearchRepository<MyDocument, Long> { } ``` 其中 `MyDocument` 是你数据模型类的名称。 4. **使用Repository**:在服务类或者控制层中,你可以直接注入并使用生成的 Repository 对象进行数据操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太空眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值