Skip to content

jwttoken and user-agent validation#73

Merged
ravishanigarapu merged 3 commits into
PSMRI:developfrom
ravishanigarapu:develop
May 22, 2025
Merged

jwttoken and user-agent validation#73
ravishanigarapu merged 3 commits into
PSMRI:developfrom
ravishanigarapu:develop

Conversation

@ravishanigarapu
Copy link
Copy Markdown
Contributor

@ravishanigarapu ravishanigarapu commented May 22, 2025

📋 Description

JIRA ID: AMM-1456

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


✅ 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 authorization headers, including support for overriding or injecting custom authorization values in HTTP requests.
    • Enhanced support for user agent tracking, allowing user agent information to be managed per request.
    • Centralized creation of HTTP request entities with consistent headers for REST operations.
  • Bug Fixes

    • Prevented potential errors when processing requests without cookies.
  • Refactor

    • Streamlined internal logic for constructing HTTP request headers and entities, reducing code duplication.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 22, 2025

Warning

Rate limit exceeded

@ravishanigarapu has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 29 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 3b24656 and ca4126d.

📒 Files selected for processing (1)
  • src/main/java/com/iemr/ecd/utils/mapper/RestTemplateUtil.java (1 hunks)

Walkthrough

The changes introduce new utility classes for HTTP request handling, refactor JWT and authorization header management, and update request entity construction for REST calls. The code now centralizes header and token logic, handles user agent context with thread-local storage, and improves robustness in cookie extraction and HTTP request wrapping.

Changes

File(s) Change Summary
src/main/java/com/iemr/ecd/service/associate/BeneficiaryRegistrationServiceImpl.java Refactored HTTP entity and header construction in two methods to use a new utility method, removing manual JWT and header handling.
src/main/java/com/iemr/ecd/utils/http_request_interceptor/AuthorizationHeaderRequestWrapper.java Added a new class to override and inject the "Authorization" header in HTTP requests.
src/main/java/com/iemr/ecd/utils/http_request_interceptor/HttpInterceptor.java Added a check to bypass processing if the authorization token is missing or empty, logging this case.
src/main/java/com/iemr/ecd/utils/mapper/CookieUtil.java Made getJwtTokenFromCookie static and added a null check for cookies to prevent exceptions.
src/main/java/com/iemr/ecd/utils/mapper/JwtUserIdValidationFilter.java Modified JWT validation logic to use the new header wrapper and thread-local user agent context; improved conditional structure.
src/main/java/com/iemr/ecd/utils/mapper/RestTemplateUtil.java Added a utility class to centralize creation of HTTP entities with consistent headers and token propagation.
src/main/java/com/iemr/ecd/utils/mapper/UserAgentContext.java Added a utility class for managing user agent strings in thread-local storage.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JwtUserIdValidationFilter
    participant AuthorizationHeaderRequestWrapper
    participant UserAgentContext
    participant DownstreamService

    Client->>JwtUserIdValidationFilter: Sends HTTP Request
    JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Check JWT in Cookie/Header
    alt JWT in Cookie or Header
        JwtUserIdValidationFilter->>AuthorizationHeaderRequestWrapper: Wrap request with Authorization header
        AuthorizationHeaderRequestWrapper-->>JwtUserIdValidationFilter: Wrapped request
        JwtUserIdValidationFilter->>DownstreamService: Continue filter chain with wrapped request
    else Mobile User-Agent with Authorization
        JwtUserIdValidationFilter->>UserAgentContext: Set UserAgent
        JwtUserIdValidationFilter->>DownstreamService: Continue filter chain with original request
        JwtUserIdValidationFilter->>UserAgentContext: Clear UserAgent
    else No valid token
        JwtUserIdValidationFilter-->>Client: Respond 401 Unauthorized
    end
Loading
sequenceDiagram
    participant ServiceImpl
    participant RestTemplateUtil
    participant CookieUtil
    participant UserAgentContext
    participant RestTemplate

    ServiceImpl->>RestTemplateUtil: createRequestEntity(body, authorization)
    RestTemplateUtil->>CookieUtil: getJwtTokenFromCookie(request)
    RestTemplateUtil->>UserAgentContext: getUserAgent()
    RestTemplateUtil-->>ServiceImpl: HttpEntity with headers/body
    ServiceImpl->>RestTemplate: exchange(HttpEntity, ...)
