jwttoken and user-agent validation#73
Conversation
|
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 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. 📒 Files selected for processing (1)
WalkthroughThe 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
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
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, ...)
Possibly related PRs
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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 suggestionInconsistent 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 conventionsThe field
Authorizationshould be renamed toauthorization(camelCase) to follow standard Java naming conventions.- private final String Authorization; + private final String authorization;
10-16: Add class and field documentationThis 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 nameThe 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 referenceIf 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 referenceIf 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 constantThe 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 warningThis 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 getUserAgentThe
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 commentsThe 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
📒 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 valueThe 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 robustnessThe 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()andUserAgentContext.clear()calls are correctly wrapped in atry { … } finally { … }block inJwtUserIdValidationFilter.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.
| if (authorization == null || authorization.isEmpty()) { | ||
| logger.info("Authorization header is null or empty. Skipping HTTPRequestInterceptor."); | ||
| return true; // Allow the request to proceed without validation | ||
| } |
There was a problem hiding this comment.
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:
- Using WARN level logging instead of INFO for security-related events
- Implementing endpoint-specific authorization checks if some endpoints require authorization
- 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.
| 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.
| AuthorizationHeaderRequestWrapper authorizationHeaderRequestWrapper = new AuthorizationHeaderRequestWrapper( | ||
| request, ""); | ||
| filterChain.doFilter(authorizationHeaderRequestWrapper, servletResponse); | ||
| return; |
There was a problem hiding this comment.
💡 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 javaLength of output: 2832
🏁 Script executed:
#!/bin/bash
# Locate and display the AuthorizationHeaderRequestWrapper implementation to understand its behavior
rg -n "class AuthorizationHeaderRequestWrapper" -A 200 --type javaLength 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.
| 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); | ||
| } | ||
|
|
||
| } |
There was a problem hiding this comment.
🛠️ 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:
- The exception handling only prints the stack trace without proper logging or error propagation
- The code doesn't handle null values from UserAgentContext.getUserAgent()
- The code doesn't handle null values from requestHeader.getHeader("JwtToken")
- 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.
| 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.
|



📋 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
ℹ️ 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
Bug Fixes
Refactor