Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
41 changes: 29 additions & 12 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@
</exclusion>
</exclusions>
</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 @@ -106,8 +106,7 @@
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!--
https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
Expand Down Expand Up @@ -240,8 +239,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 @@ -253,6 +251,26 @@
<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.11.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-impl -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-jackson -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- end newly added dependencies -->
</dependencies>

Expand All @@ -273,7 +291,7 @@
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>

<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
Expand Down Expand Up @@ -364,8 +382,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 Expand Up @@ -416,7 +433,7 @@
</execution>
</executions>
</plugin>


</plugins>
</build>
Expand Down
1 change: 1 addition & 0 deletions src/main/environment/admin_ci.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ videoConsultation-base-url=@env.SWYMED_BASE_URL@
### Redis IP
spring.redis.host=localhost
spring.main.allow-bean-definition-overriding=true
jwt.secret=<Enter_Your_Secret_Key>

1 change: 1 addition & 0 deletions src/main/environment/admin_dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ videoConsultation-base-url=https://psmri.swymed.com:92744
### Redis IP
spring.redis.host=localhost
spring.main.allow-bean-definition-overriding=true
jwt.secret=<Enter_Your_Secret_Key>

1 change: 1 addition & 0 deletions src/main/environment/admin_example.properties
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ videoConsultation-base-url=https://psmri.swymed.com:9274
### Redis IP
spring.redis.host=localhost
spring.main.allow-bean-definition-overriding=true
jwt.secret=<Enter_Your_Secret_Key>

1 change: 1 addition & 0 deletions src/main/environment/admin_test.properties
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ videoConsultation-base-url=https://psmri.swymed.com:9274
### Redis IP
spring.redis.host=localhost
spring.main.allow-bean-definition-overriding=true
jwt.secret=<Enter_Your_Secret_Key>

1 change: 1 addition & 0 deletions src/main/environment/admin_uat.properties
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ videoConsultation-base-url=https://psmri.swymed.com:9274
### Redis IP
spring.redis.host=localhost
spring.main.allow-bean-definition-overriding=true
jwt.secret=<Enter_Your_Secret_Key>

17 changes: 17 additions & 0 deletions src/main/java/com/iemr/admin/repository/user/UserLoginRepo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.iemr.admin.repository.user;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.iemr.admin.data.user.M_User;


@Repository
public interface UserLoginRepo extends CrudRepository<M_User, Long> {

@Query(" SELECT u FROM M_User u WHERE u.userID = :userID AND u.Deleted = false ")
public M_User getUserByUserID(@Param("userID") Long userID);

}
45 changes: 45 additions & 0 deletions src/main/java/com/iemr/admin/utils/CookieUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.iemr.admin.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);
}
}

19 changes: 19 additions & 0 deletions src/main/java/com/iemr/admin/utils/FilterConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.iemr.admin.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;
}

}
92 changes: 92 additions & 0 deletions src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.iemr.admin.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.admin.data.user.M_User;
import com.iemr.admin.repository.user.UserLoginRepo;
import com.iemr.admin.utils.exception.IEMRException;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;

@Component
public class JwtAuthenticationUtil {

@Autowired
private final CookieUtil cookieUtil;
@Autowired
private final 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
M_User 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