Loading

Possibly related PRs

Poem

In the warren of code, a rabbit hops quick,
Wrapping headers and cookies with a clever new trick.
JWTs now guarded, user agents in thread,
Utilities tidy where chaos once spread.
With paws on the keyboard, this bunny’s delight—
Refactoring magic, the future is bright!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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

Copy link
Copy Markdown

@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: 3

🔭 Outside diff range comments (1)
src/main/java/com/iemr/ecd/utils/http_request_interceptor/HttpInterceptor.java (1)

60-123: 🛠️ Refactor suggestion

Inconsistent handling between preHandle and postHandle

The preHandle method now bypasses validation for null/empty authorization headers, but postHandle still attempts to process them. Consider adding similar handling in postHandle to maintain consistency.

 			String postAuth = request.getHeader("Authorization");
 			if(null != postAuth && postAuth.contains("Bearer "))
 				authorization=postAuth.replace("Bearer ", "");
 			else
 				authorization = postAuth;
 			logger.debug("RequestURI::" + request.getRequestURI() + " || Authorization ::" + authorization);
-			if (authorization != null) {
+			if (authorization != null && !authorization.isEmpty()) {
 				redisStorage.updateConcurrentSessionObject(redisStorage.getSessionObject(authorization));
 				redisStorage.updateSessionObject(authorization);
 			}
🧹 Nitpick comments (9)
src/main/java/com/iemr/ecd/utils/http_request_interceptor/AuthorizationHeaderRequestWrapper.java (5)

10-11: Field name violates Java naming conventions

The field Authorization should be renamed to authorization (camelCase) to follow standard Java naming conventions.

-	private final String Authorization;
+	private final String authorization;

10-16: Add class and field documentation

This class lacks proper JavaDoc documentation. Consider adding class-level documentation explaining its purpose and constructor parameter documentation.

+/**
+ * A request wrapper that allows overriding the Authorization header.
+ * This wrapper is useful when you need to modify the Authorization header
+ * value in the HTTP request chain.
+ */
 public class AuthorizationHeaderRequestWrapper extends HttpServletRequestWrapper{
-	private final String Authorization;
+	/**
+	 * The custom Authorization header value to use
+	 */
+	private final String authorization;

     public AuthorizationHeaderRequestWrapper(HttpServletRequest request, String authHeaderValue) {
         super(request);
-        this.Authorization = authHeaderValue;
+        this.authorization = authHeaderValue;
     }

19-24: Use constant for header name

The string "Authorization" is hardcoded multiple times in the class. Extract it to a constant to improve maintainability.

 public class AuthorizationHeaderRequestWrapper extends HttpServletRequestWrapper{
+	private static final String AUTHORIZATION_HEADER = "Authorization";
 	private final String Authorization;

     // ...

     @Override
     public String getHeader(String name) {
-        if ("Authorization".equalsIgnoreCase(name)) {
+        if (AUTHORIZATION_HEADER.equalsIgnoreCase(name)) {
             return Authorization;
         }
         return super.getHeader(name);
     }

Also update references in the other methods.


19-24: Update variable reference

If you rename the field as suggested, don't forget to update the reference in this method.

     @Override
     public String getHeader(String name) {
         if ("Authorization".equalsIgnoreCase(name)) {
-            return Authorization;
+            return authorization;
         }
         return super.getHeader(name);
     }

28-30: Update variable reference

If you rename the field as suggested, update the reference in this method too.

     @Override
     public Enumeration<String> getHeaders(String name) {
         if ("Authorization".equalsIgnoreCase(name)) {
-            return Collections.enumeration(Collections.singletonList(Authorization));
+            return Collections.enumeration(Collections.singletonList(authorization));
         }
         return super.getHeaders(name);
     }
src/main/java/com/iemr/ecd/utils/mapper/CookieUtil.java (1)

27-37: Extract cookie name as a constant

The cookie name "Jwttoken" is hardcoded in the method. Extract it to a constant for better maintainability and to avoid typos.

+	private static final String JWT_COOKIE_NAME = "Jwttoken";
+
 	public static String getJwtTokenFromCookie(HttpServletRequest request) {
 		Cookie[] cookies = request.getCookies();
 	    if (cookies == null) {
 	        return null; // No cookies present, return null safely
 	    }
 	    return Arrays.stream(cookies)
-	                 .filter(cookie -> "Jwttoken".equals(cookie.getName()))
+	                 .filter(cookie -> JWT_COOKIE_NAME.equals(cookie.getName()))
 	                 .map(Cookie::getValue)
 	                 .findFirst()
 	                 .orElse(null);
 	}
src/main/java/com/iemr/ecd/utils/mapper/UserAgentContext.java (3)

3-17: Add class documentation and memory leak warning

This class lacks JavaDoc documentation. Consider adding class-level documentation explaining its purpose and usage, especially warning about potential memory leaks if clear() is not called.

+/**
+ * Thread-local context for storing and retrieving User-Agent information.
+ * <p>
+ * This class provides static methods to set, get, and clear User-Agent information
+ * specific to the current thread. This ensures thread isolation for User-Agent data.
+ * <p>
+ * IMPORTANT: Always call the clear() method after processing is complete to prevent
+ * memory leaks, especially in server environments with thread pools.
+ */
 public class UserAgentContext {
 	private static final ThreadLocal<String> userAgentHolder = new ThreadLocal<>();

10-12: Handle null case in getUserAgent

The getUserAgent() method doesn't handle the case where no value has been set, which could lead to NullPointerExceptions. Consider returning a default value or adding null checks where this method is used.

     public static String getUserAgent() {
-        return userAgentHolder.get();
+        return userAgentHolder.get(); // Note: This may return null if not set
     }

Or alternatively:

     public static String getUserAgent() {
-        return userAgentHolder.get();
+        String userAgent = userAgentHolder.get();
+        return userAgent != null ? userAgent : "";
     }

1-18: Add method JavaDoc comments

The methods in this class lack JavaDoc comments. Add documentation to explain their purpose, parameters, and return values.

+    /**
+     * Sets the User-Agent for the current thread.
+     * 
+     * @param userAgent the User-Agent string to store
+     */
     public static void setUserAgent(String userAgent) {
         userAgentHolder.set(userAgent);
     }

+    /**
+     * Gets the User-Agent for the current thread.
+     * 
+     * @return the User-Agent string or null if not set
+     */
     public static String getUserAgent() {
         return userAgentHolder.get();
     }

+    /**
+     * Clears the User-Agent for the current thread.
+     * This method should be called after processing is complete to prevent memory leaks.
+     */
     public static void clear() {
         userAgentHolder.remove();
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c7f24be and 3b24656.

📒 Files selected for processing (7)
  • src/main/java/com/iemr/ecd/service/associate/BeneficiaryRegistrationServiceImpl.java (3 hunks)
  • src/main/java/com/iemr/ecd/utils/http_request_interceptor/AuthorizationHeaderRequestWrapper.java (1 hunks)
  • src/main/java/com/iemr/ecd/utils/http_request_interceptor/HttpInterceptor.java (1 hunks)
  • src/main/java/com/iemr/ecd/utils/mapper/CookieUtil.java (1 hunks)
  • src/main/java/com/iemr/ecd/utils/mapper/JwtUserIdValidationFilter.java (2 hunks)
  • src/main/java/com/iemr/ecd/utils/mapper/RestTemplateUtil.java (1 hunks)
  • src/main/java/com/iemr/ecd/utils/mapper/UserAgentContext.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/main/java/com/iemr/ecd/service/associate/BeneficiaryRegistrationServiceImpl.java (1)
src/main/java/com/iemr/ecd/utils/mapper/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/ecd/utils/mapper/JwtUserIdValidationFilter.java (2)
src/main/java/com/iemr/ecd/utils/http_request_interceptor/AuthorizationHeaderRequestWrapper.java (1)
  • AuthorizationHeaderRequestWrapper (10-42)
src/main/java/com/iemr/ecd/utils/mapper/UserAgentContext.java (1)
  • UserAgentContext (3-18)
src/main/java/com/iemr/ecd/utils/mapper/RestTemplateUtil.java (1)
src/main/java/com/iemr/ecd/utils/mapper/UserAgentContext.java (1)
  • UserAgentContext (3-18)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
🔇 Additional comments (9)
src/main/java/com/iemr/ecd/utils/http_request_interceptor/AuthorizationHeaderRequestWrapper.java (1)

1-42: Consider handling empty authorization value

The current implementation doesn't specifically handle the case where an empty string is provided as the authorization value. Consider whether you want to treat empty strings differently from null or other values.

src/main/java/com/iemr/ecd/utils/mapper/CookieUtil.java (1)

27-37: Good improvements to method robustness

The changes properly handle null cookie arrays and use a clean functional approach with streams. Making the method static is appropriate for a utility method that doesn't depend on instance state.

src/main/java/com/iemr/ecd/utils/mapper/UserAgentContext.java (1)

1-18:

Details

✅ Verification successful

Check for thread safety concerns in application usage

The ThreadLocal approach is appropriate for maintaining thread-specific context, but ensure that the application correctly sets and clears this context for each request, especially in a servlet container with thread pools.

Run the following script to verify proper usage of UserAgentContext.clear() method:


🏁 Script executed:

#!/bin/bash
# Check if UserAgentContext.clear() is called after setUserAgent() to prevent memory leaks

echo "Checking for proper ThreadLocal cleanup..."

# Look for places where UserAgentContext.setUserAgent is used
set_locations=$(rg "UserAgentContext\.setUserAgent" -A 10 -B 2)
echo "Found UserAgentContext.setUserAgent usage:"
echo "$set_locations"
echo ""

# Check if clear() is called in the same methods or in finally blocks
echo "Checking for corresponding clear() calls..."
clear_calls=$(rg "UserAgentContext\.clear" -A 2 -B 5)
echo "$clear_calls"
echo ""

# Check specifically for try-finally patterns which are the safest
echo "Checking for try-finally cleanup patterns..."
try_finally_patterns=$(rg -p "try\s*\{.*UserAgentContext\.setUserAgent.*\}.*finally\s*\{.*UserAgentContext\.clear" --multiline)
echo "$try_finally_patterns"

echo "Make sure UserAgentContext.clear() is called in finally blocks to prevent memory leaks"

Length of output: 7470


ThreadLocal cleanup verified in JwtUserIdValidationFilter

The UserAgentContext.setUserAgent() and UserAgentContext.clear() calls are correctly wrapped in a try { … } finally { … } block in JwtUserIdValidationFilter.java, ensuring proper per-request cleanup and preventing memory leaks. No further changes required.

src/main/java/com/iemr/ecd/service/associate/BeneficiaryRegistrationServiceImpl.java (3)

54-54: Added appropriate import for the new utility class.

The import of RestTemplateUtil is correctly added to support the refactored HTTP entity creation.


111-112: Improved code maintainability by centralizing HTTP entity creation.

The manual creation of HttpEntity with headers has been replaced with the RestTemplateUtil utility method, which reduces code duplication and centralizes JWT token handling and header management.


180-180: Consistent implementation of centralized request entity creation.

This change ensures consistent header handling across different API calls, improving maintainability and reducing the risk of inconsistent header configurations.

src/main/java/com/iemr/ecd/utils/mapper/JwtUserIdValidationFilter.java (3)

9-10: Added import for the new request wrapper class.

The import is correctly added to support the authorization header wrapping functionality.


82-89: Improved handling of JWT token from header.

The implementation now uses a clearer if-else structure and consistently wraps the request with the authorization header wrapper for both cookie and header JWT tokens.


90-101: Added support for mobile client authentication.

The implementation now detects mobile clients based on the User-Agent header and allows them to proceed if they have an Authorization header. The UserAgentContext is properly set and cleared in a try-finally block, which is a good practice for thread-local variables.

However, there's no validation of the Authorization header content for mobile clients. This could be a security concern if invalid tokens are accepted.

Consider validating the Authorization header content for mobile clients similar to how JWT tokens are validated. This would ensure consistent security validation across all authentication methods.

Comment on lines +60 to +63
if (authorization == null || authorization.isEmpty()) {
logger.info("Authorization header is null or empty. Skipping HTTPRequestInterceptor.");
return true; // Allow the request to proceed without validation
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security concern: bypassing authorization validation

This change allows requests without authorization headers to bypass validation entirely. Ensure this aligns with your security requirements, as it could potentially allow unauthorized access to protected endpoints.

Consider:

  1. Using WARN level logging instead of INFO for security-related events
  2. Implementing endpoint-specific authorization checks if some endpoints require authorization
  3. Adding comments explaining why this bypass is acceptable
 		if (authorization == null || authorization.isEmpty()) {
-	        logger.info("Authorization header is null or empty. Skipping HTTPRequestInterceptor.");
+	        logger.warn("Authorization header is null or empty. Skipping HTTPRequestInterceptor validation.");
+	        // TODO: Verify this is acceptable for all endpoints or implement endpoint-specific checks
 	        return true; // Allow the request to proceed without validation
 	    }
📝 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
if (authorization == null || authorization.isEmpty()) {
logger.info("Authorization header is null or empty. Skipping HTTPRequestInterceptor.");
return true; // Allow the request to proceed without validation
}
if (authorization == null || authorization.isEmpty()) {
- logger.info("Authorization header is null or empty. Skipping HTTPRequestInterceptor.");
+ logger.warn("Authorization header is null or empty. Skipping HTTPRequestInterceptor validation.");
+ // TODO: Verify this is acceptable for all endpoints or implement endpoint-specific checks
return true; // Allow the request to proceed without validation
}
🤖 Prompt for AI Agents
In
src/main/java/com/iemr/ecd/utils/http_request_interceptor/HttpInterceptor.java
around lines 60 to 63, the current code allows requests without authorization
headers to bypass validation, which may cause unauthorized access. Change the
logger level from INFO to WARN for better visibility of security-related events,
add comments explaining why bypassing authorization is acceptable if it is
intentional, and consider implementing endpoint-specific authorization checks to
enforce security on protected endpoints.

Comment on lines +77 to 80
AuthorizationHeaderRequestWrapper authorizationHeaderRequestWrapper = new AuthorizationHeaderRequestWrapper(
request, "");
filterChain.doFilter(authorizationHeaderRequestWrapper, servletResponse);
return;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Request is now wrapped with AuthorizationHeaderRequestWrapper.

The implementation now wraps the request with an authorization header wrapper before continuing the filter chain. However, the empty string passed as the authorization value seems unusual.

Could you verify why an empty string is passed as the authorization value? This might override any existing authorization header with an empty value, potentially causing authentication issues in downstream components.


🏁 Script executed:

#!/bin/bash
# Check if any other components rely on the Authorization header
rg -A 5 "getHeader\s*\(\s*\"Authorization\"\s*\)" --type java

Length of output: 2832


🏁 Script executed:

#!/bin/bash
# Locate and display the AuthorizationHeaderRequestWrapper implementation to understand its behavior
rg -n "class AuthorizationHeaderRequestWrapper" -A 200 --type java

Length of output: 4419


The AuthorizationHeaderRequestWrapper replaces whatever “Authorization” header was on the original request with exactly the String you pass—in this case, an empty string. That means downstream components will see an empty header instead of the JWT you just validated from the cookie. Unless there’s another filter later that re-injects the token, this will effectively strip out the header entirely and is almost certainly not what you want.

You should pass the actual token (e.g. prefixed with Bearer ) into the wrapper instead of "".

• In JwtUserIdValidationFilter.java (around lines 77–80), change:

new AuthorizationHeaderRequestWrapper(request, "")

to something like:

new AuthorizationHeaderRequestWrapper(request, "Bearer " + jwtFromCookie)
🤖 Prompt for AI Agents
In src/main/java/com/iemr/ecd/utils/mapper/JwtUserIdValidationFilter.java around
lines 77 to 80, the AuthorizationHeaderRequestWrapper is instantiated with an
empty string, which replaces the Authorization header with an empty value and
can cause authentication issues downstream. To fix this, pass the actual JWT
token prefixed with "Bearer " instead of an empty string when creating the
wrapper, for example, use "Bearer " + jwtFromCookie to preserve the valid token
in the Authorization header.

Comment on lines +13 to +42
public class RestTemplateUtil {
public static HttpEntity<Object> createRequestEntity(Object body, String authorization) {

ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
if (servletRequestAttributes == null) {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
headers.add(HttpHeaders.AUTHORIZATION, authorization);
return new HttpEntity<>(body, headers);
}
HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
String jwtTokenFromCookie = null;
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);

} catch (Exception e) {
e.printStackTrace();
}

MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
headers.add(HttpHeaders.AUTHORIZATION, authorization);
headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);

return new HttpEntity<>(body, headers);
}

}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

New utility class for centralizing HTTP entity creation.

This well-structured utility method centralizes the creation of HTTP entities with consistent headers. However, there are several improvements that could be made:

  1. The exception handling only prints the stack trace without proper logging or error propagation
  2. The code doesn't handle null values from UserAgentContext.getUserAgent()
  3. The code doesn't handle null values from requestHeader.getHeader("JwtToken")
  4. The code concatenates "Jwttoken=" with jwtTokenFromCookie without checking if jwtTokenFromCookie is null

Apply these improvements:

public static HttpEntity<Object> createRequestEntity(Object body, String authorization) {
    
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
    if (servletRequestAttributes == null) {
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
        headers.add(HttpHeaders.AUTHORIZATION, authorization);
        return new HttpEntity<>(body, headers);
    }
    HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
    String jwtTokenFromCookie = null;
    try {
        jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
-       
    } catch (Exception e) {
-       e.printStackTrace();
+       // Log the exception but continue with null token
+       // Consider using a proper logger here
    }

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
-   headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
+   
+   // Add User-Agent header if available
+   String userAgent = UserAgentContext.getUserAgent();
+   if (userAgent != null) {
+       headers.add(HttpHeaders.USER_AGENT, userAgent);
+   }
    
    headers.add(HttpHeaders.AUTHORIZATION, authorization);
-   headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
-   headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
+   
+   // Add JwtToken header if available
+   String jwtToken = requestHeader.getHeader("JwtToken");
+   if (jwtToken != null) {
+       headers.add("JwtToken", jwtToken);
+   }
+   
+   // Add Cookie header if JWT token is available
+   if (jwtTokenFromCookie != null) {
+       headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
+   }

    return new HttpEntity<>(body, headers);
}
📝 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 class RestTemplateUtil {
public static HttpEntity<Object> createRequestEntity(Object body, String authorization) {
ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
if (servletRequestAttributes == null) {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
headers.add(HttpHeaders.AUTHORIZATION, authorization);
return new HttpEntity<>(body, headers);
}
HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
String jwtTokenFromCookie = null;
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
} catch (Exception e) {
e.printStackTrace();
}
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
headers.add(HttpHeaders.USER_AGENT, UserAgentContext.getUserAgent());
headers.add(HttpHeaders.AUTHORIZATION, authorization);
headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
return new HttpEntity<>(body, headers);
}
}
public class RestTemplateUtil {
public static HttpEntity<Object> createRequestEntity(Object body, String authorization) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (servletRequestAttributes == null) {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
headers.add(HttpHeaders.AUTHORIZATION, authorization);
return new HttpEntity<>(body, headers);
}
HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
String jwtTokenFromCookie = null;
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
} catch (Exception e) {
// Log the exception but continue with null token
// Consider using a proper logger here
}
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
// Add User-Agent header if available
String userAgent = UserAgentContext.getUserAgent();
if (userAgent != null) {
headers.add(HttpHeaders.USER_AGENT, userAgent);
}
headers.add(HttpHeaders.AUTHORIZATION, authorization);
// Add JwtToken header if available
String jwtToken = requestHeader.getHeader("JwtToken");
if (jwtToken != null) {
headers.add("JwtToken", jwtToken);
}
// Add Cookie header if JWT token is available
if (jwtTokenFromCookie != null) {
headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
}
return new HttpEntity<>(body, headers);
}
}
🤖 Prompt for AI Agents
In src/main/java/com/iemr/ecd/utils/mapper/RestTemplateUtil.java between lines
13 and 42, improve exception handling by replacing e.printStackTrace() with
proper logging or rethrowing the exception; check if
UserAgentContext.getUserAgent() returns null before adding the USER_AGENT header
and handle it appropriately; verify that requestHeader.getHeader("JwtToken") is
not null before adding it to headers; and ensure jwtTokenFromCookie is not null
before concatenating it with "Jwttoken=" to avoid adding invalid or null cookie
values.

@sonarqubecloud
Copy link
Copy Markdown

@ravishanigarapu ravishanigarapu merged commit 5919a09 into PSMRI:develop May 22, 2025
7 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request May 25, 2025
10 tasks
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