Skip to content

Conversation

ravishanigarapu
Copy link
Member

@ravishanigarapu ravishanigarapu commented Aug 6, 2025

📋 Description

JIRA ID: AMM-1187

Added Jwttoken in Header while calling Identity-API.
Previously we don't have any token validation in Identity so we have implemented Jwttoken session management in Identity-API


✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features

    • Improved handling of JWT tokens in HTTP requests, ensuring tokens are consistently added to request headers or cookies as needed.
  • Refactor

    • Streamlined and modularized the logic for extracting and adding JWT tokens to HTTP headers.
    • Unified header construction for outgoing HTTP requests.
  • Chores

    • Removed redundant code and unnecessary comments for cleaner and more maintainable code.

Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes refactor JWT token extraction and HTTP header construction in RestTemplateUtil, introducing helper methods for modularity. A new utility method enables populating JWT-related headers in HttpHeaders. HttpUtils is updated to invoke this method before HTTP requests, ensuring consistent JWT handling. Minor code cleanup is also performed.

Changes

Cohort / File(s) Change Summary
JWT Header Utilities Refactor
src/main/java/com/iemr/common/utils/RestTemplateUtil.java
Refactored JWT extraction into extractJwttoken; added getJwttokenFromHeaders for populating JWT headers; improved and unified header construction logic.
HTTP Utils Integration
src/main/java/com/iemr/common/utils/http/HttpUtils.java
Integrated RestTemplateUtil.getJwttokenFromHeaders into HTTP request methods; removed redundant/commented code.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HttpUtils
    participant RestTemplateUtil
    participant CookieUtil
    participant UserAgentContext

    Client->>HttpUtils: Initiate HTTP request
    HttpUtils->>RestTemplateUtil: getJwttokenFromHeaders(headers)
    RestTemplateUtil->>CookieUtil: getJwtTokenFromCookie(request)
    RestTemplateUtil->>UserAgentContext: getUserAgent() (if needed)
    RestTemplateUtil-->>HttpUtils: Headers updated with JWT and User-Agent
    HttpUtils->>Client: Proceed with HTTP request using updated headers
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Poem

In fields of code where headers grow,
A rabbit hops where JWTs flow.
With helpers new and logic neat,
Each token finds its rightful seat.
Now HTTP requests, with headers bright,
Leap forward sure—secure and right!
🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ravishanigarapu
Copy link
Member Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/main/java/com/iemr/common/utils/http/HttpUtils.java (2)

78-78: Same header duplication issue as in get() method.

The same header duplication issue exists here with the instance-level headers field.


105-105: Same header duplication issue as in get() methods.

The same header duplication issue exists here with the instance-level headers field.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b2aecd8 and aa6a558.

