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
在專案中使用 Swagger 可以增強 API 文件和測試。它為開發人員提供了一個用戶友好的介面,以探索您的 API、了解請求/回應結構並直接從文件測試端點。透過整合Swagger,您可以根據程式碼註釋自動產生API文檔,使前端和後端開發人員更輕鬆地高效協作。
首先我們註冊用戶
我們得到這樣的回應
之後我們登入使用者
我們得到這樣的回應
結論
該專案在 Spring Boot 應用程式中使用 JWT(JSON Web Tokens)實現基於角色的身份驗證。它具有安全的身份驗證機制,使用者可以註冊和登錄,接收根據分配的角色(例如 USER 或 ADMIN)授予存取權限的 JWT。 SecurityConfig 類別設定存取權限,確保每個人都可以存取公共端點,同時將敏感操作僅限於授權使用者。 JWTUtil 類別處理令牌建立、驗證和使用者提取。總體而言,此設定增強了安全性,實現了跨應用程式的無縫且強大的存取控制。
該專案採用了一個全面的安全框架,利用 Spring Security 進行使用者身份驗證和授權。 AuthController 方便用戶註冊和登錄,在身份驗證成功後產生 JWT。該應用程式使用 JWTFilter 攔截請求並驗證令牌,確保只有經過身份驗證的使用者才能存取受保護的資源。透過整合基於角色的存取控制,該專案提供了靈活且安全的使用者管理系統。這種設計不僅提高了安全性,還透過最大限度地減少重複登入的需要來增強使用者體驗。總的來說,它為建立可擴展且安全的微服務奠定了堅實的基礎。