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 implementation #35

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
52 changes: 35 additions & 17 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,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 @@ -115,8 +115,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 @@ -146,15 +145,15 @@
<artifactId>poi-ooxml</artifactId>
<version>5.3.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/jakarta.ws.rs/jakarta.ws.rs-api -->
<dependency>
<groupId>jakarta.ws.rs</groupId>
<artifactId>jakarta.ws.rs-api</artifactId>
<version>3.1.0</version>
</dependency>


<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
Expand Down Expand Up @@ -192,14 +191,13 @@
<groupId>org.springframework.boot</groupId>
<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 @@ -219,8 +217,7 @@
<artifactId>jackson-datatype-joda</artifactId>
<version>2.17.0</version>
</dependency>
<!--
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
Expand All @@ -232,9 +229,30 @@
<artifactId>jackson-core</artifactId>
<version>2.17.0-rc1</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>

<build>
<finalName>104api-v3.0.0</finalName>
<plugins>
Expand Down Expand Up @@ -318,8 +336,8 @@
<echo>concatenating properties file
${target-properties} and
${source-properties}</echo>
<concat destfile="${target-properties}"
append="yes" force="yes">
<concat destfile="${target-properties}" append="yes"
force="yes">
<fileset file="${source-properties}" />
</concat>
</target>
Expand Down
3 changes: 2 additions & 1 deletion src/main/environment/104_ci.properties
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ [email protected]_API_BASE_URL@
spring.redis.host=localhost

#ELK logging file name
[email protected]_API_LOGGING_FILE_NAME@
[email protected]_API_LOGGING_FILE_NAME@
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved
[email protected]_SECRET_KEY@
2 changes: 1 addition & 1 deletion src/main/environment/104_dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ common-url=<Enter your socket address here>/commonapi-v1.0

### Redis IP
spring.redis.host=localhost

jwt.secret=
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion src/main/environment/104_example.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ common-url=http://localhost:8080/commonapi-v1.0

### Redis IP
spring.redis.host=localhost

jwt.secret=
2 changes: 1 addition & 1 deletion src/main/environment/104_test.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ common-url=<Enter your socket address here>/commonapi-v1.0

### Redis IP
spring.redis.host=localhost

jwt.secret=
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Critical: Configure secure JWT secret for test environment

The empty JWT secret configuration poses security risks even in the test environment:

  1. Test environments should mirror production security practices
  2. Empty secrets could lead to false security assumptions during testing

Recommendations:

  1. Use environment variables similar to CI configuration:
-jwt.secret=
+jwt.secret=${JWT_SECRET_KEY:#{throw new RuntimeException("JWT secret key is required")}}
  1. Consider using a secure secret generator utility for test environments
  2. Document the JWT configuration requirements in testing guides
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
jwt.secret=
jwt.secret=${JWT_SECRET_KEY:#{throw new RuntimeException("JWT secret key is required")}}




Expand Down
2 changes: 1 addition & 1 deletion src/main/environment/104_uat.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ common-url=<Enter your socket address here>/commonapi-v1.0

### Redis IP
spring.redis.host=localhost

jwt.secret=
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ public interface IEMRUserRepositoryCustom extends CrudRepository<M_User, Long> {
@Query("UPDATE M_User u set u.StatusID = 2 where u.UserID = :userId")
int updateSetUserStatusActive(@Param("userId") Long userId);

M_User findByUserID(Long UserID);

}
31 changes: 31 additions & 0 deletions src/main/java/com/iemr/helpline104/utils/CookieUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.iemr.helpline104.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();
}
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved

public String getJwtTokenFromCookie(HttpServletRequest request) {
return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName()))
.map(Cookie::getValue).findFirst().orElse(null);
}
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved
}
19 changes: 19 additions & 0 deletions src/main/java/com/iemr/helpline104/utils/FilterConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.iemr.helpline104.utils;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FilterConfig {

@Bean
public FilterRegistrationBean<JwtUserIdValidationFilter> jwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) {
FilterRegistrationBean<JwtUserIdValidationFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil));
registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints
return registrationBean;
}
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.iemr.helpline104.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.helpline104.data.users.M_User;
import com.iemr.helpline104.repository.users.IEMRUserRepositoryCustom;
import com.iemr.helpline104.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 IEMRUserRepositoryCustom iEMRUserRepositoryCustom;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) {
this.cookieUtil = cookieUtil;
this.jwtUtil = jwtUtil;
}
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved

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);
}
sandipkarmakar3 marked this conversation as resolved.
Show resolved Hide resolved

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

// Fetch user based on userId from the database or cache
M_User user = iEMRUserRepositoryCustom.findByUserID(Long.parseLong(userId));
if (user == null) {
throw new IEMRException("Invalid User ID.");
}

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