Tech Info

Backend
Backend

SpringBoot implements data encryption and desensitization (annotation + reflection + AOP)

Scenario: In response to government requirements, commercial software should ensure that users' basic information is not "leaked" and cannot "directly display" sensitive user information such as phone numbers, ID cards, addresses, etc. According to the above scenario description, we can analyze two points: "Not leaked" means that user information should be encrypted and stored. "Cannot directly display" means that user information should be desensitized when displayed. Solution Foolish programming: Encrypt the fields related to user information entities in the project, such as name, mobile phone number, ID number, address, etc., before adding them to the database; Decrypt and desensitize the data in the database when displaying the user information list, and then return it to the frontend. Aspect-oriented programming: Mark the fields related to user information entities in the project (here we use UserBO to indicate, add @EncryptField to the name, phone fields in UserBO) with annotations, return the user information entity class (here we use UserDO to indicate, add @DecryptField to the name, phone fields in UserDO); then use @EncryptField and @DecryptField as entry points to implement encryption and decryption desensitization in an aspect-oriented way. Foolish programming does not mean foolish, it is like aspect-oriented programming. Foolish programming requires encrypting and decrypting desensitization logic processing for all interfaces related to user information, where the changes are relatively large, high risk, repetitive operations on the same logic, high workload, and difficult to maintain later; Aspect-oriented programming only needs to add annotations to user information fields, and uniformly perform encryption and decryption desensitization logic processing on fields with annotations, which is…

2023-10-25 0comments 487hotness 0likes jimmychen Read all
Backend

Brings you to understand the usage of springboot3 + jwt + security

Preface Spring Security has become the first choice for permission verification in Java backends. Today I will take you through Security in depth by reading the code based on the open source project spring-boot-3-jwt-security. This article mainly explains Spring Security + JWT (Json Web Token) to implement user authentication and permission verification. All code is built on jdk17+. Let's get started! Technology Introduction Springboot 3.0 Spring Security Json Web Token (JWT) BCrypt Maven Project Construction The project uses postgresql database to store user information and Token (why not Redis? Leave this hole for now), you can replace it with mysql database as you like Accessing the database uses jpa, which is quite convenient for some simple sql that can be automatically mapped based on method names. It doesn't matter if you haven't used it before. It won't affect reading today's article, and can be replaced with mybatis-plus etc later according to your actual needs This article uses Lombok to generate fixed template code <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.alibou</groupId> <artifactId>security</artifactId> <version>0.0.1-SNAPSHOT</version> <name>security</name> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <!-- jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- spring security security framework --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- web dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- database --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.5</version> </dependency> <!-- doc remove this if not needed --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.1.0</version> </dependency>…

2023-10-07 0comments 1176hotness 0likes jimmychen Read all
Backend

WebSocket Authentication and Authorization in Spring

