-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
jwt api implementation #110
Open
indraniBan
wants to merge
7
commits into
develop
Choose a base branch
from
jwt-api
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
37b0893
jwt api implementation
70b904b
Formatting and dependency upgrade
13d90da
changes by coderabbit comments
9484afb
fixed issues
eb2f985
use fetch from redis concept
d57b1ca
user fetch concept modify
d04dd99
Merge branch 'develop' into jwt-api
indraniBan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -86,6 +86,7 @@ prescription=TMPrescription SMS | |
|
||
### Redis IP | ||
spring.redis.host=localhost | ||
jwt.secret=@JWT_SECRET_KEY@ | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -86,6 +86,7 @@ prescription=TMPrescription SMS | |
|
||
### Redis IP | ||
spring.redis.host=localhost | ||
jwt.secret=@JWT_SECRET_KEY@ | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -86,6 +86,7 @@ prescription=TMPrescription SMS | |
|
||
### Redis IP | ||
spring.redis.host=localhost | ||
jwt.secret=@JWT_SECRET_KEY@ | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -88,6 +88,7 @@ prescription=TMPrescription SMS | |
|
||
### Redis IP | ||
spring.redis.host=localhost | ||
jwt.secret=@JWT_SECRET_KEY@ | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -90,6 +90,7 @@ prescription=TMPrescription SMS | |
|
||
### Redis IP | ||
spring.redis.host=localhost | ||
jwt.secret=@JWT_SECRET_KEY@ | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -90,6 +90,7 @@ prescription=TMPrescription SMS | |
|
||
### Redis IP | ||
spring.redis.host=localhost | ||
jwt.secret=@JWT_SECRET_KEY@ | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package com.iemr.hwc.utils; | ||
|
||
import java.util.Arrays; | ||
import java.util.Optional; | ||
|
||
import org.springframework.stereotype.Service; | ||
|
||
import jakarta.servlet.http.Cookie; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
|
||
@Service | ||
public class CookieUtil { | ||
|
||
public Optional<String> getCookieValue(HttpServletRequest request, String cookieName) { | ||
Cookie[] cookies = request.getCookies(); | ||
if (cookies != null) { | ||
for (Cookie cookie : cookies) { | ||
if (cookieName.equals(cookie.getName())) { | ||
return Optional.of(cookie.getValue()); | ||
} | ||
} | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
public void addJwtTokenToCookie(String Jwttoken, HttpServletResponse response) { | ||
// Create a new cookie with the JWT token | ||
Cookie cookie = new Cookie("Jwttoken", Jwttoken); | ||
cookie.setHttpOnly(true); // Prevent JavaScript access for security | ||
cookie.setSecure(true); // Ensure the cookie is sent only over HTTPS | ||
cookie.setMaxAge(60 * 60 * 24); // 1 day expiration time | ||
cookie.setPath("/"); // Make the cookie available for the entire application | ||
response.addCookie(cookie); // Add the cookie to the response | ||
} | ||
|
||
public String getJwtTokenFromCookie(HttpServletRequest request) { | ||
return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName())) | ||
.map(Cookie::getValue).findFirst().orElse(null); | ||
} | ||
} |
91 changes: 91 additions & 0 deletions
91
src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
package com.iemr.hwc.utils; | ||
|
||
import java.util.Optional; | ||
|
||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.stereotype.Component; | ||
|
||
import com.iemr.hwc.data.login.Users; | ||
import com.iemr.hwc.repo.login.UserLoginRepo; | ||
import com.iemr.hwc.utils.exception.IEMRException; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
|
||
@Component | ||
public class JwtAuthenticationUtil { | ||
|
||
@Autowired | ||
private CookieUtil cookieUtil; | ||
@Autowired | ||
private JwtUtil jwtUtil; | ||
@Autowired | ||
private UserLoginRepo userLoginRepo; | ||
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); | ||
|
||
public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) { | ||
this.cookieUtil = cookieUtil; | ||
this.jwtUtil = jwtUtil; | ||
} | ||
|
||
public ResponseEntity<String> validateJwtToken(HttpServletRequest request) { | ||
Optional<String> jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken"); | ||
|
||
if (jwtTokenOpt.isEmpty()) { | ||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED) | ||
.body("Error 401: Unauthorized - JWT Token is not set!"); | ||
} | ||
|
||
String jwtToken = jwtTokenOpt.get(); | ||
|
||
// Validate the token | ||
Claims claims = jwtUtil.validateToken(jwtToken); | ||
if (claims == null) { | ||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error 401: Unauthorized - Invalid JWT Token!"); | ||
} | ||
|
||
// Extract username from token | ||
String usernameFromToken = claims.getSubject(); | ||
if (usernameFromToken == null || usernameFromToken.isEmpty()) { | ||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED) | ||
.body("Error 401: Unauthorized - Username is missing!"); | ||
} | ||
|
||
// Return the username if valid | ||
return ResponseEntity.ok(usernameFromToken); | ||
} | ||
|
||
public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException { | ||
try { | ||
// Validate JWT token and extract claims | ||
Claims claims = jwtUtil.validateToken(jwtToken); | ||
|
||
if (claims == null) { | ||
throw new IEMRException("Invalid JWT token."); | ||
} | ||
|
||
String userId = claims.get("userId", String.class); | ||
String tokenUsername = jwtUtil.extractUsername(jwtToken); | ||
|
||
// Fetch user based on userId from the database or cache | ||
Users user = userLoginRepo.getUserByUserID(Long.parseLong(userId)); | ||
if (user == null) { | ||
throw new IEMRException("Invalid User ID."); | ||
} | ||
|
||
// Check if the token's username matches the user retrieved by userId | ||
if (!user.getUserName().equalsIgnoreCase(tokenUsername)) { | ||
throw new IEMRException("JWT token and User ID mismatch."); | ||
} | ||
|
||
return true; // Valid userId and JWT token | ||
} catch (Exception e) { | ||
logger.error("Validation failed: " + e.getMessage(), e); | ||
throw new IEMRException("Validation error: " + e.getMessage(), e); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Security and maintainability improvements needed
Several improvements are recommended for the
validateJwtToken
method:Apply these changes: