0

0

Spring Security 与 JWT

WBOY

WBOY

发布时间:2024-08-16 10:01:20

|

1224人浏览过

|

来源于dev.to

转载

spring security 与 jwt

在本文中,我们将探讨如何将 spring security 与 jwt 集成,为您的应用程序构建坚实的安全层。我们将完成从基本配置到实现自定义身份验证过滤器的每个步骤,确保您拥有必要的工具来高效、大规模地保护您的 api。

配置

在 spring initializr 中,我们将使用 java 21mavenjar 和这些依赖项构建一个项目:

  • spring 数据 jpa
  • 春天网
  • 龙目岛
  • 春季安全
  • postgresql 驱动程序
  • oauth2 资源服务器

设置 postgresql 数据库

使用 docker,您将使用 docker-compose 创建一个 postgresql 数据库。
在项目的根目录创建一个 docker-compose.yaml 文件。

services:
  postgre:
    image: postgres:latest
    ports:
      - "5432:5432"
    environment:
      - postgres_db=database
      - postgres_user=admin
      - postgres_password=admin
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

运行命令启动容器。

docker compose up -d

设置 application.properties 文件

这个文件是spring boot应用程序的配置。

spring.datasource.url=jdbc:postgresql://localhost:5432/database
spring.datasource.username=admin
spring.datasource.password=admin

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

jwt.public.key=classpath:public.key
jwt.private.key=classpath:private.key

jwt.public.key 和 jwt.private.key 是我们将进一步创建的密钥。

生成私钥和公钥

永远不要将这些密钥提交到你的github

在控制台运行,在资源目录下生成私钥

cd src/main/resources
openssl genrsa > private.key

之后,创建链接到私钥的公钥。


openssl rsa -in private.key -pubout -out public.key 


代码

创建安全配置文件

靠近主函数创建一个目录 configs 并在其中创建一个 securityconfig.java 文件。


import java.security.interfaces.rsaprivatekey;
import java.security.interfaces.rsapublickey;

import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.http.httpmethod;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.oauth2.jwt.jwtdecoder;
import org.springframework.security.oauth2.jwt.jwtencoder;
import org.springframework.security.oauth2.jwt.nimbusjwtdecoder;
import org.springframework.security.oauth2.jwt.nimbusjwtencoder;
import org.springframework.security.web.securityfilterchain;

import com.nimbusds.jose.jwk.jwkset;
import com.nimbusds.jose.jwk.rsakey;
import com.nimbusds.jose.jwk.source.immutablejwkset;

@configuration
@enablewebsecurity
@enablemethodsecurity
public class securityconfig {

    @value("${jwt.public.key}")
    private rsapublickey publickey;

    @value("${jwt.private.key}")
    private rsaprivatekey privatekey;

    @bean
    securityfilterchain securityfilterchain(httpsecurity http) throws exception {
        http
                .csrf(csrf -> csrf.disable())
                .authorizehttprequests(auth -> auth.requestmatchers(httpmethod.post, "/signin").permitall()
                        .requestmatchers(httpmethod.post, "/login").permitall()
                        .anyrequest().authenticated())
                .oauth2resourceserver(config -> config.jwt(jwt -> jwt.decoder(jwtdecoder())));

        return http.build();
    }

    @bean
    bcryptpasswordencoder bpasswordencoder() {
        return new bcryptpasswordencoder();
    }

    @bean
    jwtencoder jwtencoder() {
        var jwk = new rsakey.builder(this.publickey).privatekey(this.privatekey).build();

        var jwks = new immutablejwkset<>(new jwkset(jwk));

        return new nimbusjwtencoder(jwks);
    }

    @bean
    jwtdecoder jwtdecoder() {
        return nimbusjwtdecoder.withpublickey(publickey).build();
    }
}