I. Things to Know The security chain and security configuration of HTTP and WebSocket are completely independent. SpringAuthenticationProvider is not involved in WebSocket authentication at all. In the examples given, authentication will not occur on the HTTP negotiation endpoint, because the JavaScript STOMP (websocket) libraries do not send the necessary authentication headers along with the HTTP request. Once set on the CONNECT request, the user (simpUser) will be stored in the websocket session, and subsequent messages will no longer need authentication. II. Dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-messaging</artifactId> </dependency> III. WebSocket Configuration 3.1, Simple Message Broker @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(final MessageBrokerRegistry config) { config.enableSimpleBroker("/queue/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(final StompEndpointRegistry registry) { registry.addEndpoint("stomp"); setAllowedOrigins("*") } } 3.2, Spring Security Configuration Since the Stomp protocol relies on the first HTTP request, authorization for the stomp handshake endpoint HTTP call is required. @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception http.httpBasic().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests().antMatchers("/stomp").permitAll() .anyRequest().denyAll(); } } Then create a service responsible for verifying user identity. @Component public class WebSocketAuthenticatorService { public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final String username, final String password) throws AuthenticationException { if (username == null || username.trim().isEmpty()) { throw new AuthenticationCredentialsNotFoundException("Username was null or empty."); } if (password == null || password.trim().isEmpty()) { throw new AuthenticationCredentialsNotFoundException("Password was null or empty."); } if (fetchUserFromDb(username, password) == null) { throw new BadCredentialsException("Bad credentials for user " + username); } return new UsernamePasswordAuthenticationToken( username, null, Collections.singleton((GrantedAuthority) () -> "USER")…

2023-10-06 0comments 520hotness 0likes jimmychen Read all
Backend

Use Cases of Spring Security

1. Background When doing the general permission system, I used spring-security to control the permission system, and now I will summarize the most basic usage 2. Demo usage 2.1 Some basic concepts Spring Security's security management has two important concepts, Authentication and Authorization Spring Security login authentication mainly involves two important interfaces: UserDetailService and UserDetails. The UserDetailService interface mainly defines a method loadUserByUsername(String username) to complete the query of user information. username is the login name when logging in. When logging in and authenticating, you need to customize an implementation class to implement the UserDetailService interface and complete the database query. This interface returns UserDetail. The loadUserByUsername user returns UserDetails. Our own User implements UserDetails UserDetail is mainly used to encapsulate user information after successful authentication, that is, the user information returned by UserDetailService can use Spring's own User object, but it is best to implement the UserDetail interface and customize the user object What is returned after successful authentication token The token is a string generated by the server as a token for the client to request. After the first login, the server generates a token and returns this token to the client. In the future, the client only needs to bring this token to request data without having to bring the username and password again Basic dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> 2.2 Spring Security authentication steps Customize the UserDetails class: When the entity object fields do not meet the requirements, you need to customize UserDetails, generally you need to customize UserDetails Customize the UserDetailsService class, mainly used to…

2023-10-02 0comments 393hotness 0likes jimmychen Read all
Backend

Design of an Intelligent Desk Lamp Based on STM32

1. Project Background Intelligent home devices play an increasingly important role in modern life. As one of them, intelligent desk lamps have functions like adjusting brightness and color temperature to better meet people's needs for customized lighting environments. This article introduces the design of an intelligent desk lamp based on the STM32 microcontroller, which can adjust brightness and color temperature to provide users with a more comfortable experience. 2. Design Goals [1] Implement adjustable brightness and color temperature functions. [2] Add human body sensing module for automatic on/off. [3] Enable remote control of the lamp with a mobile phone. [4] Design simple, stable hardware circuits and user-friendly interfaces. 3. System Architecture 3.1 Hardware (1) MCU: STM32 series with rich peripherals and powerful processing capabilities. (2) Power supply: stable voltage regulator. (3) Light source: high-brightness LEDs with diffuser for even and soft lighting. (4) Human body sensing: infrared sensor to detect human presence and turn on light. (5) Wireless communication: WiFi/Bluetooth module for remote control with mobile app. 3.2 Software (1) Embedded software: Keil MDK, embedded C language programs for functions like brightness/color temperature control, human sensing, etc. (2) Mobile app: remote control of desk lamp functions. 3.3 Hardware Selection [1] MCU: STM32F103RCT6 [2] Light source: (1) High-brightness LEDs (2) Transparent lamp cover for even lighting [3] Human body sensing: (1) High sensitivity infrared sensor (2) Photoresistor for low light activation [4] Wireless module: HC05 Bluetooth module for communication with mobile device. 3.4 Hardware Design [1] MCU: STM32F103RCT6 [2] Infrared sensor: human presence detection [3] Photoresistor: ambient light intensity [4] LED:…

2023-09-28 0comments 362hotness 0likes jimmychen Read all
Backend

Migrate the project from SpringCloud to K8S in 7 days

Before, the project used springcloud. The main components used were spring gateway, nacos, minio, load balancer, open-feign, etc. Then we deployed our microservices to virtual machines through docker. However, for security considerations, it needs to be migrated to Azure AKS (Kubernetes), so spring cloud needs to be reconstructed into spring boot. This way we don't need to maintain security policies for virtual machines ourselves, nor do we need to pay attention to patches. Combing project structure The project is organized into microservices. There are about 5 business services and 4 public services. The main reconstruction is concentrated in gateway and auth. The reconstruction of public packages is less, mainly changing open-feign access to call by url instead of by service name as before. In Kubernetes, we use Traefik2 to replace the gateway function. If you don't know Traefik2, you can check out my previous articles. At the same time, an authorization interface needs to be provided for authorization, used with Traefik2, so that each request will be authenticated. Start reconstruction Determine branch First of all, we definitely pull a new branch for these changes, even if it doesn't work well, it won't affect others. So let's call the branch name feature/AKS-migrate. Reconstruct gateway First, comment out unnecessary dependency packages in the pom file, such as spring cloud gateway, nacos, sentinel and other spring cloud related components. After commenting out, check what errors there are in the code and modify them accordingly. There are quite a few gateway filters and handlers used in our project. At first I thought that since…

2023-09-28 0comments 312hotness 0likes jimmychen Read all
Archives
  • October 2023
  • September 2023
Categories
  • Algorithm
  • Android
  • Backend
  • Embedded
  • Security
Ads

COPYRIGHT © 2023 Tech Info. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang