”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Spring Security 与 JWT

Spring Security 与 JWT

发布于2024-11-08
浏览:475

Spring Security with JWT

In this article, we will explore how to integrate Spring Security with JWT to build a solid security layer for your application. We will go through each step, from basic configuration to implementing a custom authentication filter, ensuring you have the necessary tools to protect your APIs efficiently and at scale.

Configuration

At the Spring Initializr we're gonna build a project with Java 21, Maven, Jar and these dependencies:

  • Spring Data JPA
  • Spring Web
  • Lombok
  • Spring Security
  • PostgreSQL Driver
  • OAuth2 Resource Server

Set up the PostgreSQL database

With Docker you're going to create a PostgreSql database with Docker-compose.
Create a docker-compose.yaml file at the root of you project.

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:

Run the command to start the container.

docker compose up -d

Set up application.properties file

This file is the configuration for the spring boot application.

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

The jwt.public.key and jwt.private.key are keys that we are going to create further.

Generate the private and public keys

NEVER commit those keys to your github

Run at the console to generate the private key at the resources directory

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

After, create the public key linked to the private key.

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

Code

Create a SecurityConfig file

Closer to the main function create a directory configs and inside that a SecurityConfig.java file.

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();
    }
}

Explanation

  • @EnableWebScurity: When you use @EnableWebSecurity, it automatically triggers Spring Security's configuration for securing web applications. This configuration includes setting up filters, securing endpoints, and applying various security rules.

  • @EnableMethodSecurity: is an annotation in Spring Security that enables method-level security in your Spring application. It allows you to apply security rules directly at the method level using annotations like @PreAuthorize, @PostAuthorize, @Secured, and @RolesAllowed.

  • privateKey and publicKey: are the RSA public and private keys used for signing and verifying JWTs. The @Value annotation injects the keys from the properties file(application.properties) into these fields.

  • CSRF: Disables CSRF (Cross-Site Request Forgery) protection, which is often disabled in stateless REST APIs where JWT is used for authentication.

  • authorizeHttpRequests: Configures URL-based authorization rules.

    • requestMatchers(HttpMethod.POST, "/signin").permitAll(): Allows unauthenticated access to the /signin and /login endpoints, meaning anyone can access these routes without being logged in.
    • anyRequest().authenticated(): Requires authentication for all other requests.
  • oauth2ResourceServer: Configures the application as an OAuth 2.0 resource server that uses JWT for authentication.

    • config.jwt(jwt -> jwt.decoder(jwtDecoder())): Specifies the JWT decoder bean (jwtDecoder) that will be used to decode and validate the JWT tokens.
  • BCryptPasswordEncoder: This bean defines a password encoder that uses the BCrypt hashing algorithm to encode passwords. BCrypt is a popular choice for securely storing passwords due to its adaptive nature, making it resistant to brute-force attacks.

  • JwtEncoder: This bean is responsible for encoding (signing) JWT tokens.

    • RSAKey.Builder: Creates a new RSA key using the provided public and private RSA keys.
    • ImmutableJWKSet(new JWKSet(jwk)): Wraps the RSA key in a JSON Web Key Set (JWKSet), making it immutable.
    • NimbusJwtEncoder(jwks): Uses the Nimbus library to create a JWT encoder that will sign tokens with the RSA private key.
  • JwtDecoder: This bean is responsible for decoding (verifying) JWT tokens.

    • NimbusJwtDecoder.withPublicKey(publicKey).build(): Creates a JWT decoder using the RSA public key, which is used to verify the signature of JWT tokens.

Entity

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);
    }
}

Repository

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);
}

Services

Client Service

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);
    }
}

Token Service

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;

    }
}

Controllers

Client Controller

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");
    }

}