解释

  • @enablewebscurity:当您使用@enablewebsecurity时,它会自动触发spring security的配置以保护web应用程序。此配置包括设置过滤器、保护端点以及应用各种安全规则。

  • @enablemethodsecurity:是 spring security 中的一个注释,可在 spring 应用程序中启用方法级安全性。它允许您使用 @preauthorize、@postauthorize、@secured 和 @rolesallowed 等注释直接在方法级别应用安全规则。

    启山智软物流配送系统
    启山智软物流配送系统

    启山智软物流配送是基于Spring Cloud 和 Vue.js的JAVA物流配送系统。包含总控制后台 、城市合伙人(商家pc端)、 区域团长后台 、用户端小程序 、手机H5等多个操作模块。为响应用户需求我们新增了后台自定义装修组件模块,使页面更加美观,操作更加灵活简便。淘宝商品CSV一键导入,提升用户使用感。还有与众不同的管理台侧边栏设计,打破传统管理台样式。 另有公众号接龙、引导页上传、区域团

    下载
  • privatekeypublickey:是用于签名和验证 jwt 的 rsa 公钥和私钥。 @value 注解将属性文件(application.properties)中的键注入到这些字段中。

  • csrf:禁用 csrf(跨站请求伪造)保护,该保护通常在使用 jwt 进行身份验证的无状态 rest api 中禁用。

  • authorizehttprequests:配置基于url的授权规则。

      requestmatchers(httpmethod.post, "/signin").permitall():允许未经身份验证访问 /signin 和 /login 端点,这意味着任何人都可以在不登录的情况下访问这些路由。
    • anyrequest().authenticated():需要对所有其他请求进行身份验证。
  • oauth2resourceserver:将应用程序配置为使用 jwt 进行身份验证的 oauth 2.0 资源服务器。

      config.jwt(jwt -> jwt.decoder(jwtdecoder())):指定将用于解码和验证 jwt 令牌的 jwt 解码器 bean (jwtdecoder)。
  • bcryptpasswordencoder:这个bean定义了一个密码编码器,它使用bcrypt哈希算法对密码进行编码。 bcrypt 因其自适应特性而成为安全存储密码的热门选择,使其能够抵抗暴力攻击。

  • jwtencoder:这个bean负责编码(签名)jwt令牌。

      rsakey.builder:使用提供的公钥和私钥 rsa 密钥创建新的 rsa 密钥。
    • immutablejwkset(new jwkset(jwk)):将 rsa 密钥包装在 json web 密钥集 (jwkset) 中,使其不可变。
    • nimbusjwtencoder(jwks):使用 nimbus 库创建 jwt 编码器,该编码器将使用 rsa 私钥对令牌进行签名。
  • jwtdecoder:这个bean负责解码(验证)jwt令牌。

      nimbusjwtdecoder.withpublickey(publickey).build():使用rsa公钥创建jwt解码器,用于验证jwt令牌的签名。

实体

import org.springframework.security.crypto.password.passwordencoder;

import jakarta.persistence.column;
import jakarta.persistence.entity;
import jakarta.persistence.enumtype;
import jakarta.persistence.enumerated;
import jakarta.persistence.generatedvalue;
import jakarta.persistence.generationtype;
import jakarta.persistence.id;
import jakarta.persistence.table;
import lombok.getter;
import lombok.noargsconstructor;
import lombok.setter;

@entity
@table(name = "tb_clients")
@getter
@setter
@noargsconstructor
public class cliententity {

    @id
    @generatedvalue(strategy = generationtype.sequence)
    @column(name = "client_id")
    private long clientid;

    private string name;

    @column(unique = true)
    private string cpf;

    @column(unique = true)
    private string email;

    private string password;

    @column(name = "user_type")
    private string usertype = "client";

    public boolean islogincorrect(string password, passwordencoder passwordencoder) {
        return passwordencoder.matches(password, this.password);
    }
}


存储库

import java.util.optional;

import org.springframework.data.jpa.repository.jparepository;
import org.springframework.stereotype.repository;

import example.com.challengepicpay.entities.cliententity;

@repository
public interface clientrepository extends jparepository {
    optional findbyemail(string email);

    optional findbycpf(string cpf);

    optional findbyemailorcpf(string email, string cpf);
}


服务

客户服务


import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpstatus;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.stereotype.service;
import org.springframework.web.server.responsestatusexception;

import example.com.challengepicpay.entities.cliententity;
import example.com.challengepicpay.repositories.clientrepository;

@service
public class clientservice {

    @autowired
    private clientrepository clientrepository;

    @autowired
    private bcryptpasswordencoder bpasswordencoder;

