Skip to content

Commit

Permalink
jwt implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
IN40068837 authored and IN40068837 committed Dec 14, 2024
1 parent 9fa9ba3 commit d4b26da
Show file tree
Hide file tree
Showing 12 changed files with 355 additions and 22 deletions.
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
logging.file.name=@env.HELPLINE104_API_LOGGING_FILE_NAME@
logging.file.name=@env.HELPLINE104_API_LOGGING_FILE_NAME@
jwt.secret=@env.JWT_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=
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=



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=
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();
}

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/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;
}

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

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

// 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

0 comments on commit d4b26da

Please sign in to comment.