Explanation

  • The /protectedRoute is a private route that can only be accessed with a JWT after logging in.

  • The token must be included in the headers as a Bearer token, for example.

  • You can use the token information later in your application, such as in the service layer.

  • @PreAuthorize: The @PreAuthorize annotation in Spring Security is used to perform authorization checks before a method is invoked. This annotation is typically applied at the method level in a Spring component (like a controller or a service) to restrict access based on the user's roles, permissions, or other security-related conditions.
    The annotation is used to define the condition that must be met for the method to be executed. If the condition evaluates to true, the method proceeds. If it evaluates to false, access is denied,

  • "hasAuthority('SCOPE_client')": It checks if the currently authenticated user or client has the specific authority SCOPE_client. If they do, the method protectedRoute() is executed. If they don't, access is denied.


Token Controller: Here, you can log in to the application, and if successful, it will return a 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));
    }

}

Reference

  • Spring Security
  • Spring Security-Toptal article
版本声明 本文转载于:https://dev.to/mspilari/spring-security-with-jwt-2bl6?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • MySQL 如何处理较短列中的长整数:溢出或截断?
    MySQL 如何处理较短列中的长整数:溢出或截断?
    较短列中的长整数转换:机制和公式将长整数插入较短整数列时,MySQL 通常会截断该值以适合指定的长度。但是,在某些情况下,行为可能会有所不同,从而导致意外的转换。考虑一个 10 位长整数列 some_number。如果将超过最大整数范围 (2147483647) 的值插入到此列中,MySQL 会将该...
    编程 发布于2024-11-08
  • 如何在教义 2 中创建带有额外字段的多对多链接表?
    如何在教义 2 中创建带有额外字段的多对多链接表?
    Doctrine 2 和带有额外字段的多对多链接表本文解决了在 Dotrine 2 中创建多对多关系的问题,其中链接表包含一个附加值,特别是在库存系统的上下文中。原则 2 中的多对多关系可以使用不包含任何附加字段的链接表来建立。但是,当每个链接都需要额外的值时,必须将链接表重新定义为新实体。提供的代...
    编程 发布于2024-11-08
  • JavaScript 中的单管道运算符如何处理浮点数和整数?
    JavaScript 中的单管道运算符如何处理浮点数和整数?
    探索 JavaScript 中单管道运算符的按位性质在 JavaScript 中,单管道运算符(“|”)执行按位运算称为按位或的运算。理解此操作对于理解其对不同输入值的影响至关重要,如以下示例所示:console.log(0.5 | 0); // 0 console.log(-1 | 0); //...
    编程 发布于2024-11-08
  • 列表理解和Regae
    列表理解和Regae
    啊。我一直害怕的那一刻。 第一篇文章,包含我自己的想法、观点和可能的知识细分。 请注意,亲爱的读者,这并不是对 Python 单行 for 循环、追加到列表和返回一些数据的能力的深入探讨或令人难以置信的分解。不,不。这只是展示了如何有趣——以及如何愚蠢——小东西可以组合在一起,让一...
    编程 发布于2024-11-08
  • 如何解决 WAMP 上由于缺少 Openssl 扩展而导致的 Composer 错误?
    如何解决 WAMP 上由于缺少 Openssl 扩展而导致的 Composer 错误?
    Composer 出现问题? WAMP 上缺少 Openssl 扩展尝试将 Composer 合并到 WAMP 设置中时,您可能会遇到警告:“The openssl 扩展丢失。”此消息表明,如果没有此扩展程序,您的系统的安全性和稳定性将会受到影响。故障排除步骤:您已经认真浏览了 WAMP 界面,标记...
    编程 发布于2024-11-08
  • 如何解决 Windows 上 PHP 中的 SSL 套接字传输问题?
    如何解决 Windows 上 PHP 中的 SSL 套接字传输问题?
    解决 PHP 中的 SSL Socket 传输问题在 Windows 系统上使用 PHP 时,开发人员可能会遇到错误“无法连接到 ssl: //...”由于启用“ssl”套接字传输存在困难。本文将指导您排除故障并解决此问题,并介绍您迄今为止已采取的具体步骤。故障排除步骤检查 PHP 配置:确保 ph...
    编程 发布于2024-11-08
  • 为什么模拟鼠标悬停在 Chrome 中不会触发 CSS 悬停?
    为什么模拟鼠标悬停在 Chrome 中不会触发 CSS 悬停?
    在 JavaScript 中模拟鼠标悬停:澄清差异并实现手动控制尝试在 Chrome 中模拟鼠标悬停事件时,您可能遇到了一个有趣的问题问题。尽管“mouseover”事件监听器已成功激活,但相应的CSS“hover”声明并未生效。此外,尝试在鼠标悬停侦听器中使用 classList.add(&quo...
    编程 发布于2024-11-08
  • 你能衡量 MySQL 索引的有效性吗?
    你能衡量 MySQL 索引的有效性吗?
    了解 MySQL 索引性能优化 MySQL 查询对于高效的数据库处理至关重要。索引是提高搜索性能的关键技术,但监控其有效性也同样重要。本文解决了是否可以评估 MySQL 索引性能的问题并提供了解决方案。识别查询性能确定查询是否使用索引,执行以下查询:EXPLAIN EXTENDED SELECT c...
    编程 发布于2024-11-08
  • 如何自定义 PDF.js
    如何自定义 PDF.js
    PDF.js 是一个很棒的开源项目,它经常更新并且不断添加新功能,但是从外观上看它很丑陋,或者可以说它看起来已经过时了。从 PDF.js 获取最新的 PDF 功能和修复,但在演示方面拥有流畅的外观怎么样? PdfJsKit 的 pdf 查看器并不引人注目,它不会直接更改 PDF.js 的代码,它只是...
    编程 发布于2024-11-08
  • 即将推出大事
    即将推出大事
    我决定从头开始构建全栈 Web 开发人员课程,从 HID 一直到服务器和可扩展性。所有需要知道的,都将免费涵盖免费! 以下是涵盖的内容: 互联网 互联网是如何运作的? 什么是HTTP? 浏览器及其工作原理? DNS 及其工作原理? 什么是域名? 什么是托管? 前端 H...
    编程 发布于2024-11-08
  • HTML 页面的剖析
    HTML 页面的剖析
    编程 发布于2024-11-08
  • 设计有效数据库的终极指南(说真的,我们是认真的)
    设计有效数据库的终极指南(说真的,我们是认真的)
    Alright, you’ve got a shiny new project. Maybe it's a cutting-edge mobile app or a massive e-commerce platform. Whatever it is, behind all that glitz ...
    编程 发布于2024-11-08
  • 使用 html css 和 javascript 的图像轮播旋转幻觉
    使用 html css 和 javascript 的图像轮播旋转幻觉
    代码 旋转图像轮播 身体 { 显示:柔性; 调整内容:居中; 对齐项目:居中; 高度:100vh; 保证金:0; 背景颜色:#0d0d0d; 溢出:隐藏; ...
    编程 发布于2024-11-08
  • 如何开始 Web 开发
    如何开始 Web 开发
    介绍 Web 开发是当今最受欢迎的职业之一,对于那些对 前端(用户看到的内容)和 后端(服务器逻辑)感兴趣的人来说)。如果您刚刚起步,想知道从哪里开始或者作为开发者可以赚多少钱,本指南将为您提供清晰的入门路径和资源。 什么是网页开发? 网络开发分为两大区域: 前端:...
    编程 发布于2024-11-08
  • 如何在不使用 Composer 本身的情况下安装 Composer PHP 包?
    如何在不使用 Composer 本身的情况下安装 Composer PHP 包?
    如何在没有 Composer 的情况下安装 Composer PHP 软件包在本文中,我们将解决在没有 Composer 工具的情况下安装 Composer PHP 软件包的挑战本身。当您遇到 Composer 对于您的工作流程不可用或不切实际的情况时,此方法非常有用。识别依赖关系第一步是识别包所需...
    编程 发布于2024-11-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3