    public cliententity createclient(string name, string cpf, string email, string password) {

        var clientexists = this.clientrepository.findbyemailorcpf(email, cpf);

        if (clientexists.ispresent()) {
            throw new responsestatusexception(httpstatus.bad_request, "email/cpf already exists.");
        }

        var newclient = new cliententity();

        newclient.setname(name);
        newclient.setcpf(cpf);
        newclient.setemail(email);
        newclient.setpassword(bpasswordencoder.encode(password));

        return clientrepository.save(newclient);
    }
}


代币服务


import java.time.instant;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpstatus;
import org.springframework.security.authentication.badcredentialsexception;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.oauth2.jwt.jwtclaimsset;
import org.springframework.security.oauth2.jwt.jwtencoder;
import org.springframework.security.oauth2.jwt.jwtencoderparameters;
import org.springframework.stereotype.service;
import org.springframework.web.server.responsestatusexception;

import example.com.challengepicpay.repositories.clientrepository;

@service
public class tokenservice {

    @autowired
    private clientrepository clientrepository;

    @autowired
    private jwtencoder jwtencoder;

    @autowired
    private bcryptpasswordencoder bcryptpasswordencoder;

    public string login(string email, string password) {

        var client = this.clientrepository.findbyemail(email)
                .orelsethrow(() -> new responsestatusexception(httpstatus.bad_request, "email not found"));

        var iscorrect = client.islogincorrect(password, bcryptpasswordencoder);

        if (!iscorrect) {
            throw new badcredentialsexception("email/password invalid");
        }

        var now = instant.now();
        var expiresin = 300l;

        var claims = jwtclaimsset.builder()
                .issuer("pic_pay_backend")
                .subject(client.getemail())
                .issuedat(now)
                .expiresat(now.plusseconds(expiresin))
                .claim("scope", client.getusertype())
                .build();

        var jwtvalue = jwtencoder.encode(jwtencoderparameters.from(claims)).gettokenvalue();

        return jwtvalue;

    }
}


控制器

客户端控制器


package example.com.challengepicpay.controllers;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.security.oauth2.server.resource.authentication.jwtauthenticationtoken;
import example.com.challengepicpay.controllers.dto.newclientdto;
import example.com.challengepicpay.entities.cliententity;
import example.com.challengepicpay.services.clientservice;

@restcontroller
public class clientcontroller {

    @autowired
    private clientservice clientservice;

    @postmapping("/signin")
    public responseentity createnewclient(@requestbody newclientdto client) {
        var newclient = this.clientservice.createclient(client.name(), client.cpf(), client.email(), client.password());

        return responseentity.status(httpstatus.created).body(newclient);
    }

    @getmapping("/protectedroute")
    @preauthorize("hasauthority('scope_client')")
    public responseentity protectedroute(jwtauthenticationtoken token) {
        return responseentity.ok("authorized");
    }

}

解释

  • /protectedroute 是私有路由,登录后只能使用 jwt 访问。

  • 例如,令牌必须作为不记名令牌包含在标头中。

  • 您可以稍后在应用程序中使用令牌信息,例如在服务层中。

  • @preauthorize:spring security中的@preauthorize注解用于在调用方法之前执行授权检查。此注释通常应用于 spring 组件(如控制器或服务)中的方法级别,以根据用户的角色、权限或其他安全相关条件来限制访问。 注解用于定义方法执行必须满足的条件。如果条件评估为真,则该方法继续进行。如果评估结果为 false,则访问被拒绝,

  • "hasauthority('scope_client')":检查当前经过身份验证的用户或客户端是否具有特定权限 scope_client。如果这样做,则执行 protectedroute() 方法。如果不这样做,访问将被拒绝。


token controller:在这里,你可以登录应用程序,如果成功,会返回一个token。


package example.com.challengePicPay.controllers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import example.com.challengePicPay.controllers.dto.LoginDTO;
import example.com.challengePicPay.services.TokenService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public ResponseEntity> login(@RequestBody LoginDTO loginDTO) {
        var token = this.tokenService.login(loginDTO.email(), loginDTO.password());

        return ResponseEntity.ok(Map.of("token", token));
    }

}


参考

    春季安全
  • spring security-toptal 文章

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

118

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

69

2026.01.26

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

395

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

70

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

59

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

213

2025.12.24

json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

425

2023.08.07

全国统一发票查询平台入口合集
全国统一发票查询平台入口合集

本专题整合了全国统一发票查询入口地址合集,阅读专题下面的文章了解更多详细入口。

19

2026.02.03

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 3.3万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.5万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号