From 9d50750669b93604bed32c9375e94e07cda6eae8 Mon Sep 17 00:00:00 2001
From: letung999
Date: Thu, 2 Nov 2023 16:18:42 +0700
Subject: [PATCH 01/27] implement authentication and fix error security
---
pom.xml | 39 ++++++++++++-
.../config/security/CustomUserDetails.java | 12 ++--
.../security/JwtAuthenticationFilter.java | 23 +++++---
.../ppn/config/security/JwtTokenProvider.java | 18 +++---
.../ppn/config/security/SecurityConfig.java | 2 +-
.../ppn/ppn/controller/AuthController.java | 57 +++++++++++++++++++
src/main/java/com/ppn/ppn/entities/Car.java | 2 +
.../java/com/ppn/ppn/entities/Payment.java | 2 +
src/main/java/com/ppn/ppn/entities/Users.java | 4 ++
.../com/ppn/ppn/payload/LoginRequest.java | 15 +++++
.../com/ppn/ppn/payload/LoginResponse.java | 24 ++++++++
.../com/ppn/ppn/service/UsersServiceImpl.java | 16 ++++++
.../resources/application-prod.properties | 6 +-
src/main/resources/application.properties | 4 +-
src/main/resources/bootstrap.properties | 2 +-
15 files changed, 193 insertions(+), 33 deletions(-)
create mode 100644 src/main/java/com/ppn/ppn/controller/AuthController.java
create mode 100644 src/main/java/com/ppn/ppn/payload/LoginRequest.java
create mode 100644 src/main/java/com/ppn/ppn/payload/LoginResponse.java
diff --git a/pom.xml b/pom.xml
index 02a0387..7637209 100644
--- a/pom.xml
+++ b/pom.xml
@@ -21,6 +21,9 @@
2.2.6.RELEASE
6.0.2
0.11.2
+ 0.11.5
+ 0.11.5
+ 0.9.1
@@ -102,10 +105,42 @@
${spring-security-config.version}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
io.jsonwebtoken
- jjwt-api
- ${jjwt-api.version}
+ jjwt
+ ${jjwt.version}
+
+
+
+ com.sun.xml.bind
+ jaxb-core
+ 2.3.0.1
+
+
+ javax.xml.bind
+ jaxb-api
+ 2.3.1
diff --git a/src/main/java/com/ppn/ppn/config/security/CustomUserDetails.java b/src/main/java/com/ppn/ppn/config/security/CustomUserDetails.java
index ea9ca49..21f4501 100644
--- a/src/main/java/com/ppn/ppn/config/security/CustomUserDetails.java
+++ b/src/main/java/com/ppn/ppn/config/security/CustomUserDetails.java
@@ -32,31 +32,31 @@ public Collection extends GrantedAuthority> getAuthorities() {
@Override
public String getPassword() {
- return null;
+ return users.getPassword();
}
@Override
public String getUsername() {
- return null;
+ return users.getEmail();
}
@Override
public boolean isAccountNonExpired() {
- return false;
+ return true;
}
@Override
public boolean isAccountNonLocked() {
- return false;
+ return true;
}
@Override
public boolean isCredentialsNonExpired() {
- return false;
+ return true;
}
@Override
public boolean isEnabled() {
- return false;
+ return true;
}
}
diff --git a/src/main/java/com/ppn/ppn/config/security/JwtAuthenticationFilter.java b/src/main/java/com/ppn/ppn/config/security/JwtAuthenticationFilter.java
index c960f55..c29b2b2 100644
--- a/src/main/java/com/ppn/ppn/config/security/JwtAuthenticationFilter.java
+++ b/src/main/java/com/ppn/ppn/config/security/JwtAuthenticationFilter.java
@@ -28,18 +28,23 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
- if (!request.getRequestURI().contains("/login") && !request.getRequestURI().contains("/getByEmail")) {
- String jwt = getJwtFromRequest(request);
- if (StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)) {
- String userName = jwtTokenProvider.getUserNameFromJWT(jwt);
- UserDetails userDetails = customUserDetailsService.loadUserByUsername(userName);
- if (userDetails != null) {
- UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
- authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
- SecurityContextHolder.getContext().setAuthentication(authentication);
+ try {
+ if (!request.getRequestURI().contains("/login") && !request.getRequestURI().contains("/getByEmail")) {
+ String jwt = getJwtFromRequest(request);
+ if (StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)) {
+ String userName = jwtTokenProvider.getUserNameFromJWT(jwt);
+ UserDetails userDetails = customUserDetailsService.loadUserByUsername(userName);
+ if (userDetails != null) {
+ UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
+ authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+ }
}
}
+ } catch (Exception ex){
+ log.error("failed on set user authentication", ex);
}
+ filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
diff --git a/src/main/java/com/ppn/ppn/config/security/JwtTokenProvider.java b/src/main/java/com/ppn/ppn/config/security/JwtTokenProvider.java
index 6735071..098a922 100644
--- a/src/main/java/com/ppn/ppn/config/security/JwtTokenProvider.java
+++ b/src/main/java/com/ppn/ppn/config/security/JwtTokenProvider.java
@@ -17,15 +17,15 @@ public class JwtTokenProvider {
private String JWT_SECRET;
@Value("${ppn.app.jwt.expiration}")
- private String JWT_EXPIRATION;
+ private Long JWT_EXPIRATION;
- public String generateToken(CustomUserDetails userDetails) {
- Date currentDate = new Date();
- Date expiryDate = new Date(currentDate.getTime() + JWT_EXPIRATION);
+ public String generateToken(CustomUserDetails customUserDetails) {
+ Date now = new Date();
+ Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION);
return Jwts.builder()
- .setSubject(userDetails.getUsers().getEmail())
- .setIssuedAt(currentDate)
+ .setSubject(customUserDetails.getUsers().getEmail())
+ .setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, JWT_SECRET)
.compact();
@@ -33,9 +33,8 @@ public String generateToken(CustomUserDetails userDetails) {
public String getUserNameFromJWT(String token) {
- Claims claims = Jwts.parserBuilder()
+ Claims claims = Jwts.parser()
.setSigningKey(JWT_SECRET)
- .build()
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
@@ -43,9 +42,8 @@ public String getUserNameFromJWT(String token) {
public boolean validateToken(String authToken) {
try {
- Jwts.parserBuilder()
+ Jwts.parser()
.setSigningKey(JWT_SECRET)
- .build()
.parseClaimsJws(authToken);
return true;
} catch (MalformedJwtException ex) {
diff --git a/src/main/java/com/ppn/ppn/config/security/SecurityConfig.java b/src/main/java/com/ppn/ppn/config/security/SecurityConfig.java
index ea42ac8..7940803 100644
--- a/src/main/java/com/ppn/ppn/config/security/SecurityConfig.java
+++ b/src/main/java/com/ppn/ppn/config/security/SecurityConfig.java
@@ -43,7 +43,7 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests((authorize) ->
- authorize.requestMatchers(HttpMethod.GET, "/api/**").permitAll()
+ authorize.requestMatchers("/api/**").permitAll()
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/swagger-ui/**").permitAll()
.requestMatchers("/v3/api-docs/**").permitAll()
diff --git a/src/main/java/com/ppn/ppn/controller/AuthController.java b/src/main/java/com/ppn/ppn/controller/AuthController.java
new file mode 100644
index 0000000..38ce61c
--- /dev/null
+++ b/src/main/java/com/ppn/ppn/controller/AuthController.java
@@ -0,0 +1,57 @@
+package com.ppn.ppn.controller;
+
+import com.ppn.ppn.config.security.CustomUserDetails;
+import com.ppn.ppn.config.security.JwtTokenProvider;
+import com.ppn.ppn.entities.Users;
+import com.ppn.ppn.payload.LoginRequest;
+import com.ppn.ppn.payload.LoginResponse;
+import com.ppn.ppn.service.UsersServiceImpl;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/v1/auth")
+public class AuthController {
+ @Autowired
+ private UsersServiceImpl usersService;
+ @Autowired
+ private JwtTokenProvider jwtTokenProvider;
+ @Autowired
+ private AuthenticationManager authenticationManager;
+
+ @PostMapping({"/login"})
+ public ResponseEntity login(@RequestBody LoginRequest request) {
+ Users user = new Users();
+ user.setEmail(request.getEmail());
+ user.setPassword(request.getPassword());
+ Users userCheckLogin = usersService.checkLogin(user);
+ try {
+ if (userCheckLogin != null) {
+ Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
+ String jwt = jwtTokenProvider.generateToken((CustomUserDetails) authentication.getPrincipal());
+ Map response = new HashMap<>();
+ response.put("accessToken", jwt);
+ response.put("user", userCheckLogin);
+
+ LoginResponse
-
-
\ No newline at end of file
From efaee967a063d0104fcc6c98892847f8418a4d26 Mon Sep 17 00:00:00 2001
From: letung999
Date: Mon, 6 Nov 2023 22:04:01 +0700
Subject: [PATCH 13/27] create a general for response api and modify response
at controller
---
.../ppn/ppn/controller/AuthController.java | 39 +++++++++++++------
.../ppn/ppn/controller/RoleController.java | 16 +++++++-
.../ppn/ppn/controller/UserController.java | 24 ++++++++++--
.../java/com/ppn/ppn/payload/APIResponse.java | 27 +++++++++++++
.../com/ppn/ppn/payload/LoginResponse.java | 30 --------------
5 files changed, 89 insertions(+), 47 deletions(-)
create mode 100644 src/main/java/com/ppn/ppn/payload/APIResponse.java
delete mode 100644 src/main/java/com/ppn/ppn/payload/LoginResponse.java
diff --git a/src/main/java/com/ppn/ppn/controller/AuthController.java b/src/main/java/com/ppn/ppn/controller/AuthController.java
index d7fb7fd..2b96e5a 100644
--- a/src/main/java/com/ppn/ppn/controller/AuthController.java
+++ b/src/main/java/com/ppn/ppn/controller/AuthController.java
@@ -3,11 +3,10 @@
import com.ppn.ppn.config.security.CustomUserDetails;
import com.ppn.ppn.config.security.JwtTokenProvider;
import com.ppn.ppn.entities.Users;
+import com.ppn.ppn.payload.APIResponse;
import com.ppn.ppn.payload.LoginRequest;
-import com.ppn.ppn.payload.LoginResponse;
import com.ppn.ppn.service.UsersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -17,11 +16,11 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
+import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
-import static com.ppn.ppn.constant.MessageStatus.ERR_MSG_SOME_THING_WENT_WRONG;
-import static com.ppn.ppn.constant.MessageStatus.ERR_MSG_UNAUTHENTICATED_ACCESS;
+import static com.ppn.ppn.constant.MessageStatus.*;
@RestController
@RequestMapping("/api/v1/auth")
@@ -34,7 +33,7 @@ public class AuthController {
private AuthenticationManager authenticationManager;
@PostMapping({"/login"})
- public ResponseEntity login(@RequestBody LoginRequest request) {
+ public ResponseEntity> login(@RequestBody LoginRequest request) {
Users user = new Users();
user.setEmail(request.getEmail());
user.setPassword(request.getPassword());
@@ -46,15 +45,33 @@ public ResponseEntity login(@RequestBody LoginRequest request) {
Map response = new HashMap<>();
response.put("accessToken", jwt);
response.put("user", userCheckLogin);
-
- LoginResponse