首页 > 图灵资讯 > 技术篇>正文

Spring Security 与 JWT

2024-08-18 23:08:49

spring security 与 jwt

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

配置

在 spring initializr 中,我们将使用它 java 21、maven、jar 与这些依赖项目建立一个项目:

  • 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 安全规则直接应用于方法级别等注释。

  • privatekey 和 publickey:用于签名和验证 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<cliententity long> {
    optional<cliententity> findbyemail(string email);

    optional<cliententity> findbycpf(string cpf);

    optional<cliententity> findbyemailorcpf(string email, string cpf);
}
</cliententity></cliententity></cliententity></cliententity>

服务 客户服务

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(() -&gt; 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<cliententity> 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<string> protectedroute(jwtauthenticationtoken token) {
        return responseentity.ok("authorized");
    }

}
</string></cliententity>

解释
  • /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<map string>&gt; login(@RequestBody LoginDTO loginDTO) {
        var token = this.tokenService.login(loginDTO.email(), loginDTO.password());

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

}
</map>

参考
    春季安全
  • spring security-toptal 文章

以上是Spring Security 与 更多关于JWT的详细信息,请关注图灵教育的其他相关文章!

上一篇 Java 中的变量和数据类型
下一篇 返回列表

文章素材均来源于网络,如有侵权,请联系管理员删除。