Securing Microservices with Spring Security: Implementing JWT
PHPz
Release: 2024-08-24 06:42:38
Original
386 people have browsed it
JSON WEB TOKEN (JWT)
JWT (JSON Web Token) is a method for securely transmitting information between two parties (such as a client and a server) as a JSON object. It's designed to be compact and URL-safe, making it easy to pass around in URLs, headers.
Header
Payload
Signature
Header The header typically consist two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.
{ "alg":"HS256", "typ":"JWT" }
Payload This is where the actual data is stored. It can include information like the user ID, roles, expiration time, and other claims (data about the user or session).
{ "email":"ayushstwt@gmail.com", "name":"Ayush" }
Signature Ensures the integrity of the token. This is a security feature that ensures the token hasn’t been altered. It’s created by combining the encoded header and payload with a secret key using the specified algorithm. The signature helps the server verify that the token is legitimate and hasn’t been tampered with.
The benefits of JWT
No Need to Repeatedly Send Credentials:With JWT, you don't have to send your username and password with every request. Instead, you log in once, and the server gives you a token. You then send this token with each request to prove your identity, making the process more secure and efficient.
Built-in Expiration:Each JWT comes with an expiration time, meaning it’s only valid for a specific period. This reduces the risk of long-term misuse if a token is somehow intercepted. After it expires, the user needs to log in again to get a new token, adding an extra layer of security.
JWT with Spring Boot securely manages user authentication by issuing tokens after login. These tokens are sent with each request, ensuring secure, stateless communication without repeatedly sending credentials.
Stateless communicationmeans the server doesn't remember past requests. Each request carries everything needed (like a JWT), so the server doesn't store session info.
Implementing JWT in a Java Spring Boot application involves several steps. Here's a simplified outline to get you started:
1. Add Dependencies
Include the necessary dependencies in your pom.xml file
All the dependencies that we need to create the spring-boot application with JWT
4.0.0org.springframework.bootspring-boot-starter-parent3.3.3com.tier3Hubuser-auth-service0.0.1-SNAPSHOTuser-auth-serviceThe user-auth-service is a microservice responsible for handling user authentication and authorization within a distributed system. It is designed to manage user login, registration, and secure access to various services using robust security practices. This service implements authentication mechanisms like JSON Web Tokens (JWT) and integrates with OAuth 2.0 for third-party authentication. Built with Spring Boot, it ensures scalability, reliability, and easy integration with other microservices in the system.21org.springframework.bootspring-boot-starter-actuatororg.springframework.bootspring-boot-starter-data-jpaorg.springframework.bootspring-boot-starter-securityorg.springframework.bootspring-boot-starter-webio.jsonwebtokenjjwt-api0.12.5io.jsonwebtokenjjwt-impl0.12.5runtimeio.jsonwebtokenjjwt-jackson0.12.5runtimecom.mysqlmysql-connector-jruntimeorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestorg.springframework.securityspring-security-testtestorg.springframework.bootspring-boot-starter-validationorg.springdocspringdoc-openapi-starter-webmvc-ui2.5.0org.modelmappermodelmapper3.1.1org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok
Copy after login
we are using different types of dependencies like
Spring Boot Starter Actuator: 3.3.3 - Adds production-ready features like monitoring and health checks.
Spring Boot Starter Data JPA: 3.3.3 - Simplifies database interactions with JPA support.
Spring Boot Starter Security: 3.3.3 - Provides security features like authentication and authorization.
Spring Boot Starter Web: 3.3.3 - Supports building web applications, including RESTful services.
JJWT API: 0.12.5 - Handles JWT creation and parsing for secure token management.
package com.tier3Hub.user_auth_service.dto; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Data public class RegisterDTO { @NotBlank(message = "Username is required") @Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters") private String username; @NotBlank(message = "Password is required") @Size(min = 8, message = "Password must be at least 8 characters") private String password; @NotBlank(message = "Email is required") @Email(message = "Email should be valid") private String email; }
*7. for sending custom response from the API we use the ResponseHandler.java *
package com.tier3Hub.user_auth_service.utils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.HashMap; import java.util.Map; public class ResponseHandler { public static ResponseEntity
Copy after login
8. for storing some constants we create the class inside the utils package that is ApplicationConstants.java
package com.tier3Hub.user_auth_service.utils; public class AppConstants { public static final String[] PUBLIC_URLS = { "/v3/api-docs/**", "/swagger-ui/**", "/api/auth/register/**", "/api/auth/login/**","/api/auth/registerAdmin/**" }; }
Copy after login
9. for converting the object one to another we use the dependency that is model mapper for configuration that we create the class inside the config package that is ApplicationConfigs.java
package com.tier3Hub.user_auth_service.config; import org.modelmapper.ModelMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationConfigs { @Bean public ModelMapper modelMapper() { return new ModelMapper(); } }
Copy after login
** This is the basic setup that we do for every spring-boot application we create now securing the rest endpoint with JWT we started. **
now inside the security package we create the class called JWTFilter.java
The JWTFilter is a custom Spring Security filter that intercepts HTTP requests to validate JWTs. It checks for the "Authorization" header, extracts the token, and retrieves the username. If the token is valid, it creates an authentication token with user details and sets it in the security context, allowing the application to recognize the authenticated user for further processing.
The JWTUtil class manages JWT operations, including extracting usernames and expiration dates from tokens. It generates new tokens using a secret key and validates existing tokens by checking their expiration. The class uses HMAC for signing and includes methods to parse claims and determine if tokens are expired, ensuring secure authentication and authorization in the application.
*configure the Spring security and add some modifictaion we create the class SecurityConfig.java *
The SecurityConfig class sets up security for the application using Spring Security. It defines access rules, allowing public endpoints while restricting others based on user roles. The class incorporates a JWT filter to validate tokens and uses BCrypt for password encoding. It also configures an authentication manager with a custom user details service for secure user authentication.
The securityFilterChain method configures access rules for different API endpoints in the Spring application. It permits public URLs and applies role-based access control for user and admin roles. Role-based authentication restricts resource access based on user roles (e.g., USER, ADMIN). In Spring Boot, you define roles and configure security settings in the SecurityConfig class to specify access permissions. During user registration, assign roles, and use annotations like @PreAuthorize to enforce role checks in controllers. This approach enhances security, allows easy permission management, and simplifies user access rights as the application scales. Implementing role-based auth provides flexibility and maintainability for your user management system. CSRF protection is disabled, and a custom JWT filter is added to authenticate requests based on JSON Web Tokens, ensuring secure and controlled access to resources.
configureGlobal method handle configures global authentication settings in a Spring application. It uses a custom user details service for loading user data and a BCrypt password encoder for secure password hashing. Additionally, it provides an AuthenticationManager bean for handling authentication processes, ensuring a secure and efficient user authentication system that leverages strong password management practices.
This login method in the AuthController handles user login requests. It takes a LoginDTO containing the username and password, validates them, and attempts authentication using the AuthenticationManager. Upon successful authentication, it retrieves user details and generates a JWT token using the JWTUtil class. The token is then included in a LoginResponse object and returned with a success message. If authentication fails, it catches the exception and returns a "Incorrect username or password" response with a 400 status code.
generateToken(String username):This method creates an empty claims map and calls the createToken method with the username as the subject. It serves as the entry point for token generation.
c*reateToken(Map claims, String subject):* This method builds the JWT using the Jwts.builder(). It sets the claims, subject, and token metadata, such as issue date and expiration time (set to 5 minutes). The token is then signed with a secret key and compacted into a string format for transmission.
Testing
now we run the application
and hit the URL here our application is runing on 8000 port
http://localhost:8000/swagger-ui/index.html
Using Swagger in your project enhances API documentation and testing. It provides a user-friendly interface for developers to explore your APIs, understand request/response structures, and test endpoints directly from the documentation. By integrating Swagger, you enable automatic generation of API docs based on your code annotations, making it easier for both front-end and back-end developers to collaborate efficiently.
first we register the user
we get the response like this
after that we login the user
we get the response like this
Conclusion
The project implements role-based authentication using JWT (JSON Web Tokens) in a Spring Boot application. It features a secure authentication mechanism where users can register and log in, receiving a JWT that grants access based on their assigned roles (like USER or ADMIN). The SecurityConfig class configures access permissions, ensuring that public endpoints are accessible to everyone while restricting sensitive operations to authorized users only. The JWTUtil class handles token creation, validation, and user extraction. Overall, this setup enhances security, enabling seamless and robust access control across the application.
The project employs a comprehensive security framework that leverages Spring Security for user authentication and authorization. The AuthController facilitates user registration and login, generating a JWT upon successful authentication. The application uses a JWTFilter to intercept requests and validate tokens, ensuring that only authenticated users can access protected resources. By integrating role-based access control, the project provides a flexible and secure user management system. This design not only improves security but also enhances user experience by minimizing the need for repeated logins. Overall, it lays a solid foundation for building scalable and secure microservices.
You can explore the complete source code for the User Authentication Service on my GitHub repository. This project showcases various features such as user registration, login, and secure access using JWT for authentication. Feel free to check it out, contribute, or use it as a reference for your own projects!
For those interested in diving deeper into JSON Web Tokens (JWT), I recommend visiting jwt.io. This resource provides comprehensive information about JWT, including how it works, its structure, and practical examples. It's an excellent starting point for understanding token-based authentication and authorization, which are essential for modern web applications. Whether you're a beginner or looking to refresh your knowledge, jwt.io offers valuable insights into securely managing user sessions.
The above is the detailed content of Securing Microservices with Spring Security: Implementing JWT. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn