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).
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 communication means 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
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
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/**" };
}
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();
}
}
**
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.
릴리스 선언문
이 기사는 https://dev.to/ayushstwt/securing-microservices-with-spring-security-implementing-jwt-38m6?1에서 복제됩니다. 침해가 있는 경우, [email protected]에 연락하여 삭제하시기 바랍니다.
PHP에서 연관 배열 결합PHP에서는 두 개의 연관 배열을 단일 배열로 결합하는 것이 일반적인 작업입니다. 다음 요청을 고려하십시오.문제 설명:제공된 코드는 두 개의 연관 배열 $array1 및 $array2를 정의합니다. 목표는 두 배열의 모든 키-값 쌍을 통합하는 ...
C ifstream을 사용하여 텍스트 파일에서 정수 읽기텍스트 파일에서 그래프 인접 정보를 벡터로 검색하고 저장하는 것이 어려운 경우 가변 정수 개수의 라인을 처리합니다. 다음은 C의 ifstream을 사용하는 포괄적인 솔루션입니다.기존 접근 방식에서는 getline(...
Bootstrap 4 베타: 열 오프셋 제거 및 복원Bootstrap 4는 베타 1 릴리스에서 열 오프셋 방식에 중요한 변경 사항을 도입했습니다. 열이 오프셋되었습니다. 그러나 후속 베타 2 릴리스에서는 이러한 변경 사항이 취소되었습니다.offset-md-*에서 ml-...
MySQL이 잘못 구성됨: 상대 경로 문제Django에서 python prepare.py runserver를 실행할 때 다음 오류가 발생할 수 있습니다:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Libra...
MySQL을 사용하여 오늘 생일이 있는 사용자를 식별하는 방법MySQL을 사용하여 오늘이 사용자의 생일인지 확인하려면 생일이 일치하는 모든 행을 찾는 것이 필요합니다. 오늘 날짜. 이는 UNIX 타임스탬프로 저장된 생일을 오늘 날짜와 비교하는 간단한 MySQL 쿼리를 ...
Windows에서 기능하지 않는 고루틴의 수수께끼 이해동시성 영역에서 고루틴은 Go에서 경량 스레드 역할을 합니다. 그러나 일부 프로그래머는 Windows에서 고루틴이 실행되지 않는 예상치 못한 문제에 직면했습니다. 이 수수께끼를 풀기 위해 근본적인 문제를 파헤쳐 보겠...
PHP에서 효율적인 MySQL 파일 가져오기: 공유 호스팅을 위한 쿼리 분할웹 개발 영역에서 공유 호스팅 제공업체를 공통적으로 사용하면서 대용량 데이터베이스 파일을 가져와야 하는 필요성 발생합니다. 안타깝게도 명령줄을 통한 MySQL 액세스는 제한될 수 있으므로 쿼리 ...
CSS를 사용하여 이미지 크기를 특정 비율로 조정웹 디자인 영역에서는 이미지 크기를 특정 크기로 조정해야 함 자주 발생합니다. 한 가지 시나리오에는 컨테이너 요소의 크기를 변경하지 않고 이미지 크기를 원래 크기의 백분율로 줄이는 것이 포함됩니다. JavaScript 또...
JavaScript 상속: Object.create와 newJavaScript의 상속 개념은 혼란스러울 수 있습니다. 그것. 이 문서의 목적은 가장 널리 사용되는 방법을 명확히 하고 특정 시나리오에 대한 솔루션을 제공하는 것입니다.Object.create 및 new 이...
부트스트랩 그리드 클래스의 숫자 이해: col-md-4, col-xs-1, col-lg-2The 부트스트랩 프레임워크는 반응형 레이아웃 생성을 용이하게 하는 강력한 그리드 시스템을 도입합니다. 이 시스템에 필수적인 것은 col-* 형식의 클래스입니다. 여기서 별표는 숫...
C에서 IEEE 754 부동 소수점 표준 확인 C 컴파일러가 IEEE 754 부동 소수점 표준을 준수하는지 확인하는 작업은 일반적으로 다음을 통해 수행됩니다. 컴파일러가 정의합니다. 그러나 C에 사용된 기술은 C에 직접 적용되지 않을 수 있습니다.C - 특정 접근 방식...
SHA-256을 사용하는 Java 해시 문자열Java에서 SHA-256을 사용하여 문자열을 해싱하는 것은 간단한 작업처럼 보일 수 있지만 해싱과 인코딩 사이의 중요한 차이점은 설명이 필요합니다.SHA-256(Secure Hash Algorithm-256)은 인코딩 메커...
HTML5 테이블 속성: 지원 중단 및 CSS 대체HTML 테이블 스타일을 지정하는 데 일반적으로 사용된 여러 속성(셀 패딩 포함)이 HTML5에서 더 이상 사용되지 않습니다. , 셀 간격, valign 및 정렬. 이 변경은 웹 개발을 현대화하고 HTML5 표준에 대한...
생성 AI가 우리 세상을 부풀린 텍스트로 채우기 전에 인간은 문법적으로 무관심하고 간결한 메모에 의존하여 다른 사람과 자신이 소프트웨어 개발의 광대한 바다를 탐색할 수 있도록 도왔습니다. 몇 년 전에 발굴된 메모에서 가져온 Ember에 대해 제가 중요하다고 생각한 내용...
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오.
최대한 빨리 처리해 드리겠습니다.