📒 Files selected for processing (2)
  • src/main/java/com/iemr/common/utils/RestTemplateUtil.java (1 hunks)
  • src/main/java/com/iemr/common/utils/http/HttpUtils.java (5 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: vishwab1
PR: PSMRI/Common-API#214
File: src/main/java/com/iemr/common/service/recaptcha/CaptchaValidationService.java:28-31
Timestamp: 2025-06-10T10:21:53.819Z
Learning: The user vishwab1 expects CAPTCHA tokens to be optionally sent in request bodies during implementation, suggesting a gradual rollout approach where clients may or may not include CAPTCHA tokens initially.
Learnt from: vishwab1
PR: PSMRI/Common-API#214
File: src/main/java/com/iemr/common/service/recaptcha/CaptchaValidationService.java:28-31
Timestamp: 2025-06-10T10:53:24.380Z
Learning: The user vishwab1 confirmed that their CAPTCHA implementation handles null token checking at the controller level before calling the service, which mitigates the direct security vulnerability of the service returning true for null tokens.
Learnt from: sandipkarmakar3
PR: PSMRI/Common-API#162
File: src/main/java/com/iemr/common/utils/CookieUtil.java:52-66
Timestamp: 2025-02-21T07:43:03.828Z
Learning: In the Common-API project's CookieUtil class, the current implementation of addJwtTokenToCookie using both response.addCookie() and manual Set-Cookie header has been tested and confirmed to work as required for their use case. URL encoding of the JWT token is not necessary.
Learnt from: sandipkarmakar3
PR: PSMRI/Common-API#162
File: src/main/java/com/iemr/common/utils/CookieUtil.java:40-47
Timestamp: 2025-02-21T07:42:36.497Z
Learning: In the Common-API project's CookieUtil class, JWT cookies are configured with SameSite=None to support cross-origin requests, which is required for the project's CORS functionality.
Learnt from: indraniBan
PR: PSMRI/Common-API#138
File: src/main/java/com/iemr/common/utils/JwtAuthenticationUtil.java:0-0
Timestamp: 2025-02-03T12:42:38.278Z
Learning: In the JwtAuthenticationUtil class, catching a generic Exception in the validateUserIdAndJwtToken method is acceptable as per the team's preference.
Learnt from: indraniBan
PR: PSMRI/Common-API#138
File: src/main/environment/common_uat.properties:0-0
Timestamp: 2025-02-03T12:41:59.244Z
Learning: In the Common-API project, JWT secret configuration should use environment variables (e.g., `jwt.secret=env.JWT_SECRET_KEY@`) across all environments for better security.
📚 Learning: in the common-api project's cookieutil class, the current implementation of addjwttokentocookie usin...
Learnt from: sandipkarmakar3
PR: PSMRI/Common-API#162
File: src/main/java/com/iemr/common/utils/CookieUtil.java:52-66
Timestamp: 2025-02-21T07:43:03.828Z
Learning: In the Common-API project's CookieUtil class, the current implementation of addJwtTokenToCookie using both response.addCookie() and manual Set-Cookie header has been tested and confirmed to work as required for their use case. URL encoding of the JWT token is not necessary.

Applied to files:

  • src/main/java/com/iemr/common/utils/RestTemplateUtil.java
  • src/main/java/com/iemr/common/utils/http/HttpUtils.java
📚 Learning: in the common-api project's cookieutil class, jwt cookies are configured with samesite=none to suppo...
Learnt from: sandipkarmakar3
PR: PSMRI/Common-API#162
File: src/main/java/com/iemr/common/utils/CookieUtil.java:40-47
Timestamp: 2025-02-21T07:42:36.497Z
Learning: In the Common-API project's CookieUtil class, JWT cookies are configured with SameSite=None to support cross-origin requests, which is required for the project's CORS functionality.

Applied to files:

  • src/main/java/com/iemr/common/utils/RestTemplateUtil.java
  • src/main/java/com/iemr/common/utils/http/HttpUtils.java
📚 Learning: in this codebase, for java spring boot api controllers like `abdmfacilitycontroller.java`, it's a co...
Learnt from: helenKaryamsetty
PR: PSMRI/Common-API#123
File: src/main/java/com/iemr/common/controller/abdmfacility/AbdmFacilityController.java:31-31
Timestamp: 2024-12-07T19:32:42.660Z
Learning: In this codebase, for Java Spring Boot API controllers like `AbdmFacilityController.java`, it's a common pattern to include the `Authorization` parameter in method signatures, even if it's not used in the implementation, to maintain consistency across APIs.

Applied to files:

  • src/main/java/com/iemr/common/utils/RestTemplateUtil.java
  • src/main/java/com/iemr/common/utils/http/HttpUtils.java
📚 Learning: in the common-api project, jwt secret configuration should use environment variables (e.g., `jwt.sec...
Learnt from: indraniBan
PR: PSMRI/Common-API#138
File: src/main/environment/common_uat.properties:0-0
Timestamp: 2025-02-03T12:41:59.244Z
Learning: In the Common-API project, JWT secret configuration should use environment variables (e.g., `jwt.secret=env.JWT_SECRET_KEY@`) across all environments for better security.

Applied to files:

  • src/main/java/com/iemr/common/utils/RestTemplateUtil.java
📚 Learning: in the jwtauthenticationutil class, catching a generic exception in the validateuseridandjwttoken me...
Learnt from: indraniBan
PR: PSMRI/Common-API#138
File: src/main/java/com/iemr/common/utils/JwtAuthenticationUtil.java:0-0
Timestamp: 2025-02-03T12:42:38.278Z
Learning: In the JwtAuthenticationUtil class, catching a generic Exception in the validateUserIdAndJwtToken method is acceptable as per the team's preference.

Applied to files:

  • src/main/java/com/iemr/common/utils/RestTemplateUtil.java
🧬 Code Graph Analysis (1)
src/main/java/com/iemr/common/utils/http/HttpUtils.java (1)
src/main/java/com/iemr/common/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (17-81)
🔇 Additional comments (6)
src/main/java/com/iemr/common/utils/RestTemplateUtil.java (3)

13-13: LGTM! Import added for Constants usage.

The import for Constants is correctly added to support the JWT token header references used throughout the class.


50-59: LGTM! JWT token extraction properly modularized.

The extraction of JWT token logic into a separate method improves code reusability and maintainability. Error handling with logging is appropriate.


20-48: No inconsistency in JWT token header formats
Constants.JWT_TOKEN is defined as "Jwttoken", so both

"Jwttoken=" + jwtTokenFromCookie

and

Constants.JWT_TOKEN + "=" + jwtTokenFromCookie

produce identical header names. You can safely ignore this concern. (Optionally, for consistency, replace the hardcoded "Jwttoken" on line 44 with Constants.JWT_TOKEN.)

Likely an incorrect or invalid review comment.

src/main/java/com/iemr/common/utils/http/HttpUtils.java (3)

43-43: LGTM! Import correctly added for RestTemplateUtil usage.

The import statement is properly added to support the new JWT token handling functionality.


95-95: LGTM! JWT token integration properly implemented.

The JWT token handling is correctly integrated using a local HttpHeaders object, avoiding the duplication issue present in other methods.


119-119: LGTM! JWT token integration properly implemented.

Similar to the get() method with headers parameter, this correctly uses a local HttpHeaders object to avoid duplication issues.


public String get(String uri) {
String body;
RestTemplateUtil.getJwttokenFromHeaders(headers);
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

Potential header duplication in instance-level headers.

The getJwttokenFromHeaders(headers) call on Line 68 uses the instance-level headers field that already contains "Content-Type: application/json" (set in constructor). This will cause duplication since getJwttokenFromHeaders also adds Content-Type header.

 public String get(String uri) {
 	String body;
+	HttpHeaders requestHeaders = new HttpHeaders();
+	requestHeaders.add("Content-Type", "application/json");
-	RestTemplateUtil.getJwttokenFromHeaders(headers);
-	HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
+	RestTemplateUtil.getJwttokenFromHeaders(requestHeaders);
+	HttpEntity<String> requestEntity = new HttpEntity<String>("", requestHeaders);
 	ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.GET, requestEntity, String.class);
📝 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
RestTemplateUtil.getJwttokenFromHeaders(headers);
public String get(String uri) {
String body;
+ HttpHeaders requestHeaders = new HttpHeaders();
+ requestHeaders.add("Content-Type", "application/json");
- RestTemplateUtil.getJwttokenFromHeaders(headers);
- HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
+ RestTemplateUtil.getJwttokenFromHeaders(requestHeaders);
+ HttpEntity<String> requestEntity = new HttpEntity<String>("", requestHeaders);
ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.GET, requestEntity, String.class);
🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/utils/http/HttpUtils.java at line 68, the call
to getJwttokenFromHeaders(headers) uses the instance-level headers which already
include "Content-Type: application/json" set in the constructor, causing
duplicate Content-Type headers. To fix this, create a new HttpHeaders object or
clone the existing headers without the Content-Type before passing it to
getJwttokenFromHeaders, ensuring no duplicate Content-Type headers are added.

Comment on lines 61 to 79
public static void getJwttokenFromHeaders(HttpHeaders headers) {
ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes());
if (servletRequestAttributes == null) {
return;
}
HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
String jwtTokenFromCookie = extractJwttoken(requestHeader);
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
if (null != UserAgentContext.getUserAgent()) {
headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
}
if (null != jwtTokenFromCookie) {
headers.add(HttpHeaders.COOKIE, Constants.JWT_TOKEN + "=" + jwtTokenFromCookie);
} else if (null != requestHeader.getHeader(Constants.JWT_TOKEN)) {
headers.add(Constants.JWT_TOKEN, requestHeader.getHeader(Constants.JWT_TOKEN));
}

}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential header duplication issue in new utility method.

The getJwttokenFromHeaders method adds headers to the provided HttpHeaders object without checking if they already exist. This could cause header duplication if the method is called multiple times or if headers are already present.

Consider checking for existing headers before adding them or document that this method should only be called on empty HttpHeaders objects.

 public static void getJwttokenFromHeaders(HttpHeaders headers) {
 	ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder
 			.getRequestAttributes());
 	if (servletRequestAttributes == null) {
 		return;
 	}
 	HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
 	String jwtTokenFromCookie = extractJwttoken(requestHeader);
-	headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
+	if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
+		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
+	}
 	if (null != UserAgentContext.getUserAgent()) {
-		headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
+		if (!headers.containsKey(HttpHeaders.USER_AGENT)) {
+			headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
+		}
 	}
 	if (null != jwtTokenFromCookie) {
 		headers.add(HttpHeaders.COOKIE, Constants.JWT_TOKEN + "=" + jwtTokenFromCookie);
 	} else if (null != requestHeader.getHeader(Constants.JWT_TOKEN)) {
 		headers.add(Constants.JWT_TOKEN, requestHeader.getHeader(Constants.JWT_TOKEN));
 	}
 }
📝 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
public static void getJwttokenFromHeaders(HttpHeaders headers) {
ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes());
if (servletRequestAttributes == null) {
return;
}
HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
String jwtTokenFromCookie = extractJwttoken(requestHeader);
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
if (null != UserAgentContext.getUserAgent()) {
headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
}
if (null != jwtTokenFromCookie) {
headers.add(HttpHeaders.COOKIE, Constants.JWT_TOKEN + "=" + jwtTokenFromCookie);
} else if (null != requestHeader.getHeader(Constants.JWT_TOKEN)) {
headers.add(Constants.JWT_TOKEN, requestHeader.getHeader(Constants.JWT_TOKEN));
}
}
public static void getJwttokenFromHeaders(HttpHeaders headers) {
ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes());
if (servletRequestAttributes == null) {
return;
}
HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
String jwtTokenFromCookie = extractJwttoken(requestHeader);
if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
}
if (null != UserAgentContext.getUserAgent()) {
if (!headers.containsKey(HttpHeaders.USER_AGENT)) {
headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
}
}
if (null != jwtTokenFromCookie) {
headers.add(HttpHeaders.COOKIE, Constants.JWT_TOKEN + "=" + jwtTokenFromCookie);
} else if (null != requestHeader.getHeader(Constants.JWT_TOKEN)) {
headers.add(Constants.JWT_TOKEN, requestHeader.getHeader(Constants.JWT_TOKEN));
}
}
🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/utils/RestTemplateUtil.java between lines 61
and 79, the getJwttokenFromHeaders method adds headers to the HttpHeaders object
without checking for existing headers, which may cause duplication. To fix this,
before adding each header, check if the header is already present in the
HttpHeaders object and only add it if it is absent. Alternatively, document
clearly that this method should only be called on empty HttpHeaders instances to
avoid duplication.

Copy link

sonarqubecloud bot commented Aug 6, 2025

@ravishanigarapu ravishanigarapu merged commit f8d543e into PSMRI:release-3.5.0 Aug 7, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants