Skip to content
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
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 33 additions & 21 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>co.elastic.logging</groupId>
<artifactId>logback-ecs-encoder</artifactId>
<version>1.3.2</version>
<dependency>
<groupId>co.elastic.logging</groupId>
<artifactId>logback-ecs-encoder</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down Expand Up @@ -125,8 +125,7 @@
<version>1.5.5.Final</version>
</dependency>

<!--
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down Expand Up @@ -197,14 +196,12 @@
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!--
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework.session/spring-session-data-redis -->
<!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session-data-redis -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
Expand All @@ -225,24 +222,21 @@
<version>7.0.0</version>
</dependency>

<!--
https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-structures-r4 -->
<!-- https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-structures-r4 -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-structures-r4</artifactId>
<version>7.0.0</version>
</dependency>

<!--
https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-server -->
<!-- https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-server -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-server</artifactId>
<version>7.0.0</version>
</dependency>

<!--
https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-validation -->
<!-- https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-validation -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-validation</artifactId>
Expand All @@ -255,8 +249,7 @@
</exclusions>
</dependency>

<!--
https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-validation-resources-r4 -->
<!-- https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-validation-resources-r4 -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-validation-resources-r4</artifactId>
Expand All @@ -273,11 +266,31 @@
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
</dependency>
<dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.1.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-impl -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-jackson -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
</dependencies>


Expand Down Expand Up @@ -370,8 +383,7 @@
${target-properties} and
${source-properties}
</echo>
<concat destfile="${target-properties}"
append="yes"
<concat destfile="${target-properties}" append="yes"
force="yes">
<fileset file="${source-properties}">
</fileset>
Expand Down
1 change: 1 addition & 0 deletions src/main/environment/common_ci.properties
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ prescription=TMPrescription SMS

### Redis IP
spring.redis.host=localhost
jwt.secret=@JWT_SECRET_KEY@



1 change: 1 addition & 0 deletions src/main/environment/common_dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ prescription=TMPrescription SMS

### Redis IP
spring.redis.host=localhost
jwt.secret=@JWT_SECRET_KEY@



1 change: 1 addition & 0 deletions src/main/environment/common_example.properties
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ prescription=TMPrescription SMS

### Redis IP
spring.redis.host=localhost
jwt.secret=@JWT_SECRET_KEY@



1 change: 1 addition & 0 deletions src/main/environment/common_prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ prescription=TMPrescription SMS

### Redis IP
spring.redis.host=localhost
jwt.secret=@JWT_SECRET_KEY@



1 change: 1 addition & 0 deletions src/main/environment/common_test.properties
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ prescription=TMPrescription SMS

### Redis IP
spring.redis.host=localhost
jwt.secret=@JWT_SECRET_KEY@



1 change: 1 addition & 0 deletions src/main/environment/common_uat.properties
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ prescription=TMPrescription SMS

### Redis IP
spring.redis.host=localhost
jwt.secret=@JWT_SECRET_KEY@



41 changes: 41 additions & 0 deletions src/main/java/com/iemr/hwc/utils/CookieUtil.java
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 src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java
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);
}
Comment on lines +39 to +64
Copy link

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:

  1. Move the cookie name to a constant
  2. Use generic error messages to avoid exposing internal details
  3. Add security event logging

Apply these changes:

+    private static final String JWT_COOKIE_NAME = "Jwttoken";
+
     public ResponseEntity<String> validateJwtToken(HttpServletRequest request) {
-        Optional<String> jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken");
+        Optional<String> jwtTokenOpt = cookieUtil.getCookieValue(request, JWT_COOKIE_NAME);
+        logger.debug("Validating JWT token from request");

         if (jwtTokenOpt.isEmpty()) {
+            logger.warn("JWT token not found in request");
             return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
-                    .body("Error 401: Unauthorized - JWT Token is not set!");
+                    .body("Authentication required");
         }

         String jwtToken = jwtTokenOpt.get();

         // Validate the token
         Claims claims = jwtUtil.validateToken(jwtToken);
         if (claims == null) {
+            logger.warn("Invalid JWT token detected");
             return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
-                    .body("Error 401: Unauthorized - Invalid JWT Token!");
+                    .body("Authentication failed");
         }

         // Extract username from token
         String usernameFromToken = claims.getSubject();
         if (usernameFromToken == null || usernameFromToken.isEmpty()) {
+            logger.warn("JWT token missing username claim");
             return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
-                    .body("Error 401: Unauthorized - Username is missing!");
+                    .body("Authentication failed");
         }

+        logger.debug("JWT token validation successful for user: {}", usernameFromToken);
         // Return the username if valid
         return ResponseEntity.ok(usernameFromToken);
     }

Committable suggestion skipped: line range outside the PR's diff.


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);
}
}
}
Loading
Loading