Skip to content

Conversation

@vishwab1
Copy link
Member

@vishwab1 vishwab1 commented May 23, 2025

📋 Description

JIRA ID: 593

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


Added cors orign method to restrict from the browsers

✅ 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

    • Introduced advanced CORS (Cross-Origin Resource Sharing) configuration, allowing the application to control which origins can access the APIs based on external settings.
    • Added support for dynamic CORS headers and preflight request handling, improving compatibility with modern web clients.
  • Refactor

    • Centralized CORS management by removing individual CORS annotations from all controllers and handling CORS at the global configuration and filter level.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 23, 2025

Walkthrough

This change centralizes and enhances Cross-Origin Resource Sharing (CORS) configuration for the application. It removes all @CrossOrigin annotations from controller classes and methods, introduces configurable CORS support via new configuration properties and classes, and implements dynamic CORS handling at the filter and configuration levels.

Changes

File(s) Change Summary
src/main/environment/104_ci.properties, src/main/environment/104_example.properties Added cors.allowed-origins property for CORS configuration. The example file sets it to http://localhost:*, and the CI file uses an environment variable placeholder.
src/main/java/com/iemr/helpline104/config/CorsConfig.java Introduced new CorsConfig class implementing WebMvcConfigurer to configure CORS globally using the allowed origins property.
src/main/java/com/iemr/helpline104/utils/DynamicCorsFilter.java Added new DynamicCorsFilter class that dynamically sets CORS headers based on allowed origins from configuration and handles preflight OPTIONS requests.
src/main/java/com/iemr/helpline104/utils/FilterConfig.java Updated to inject cors.allowed-origins property and pass it to JwtUserIdValidationFilter.
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java Enhanced to support CORS by accepting allowed origins, setting CORS headers, handling preflight requests, and adding origin validation logic.
All controller files under src/main/java/com/iemr/helpline104/controller/... Removed all @CrossOrigin annotations from controller classes and methods. No other logic or method signature changes.

Sequence Diagram(s)

sequenceDiagram
    participant Browser
    participant Filter (JwtUserIdValidationFilter / DynamicCorsFilter)
    participant Spring MVC (CorsConfig)
    participant Controller

    Browser->>Filter: HTTP Request (with Origin header)
    alt OPTIONS (Preflight)
        Filter->>Browser: Set CORS headers, respond 200 OK (short-circuit)
    else Other Methods
        Filter->>Spring MVC: Pass request
        Spring MVC->>Controller: Route to endpoint
        Controller->>Spring MVC: Response
        Spring MVC->>Filter: Response
        Filter->>Browser: Set CORS headers, return response
    end
Loading

Suggested reviewers

  • ravishanigarapu

Poem

In the meadow of code, the CORS bunnies hop,
From filters and configs, the old tags they swap.
No more annotations, just one place to rule,
Origins allowed—now that’s pretty cool!
With headers in tow and wildcards in sight,
This rabbit says: cross-origin’s set right! 🐇✨

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

@sonarqubecloud
Copy link

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

🧹 Nitpick comments (8)
src/main/java/com/iemr/helpline104/controller/version/VersionController.java (1)

31-31: Remove unused CrossOrigin import.
Since the @CrossOrigin annotation was deleted, you can remove the now-unused import org.springframework.web.bind.annotation.CrossOrigin;.

src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)

53-58: Centralized CORS configuration for getBenDirectoryHistory
Removing the method-level CORS annotation is correct. Confirm that /beneficiary/getdirectorySearchHistory is covered by the global CORS configuration.
Nitpick: The import for CrossOrigin on line 30 is now unused and can be removed.

src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java (1)

67-67: Removed method-level @crossorigin annotations – verify global CORS coverage

All four endpoints (startCall, updateBeneficiaryIDInCall, getServices, setServiceHistory) no longer have @CrossOrigin annotations. Ensure that your centralized CORS configuration (in CorsConfig and/or DynamicCorsFilter) includes mappings for /beneficiary/**, correctly handles preflight OPTIONS requests, and allows the required HTTP methods and headers. Without this, browser-based clients may be blocked.

Also applies to: 88-88, 118-118, 141-141

src/main/java/com/iemr/helpline104/controller/epidemicOutbreak/EpidemicOutbreakController.java (2)

30-30: Unused import: remove CrossOrigin

The import org.springframework.web.bind.annotation.CrossOrigin is no longer used after removing all @CrossOrigin annotations. Please delete this import to clean up unused code.


54-54: Removed method-level @crossorigin annotations – confirm centralized CORS config

The methods saveEpidemicOutbreakComplaint, getEpidemicOutbreakComplaint, and updateEpidemicOutbreakComplaint have had their @CrossOrigin annotations removed. Verify that the global CORS settings in CorsConfig (and DynamicCorsFilter) cover /beneficiary/** paths, correctly apply allowed origins, methods, and headers, and support preflight checks for these endpoints.

Also applies to: 77-77, 104-104

src/main/java/com/iemr/helpline104/controller/diseaseScreening/DiseaseScreeningController.java (1)

60-60: Removed method-level @crossorigin annotations – ensure global CORS rules apply

Both fetchQuestions and fetchAnswers endpoints have had their @CrossOrigin annotations removed. Please confirm that your centralized CORS configuration in CorsConfig or via DynamicCorsFilter properly registers these /beneficiary/get/** endpoints, handles OPTIONS preflights, and allows the necessary headers and methods for disease-screening data.

Also applies to: 84-84

src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java (1)

56-56: Removed method-level @crossorigin annotations – validate global CORS coverage

All five getDrugGroups, getDrugList, getDrugFrequency, getDrugStrength, and getDrugNameList endpoints no longer carry @CrossOrigin. Make sure CorsConfig or your dynamic filter includes /beneficiary/** mappings for these drug-group related URIs, allows required methods/headers, and processes preflight requests so that browser clients can interact with these APIs.

Also applies to: 77-77, 102-102, 120-120, 142-142

src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (1)

47-47: Removed class-level @crossorigin annotation – confirm class paths are covered

The class-level @CrossOrigin annotation was removed. Verify that the global CORS configuration applies to the /crmReports/** base path for all report endpoints.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 170af88 and 552198b.

📒 Files selected for processing (35)
  • src/main/environment/104_ci.properties (1 hunks)
  • src/main/environment/104_example.properties (1 hunks)
  • src/main/java/com/iemr/helpline104/config/CorsConfig.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java (4 hunks)
  • src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java (3 hunks)
  • src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java (4 hunks)
  • src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/bloodRequest/BloodRequestController.java (6 hunks)
  • src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/casesheet/Helpline104BeneficiaryHistoryController.java (3 hunks)
  • src/main/java/com/iemr/helpline104/controller/cdss/ClinicalDecisionSupportController.java (4 hunks)
  • src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/disease/DiseaseController.java (6 hunks)
  • src/main/java/com/iemr/helpline104/controller/diseaseScreening/DiseaseScreeningController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java (5 hunks)
  • src/main/java/com/iemr/helpline104/controller/epidemicOutbreak/EpidemicOutbreakController.java (3 hunks)
  • src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java (4 hunks)
  • src/main/java/com/iemr/helpline104/controller/feedbackType/FeedbackTypeController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/location/CountryCityController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/location/LocationController.java (6 hunks)
  • src/main/java/com/iemr/helpline104/controller/organDonation/OrganDonationController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/prescription/PrescriptionController.java (4 hunks)
  • src/main/java/com/iemr/helpline104/controller/scheme/SchemeController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (18 hunks)
  • src/main/java/com/iemr/helpline104/controller/sioHistory/ServiceImprovementOfficerController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/snomedct/SnomedController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java (7 hunks)
  • src/main/java/com/iemr/helpline104/controller/version/VersionController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/DynamicCorsFilter.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (4 hunks)
💤 Files with no reviewable changes (2)
  • src/main/java/com/iemr/helpline104/controller/organDonation/OrganDonationController.java
  • src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
🔇 Additional comments (62)
src/main/environment/104_ci.properties (1)

29-29: Added cors.allowed-origins property for CORS configuration.
This new property externalizes allowed origins via an environment variable placeholder. Ensure that @CORS_ALLOWED_ORIGINS@ is populated in CI with a comma-separated list of valid origins, and that the corresponding 104_example.properties file is also updated for local testing.

src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java (2)

37-37: Confirm centralized CORS handling covers this endpoint.
The class‐level @CrossOrigin annotation was removed to defer to the global CORS configuration (CorsConfig/DynamicCorsFilter). Verify that WebMvcConfigurer mappings and the filter chain correctly apply CORS to all /master/** endpoints, including OPTIONS preflight.


59-59: Removed method‐level @CrossOrigin; using global CORS config.
The saveBenCovidDoctorData method no longer needs explicit CORS annotations. Confirm that dynamic origin validation in DynamicCorsFilter handles this POST endpoint.

src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java (1)

37-37: Removed class‐level @CrossOrigin annotation.
CORS is now managed centrally via CorsConfig and DynamicCorsFilter. Ensure that the /hihl/** endpoints are properly covered by the global CORS rules and that OPTIONS requests are handled appropriately.

src/main/java/com/iemr/helpline104/controller/version/VersionController.java (1)

44-44: Removed obsolete @CrossOrigin on versionInformation.
This endpoint now relies on the centralized CORS configuration. Confirm that origin checks and preflight support apply to /version.

src/main/java/com/iemr/helpline104/controller/feedbackType/FeedbackTypeController.java (1)

49-49: Removed method‐level CORS annotation for complaint types.
The @CrossOrigin on getNatureOfComplaintTypes is no longer needed; CORS is handled by the centralized config. Verify that the /beneficiary/get/natureOfComplaintTypes POST endpoint responds correctly to preflight requests.

src/main/java/com/iemr/helpline104/controller/sioHistory/ServiceImprovementOfficerController.java (1)

67-70: Centralized CORS configuration applied correctly
Removing the method-level @CrossOrigin to rely on the new global CORS setup is appropriate. Ensure the global CorsConfig covers the /beneficiary/getSioHistory endpoint and handles preflight requests.

src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java (4)

61-66: Centralized CORS configuration for feedbackReuest method
The @CrossOrigin annotation removal is correct. Confirm that the global CORS policy applies to /beneficiary/getfeedbacklist and supports both preflight and actual requests.


78-83: Centralized CORS configuration for getFeedbackByPost method
Removing the method-level CORS annotation is appropriate. Verify that /beneficiary/getfeedback/{feedbackID} is included in the global CORS configuration.


94-99: Centralized CORS configuration for updateFeedback method
The @CrossOrigin removal here is aligned with the centralized approach. Ensure the global filter handles /beneficiary/updatefeedback correctly.


118-123: Centralized CORS configuration for saveBenFeedback method
Good removal of @CrossOrigin. Confirm that /beneficiary/saveBenFeedback is covered by the new global CORS setup.

src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java (2)

51-56: Centralized CORS configuration for saveCallqamapping method
Removing the method-level CORS annotation is correct. Verify that /beneficiary/save/callqamapping is included in the global cors.allowed-origins.


72-76: Centralized CORS configuration for getCDIqamapping method
The removal of @CrossOrigin aligns with the global strategy. Ensure that preflight OPTIONS and actual requests to /beneficiary/get/CDIqamapping are handled by the centralized filter.

src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)

75-80: Centralized CORS configuration for directorySearchHistory
Removing @CrossOrigin here is appropriate. Verify that /beneficiary/save/directorySearchHistory preflight and actual requests are managed by the centralized filter.

src/main/java/com/iemr/helpline104/controller/snomedct/SnomedController.java (2)

53-57: Centralized CORS configuration for getSnomedCTRecord
The removal of the method-level CORS annotation is correct. Ensure that /snomed/getSnomedCTRecord is properly handled by the new global CORS setup.


87-91: Centralized CORS configuration for getSnomedCTRecords
Removing @CrossOrigin aligns with the centralized approach. Confirm that /snomed/getSnomedCTRecords requests (including OPTIONS) are covered by the global CORS policy.

src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java (2)

50-56: Removal of method‐level CORS annotations is correct and aligns with centralized CORS setup.

The @CrossOrigin annotation has been removed before saveBloodComponentDetails. CORS is now handled via the global CorsConfig and DynamicCorsFilter, so per-controller annotations are no longer needed.


68-73: Removal of method‐level CORS annotations is correct and aligns with centralized CORS setup.

The @CrossOrigin annotation has been removed before getBloodComponentDetails. Centralized CORS configuration covers this endpoint now.

src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java (3)

57-64: Removed @CrossOrigin above saveIMRMMR—consistent with global CORS approach.

CORS will be applied via the externalized cors.allowed-origins and filters. No further per-method configuration is needed.


81-87: Removed @CrossOrigin above fetchSupportServices—consistent with global CORS approach.

Global CORS rules will cover preflight and runtime headers for this GET endpoint.


108-113: Removed @CrossOrigin above feedbackReuest—consistent with global CORS approach.

This POST endpoint is now protected by the centralized filter configuration.

src/main/java/com/iemr/helpline104/controller/disease/DiseaseController.java (6)

42-46: Removed @CrossOrigin above saveDisease—aligned with centralized CORS config.


60-64: Removed @CrossOrigin above deleteDisease—aligned with centralized CORS config.


78-82: Removed @CrossOrigin above getDisease—aligned with centralized CORS config.


96-100: Removed @CrossOrigin above updateDisease—aligned with centralized CORS config.


114-118: Removed @CrossOrigin above getAvailableDiseases—aligned with centralized CORS config.


131-135: Removed @CrossOrigin above getDiseasesByID—aligned with centralized CORS config.

src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java (2)

53-60: Removed @CrossOrigin above saveFoodComplaintDetails—centralized CORS applies globally.

Controlled via CorsConfig and DynamicCorsFilter.


83-88: Removed @CrossOrigin above getFoodComplaintDetails—centralized CORS applies globally.

src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java (3)

48-54: Removed @CrossOrigin above saveBalVivahComplaint—centralized CORS applies globally.


63-69: Removed @CrossOrigin above getBalVivahList—centralized CORS applies globally.


82-88: Removed @CrossOrigin above updateBalVivahComplaint—centralized CORS applies globally.

src/main/java/com/iemr/helpline104/controller/location/CountryCityController.java (1)

44-44:

Details

✅ Verification successful

Verify centralized CORS configuration covers these endpoints.

The removal of @CrossOrigin annotations from the getCountry() and getCities() methods aligns with the centralized CORS configuration approach. However, ensure that the new centralized configuration properly handles CORS for these endpoints.

Please test that frontend applications can still access these endpoints after the CORS configuration change.

Also applies to: 62-62


🏁 Script executed:

#!/bin/bash
# Verify that centralized CORS configuration exists and covers all endpoints

# Search for the CorsConfig class mentioned in AI summary
ast-grep --pattern 'class CorsConfig {
  $$$
}'

# Search for DynamicCorsFilter class
ast-grep --pattern 'class DynamicCorsFilter {
  $$$
}'

# Search for any remaining @CrossOrigin annotations that might have been missed
rg -n "@CrossOrigin" --type java

Length of output: 139


🏁 Script executed:

#!/bin/bash
set -e
# Search for centralized CORS setup in the repository

# Look for WebMvcConfigurer implementations configuring CORS
rg -n "implements WebMvcConfigurer" --type java -A3

# Look for addCorsMappings usage
rg -n "addCorsMappings" --type java -A3

# Look for any CorsConfigurationSource beans
rg -n "CorsConfigurationSource" --type java -A3

# Look for a class named CorsConfig
rg -n "class .*CorsConfig" --type java -A3

# Look for a custom DynamicCorsFilter
rg -n "class .*DynamicCorsFilter" --type java -A3

Length of output: 1391


Centralized CORS configuration in CorsConfig covers all endpoints

Verified that src/main/java/com/iemr/helpline104/config/CorsConfig.java implements WebMvcConfigurer and calls registry.addMapping("/**") with the configured origin patterns and HTTP methods. This global mapping ensures CORS is applied to the getCountry() and getCities() endpoints, making the removal of their @CrossOrigin annotations safe.

src/main/java/com/iemr/helpline104/controller/cdss/ClinicalDecisionSupportController.java (1)

49-49:

Details

✅ Verification successful

Ensure centralized CORS handles POST endpoints for critical healthcare operations.

The removal of @CrossOrigin annotations from all four methods (getSymptomsPost, getQuestion, getResult, saveSymptom) is consistent with the centralization approach. These are critical healthcare decision support endpoints that likely require CORS support for browser-based frontends.

Verify that the centralized CORS configuration properly handles POST requests and preflight OPTIONS requests for these endpoints:

Critical: Test these endpoints thoroughly as they handle clinical decision support functionality.

Also applies to: 76-76, 102-102, 128-128


🏁 Script executed:

#!/bin/bash
# Check if the centralized CORS configuration handles POST methods
rg -A 10 -B 5 "allowedMethods.*POST" --type java

# Look for preflight request handling in filters
rg -A 5 -B 5 "OPTIONS.*request" --type java

# Verify CORS headers are being set for POST endpoints
rg -A 5 -B 5 "Access-Control-Allow-Methods" --type java

Length of output: 5304


Centralized CORS configuration supports POST and preflight OPTIONS for CDSS endpoints

  • In CorsConfig.java: .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") covers all controller methods.
  • In JwtUserIdValidationFilter.java: OPTIONS requests are short-circuited with SC_OK and CORS headers (Access-Control-Allow-Methods, etc.) are set.
  • In DynamicCorsFilter.java: the Origin header is validated, allowed origins are echoed, and OPTIONS requests are handled before the filter chain.
  • Removal of @CrossOrigin from getSymptomsPost, getQuestion, getResult, and saveSymptom is safe under this centralized setup.

No further action required.

src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java (1)

61-61:

Details

❓ Verification inconclusive

Test authentication and security endpoints thoroughly after CORS centralization.

Seven critical authentication and user management methods had their @CrossOrigin annotations removed:

  • userAuthenticate - Core authentication
  • forgetPassword - Password recovery
  • setForgetPassword - Password reset
  • changePassword - Password change
  • saveUserSecurityQuesAns - Security questions
  • getSecurityts - Security questions retrieval
  • getrolewrapuptime - Role management

These endpoints are critical for user security. Please thoroughly test:

  1. Login flows from browser-based applications
  2. Password reset workflows
  3. Cross-origin preflight handling for POST requests
  4. Security question management

Consider implementing additional security measures like origin validation for these sensitive endpoints.

Also applies to: 102-102, 130-130, 152-152, 175-175, 197-197, 205-205


🏁 Script executed:

#!/bin/bash
# Verify authentication endpoints maintain security while supporting CORS
rg -A 5 -B 5 "userAuthenticate\|forgetPassword\|changePassword" --type java

# Check for any security-related CORS configurations
rg -A 10 "security.*cors\|cors.*security" --type java

Length of output: 133


🏁 Script executed:

#!/bin/bash
# Locate the IEMRAdminController file
controller_file=$(fd IEMRAdminController.java)
echo "Controller file found at: $controller_file"

# List the target methods with context to see if @CrossOrigin is present
rg -n -C2 "public .*userAuthenticate|forgetPassword|setForgetPassword|changePassword|saveUserSecurityQuesAns|getSecurityts|getrolewrapuptime" "$controller_file"

# Check for any @CrossOrigin annotations in that controller
rg -n -C2 "@CrossOrigin" "$controller_file"

Length of output: 3421


Verify CORS for critical authentication and user‐management endpoints

Our inspection of IEMRAdminController.java confirms that the following methods no longer declare @CrossOrigin:

  • userAuthenticate
  • forgetPassword
  • setForgetPassword
  • changePassword
  • saveUserSecurityQuesAns
  • getSecurityts
  • getrolewrapuptime

Please ensure your centralized CORS configuration covers these endpoints and validate that no cross‐origin requests are inadvertently blocked. Thoroughly test:

• Browser-based login flows (including preflight OPTIONS for POST)
• “Forgot password” and reset workflows end-to-end
• Security question CRUD operations
• Role-based endpoints requiring Authorization header

If you haven’t already, review your global CorsConfiguration or WebMvcConfigurer setup to whitelist the necessary origins and HTTP methods. Consider adding origin checks or stricter allowed‐methods on these sensitive routes.

src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (17)

56-56: Removed method-level @crossorigin for getROSummaryReportByDate

Ensure your centralized CORS setup handles /crmReports/getROSummaryReportByDate correctly, including preflight support.


80-80: Removed method-level @crossorigin for getHAOSummaryReportByDate

Confirm the global CORS config allows cross-origin requests to this HAO summary report endpoint.


108-108: Removed method-level @crossorigin for getMOSummaryReportByDate

Validate that /crmReports/getMOSummaryReportByDate is covered by the centralized CORS rules.


136-136: Removed method-level @crossorigin for getMedicalAdviseReport

Confirm global CORS mappings include this medical-advise report URI.


164-164: Removed method-level @crossorigin for getCOSummaryReportByDate

Ensure CORS is configured for the counselling-service summary endpoint.


193-193: Removed method-level @crossorigin for getMentalHealthReport

Verify this mental-health report path is included in global CORS mappings.


221-221: Removed method-level @crossorigin for getGrievanceReportByDate

Check that /crmReports/getGrievanceReportByDate is permitted via centralized CORS.


249-249: Removed method-level @crossorigin for getPrescriptionReportByDate

Confirm cross-origin rules cover prescription report requests.


277-277: Removed method-level @crossorigin for getCDIResponseReport

Ensure CORS config includes the Surveyor report endpoint.


305-305: Removed method-level @crossorigin for getSchemesReportByDate

Validate /crmReports/getSchemesReportByDate in your global CORS policy.


334-334: Removed method-level @crossorigin for getDirectoryServiceReportByDate

Confirm directory-service report URI is covered by CORS mappings.


362-362: Removed method-level @crossorigin for getFoodSafetyReportByDate

Verify food-safety report path is permitted cross-origin.


391-391: Removed method-level @crossorigin for getBloodOnCallReportByDate

Ensure /crmReports/getBloodOnCallReportByDate is included in global CORS rules.


419-419: Removed method-level @crossorigin for getBloodOnCallCountReportByDate

Confirm count report path is configured for cross-origin access.


450-450: Removed method-level @crossorigin for getEpidemicReportByDate

Validate epidemic-outbreak report endpoint in your centralized CORS setup.


476-476: Removed method-level @crossorigin for getOrganDonationReportByDate

Ensure organ-donation report URI is in the global CORS mappings.


504-504: Removed method-level @crossorigin for getPDSummaryReportByDate

Verify psychiatrist summary report endpoint is covered by your CORS configuration.

src/main/java/com/iemr/helpline104/controller/bloodRequest/BloodRequestController.java (1)

58-58: Approve centralized CORS handling
Method‐level @CrossOrigin annotations have been removed in favor of a global configuration (CorsConfig + DynamicCorsFilter). This aligns with best practices for maintainability and consistency across all endpoints.

Also applies to: 80-80, 105-105, 123-123, 141-141, 166-166

src/main/java/com/iemr/helpline104/controller/prescription/PrescriptionController.java (1)

51-51: Approve centralized CORS handling
Removed inline @CrossOrigin annotations from all controller methods; relying on the new global CORS configuration ensures uniform policy enforcement.

Also applies to: 72-72, 99-99, 132-132

src/main/java/com/iemr/helpline104/controller/location/LocationController.java (1)

42-42: Approve centralized CORS handling
All method‐level @CrossOrigin annotations have been dropped. The endpoints will now adhere to global CORS rules defined in CorsConfig, improving consistency and reducing annotation clutter.

Also applies to: 61-61, 70-70, 79-79, 88-88

src/main/java/com/iemr/helpline104/controller/scheme/SchemeController.java (1)

51-51: Approve centralized CORS handling
Inline CORS annotations have been removed from saveSchemeSearchHistory and getBenSchemeHistory. Central configuration now governs cross‐origin policies application‐wide.

Also applies to: 74-74

src/main/java/com/iemr/helpline104/controller/casesheet/Helpline104BeneficiaryHistoryController.java (1)

51-51: Approve centralized CORS handling
Removed method‐level CORS declarations across all three endpoints. The new CorsConfig and dynamic filter will uniformly enforce allowed‐origin rules.

Also applies to: 73-73, 104-104

src/main/java/com/iemr/helpline104/utils/FilterConfig.java (2)

3-3: LGTM! Property injection setup is correct.

The addition of the @Value import and the allowedOrigins field with proper Spring property injection follows standard patterns.

Also applies to: 12-13


16-17:

Details

✅ Verification successful

Verify constructor signature compatibility.

The method now passes allowedOrigins to the JwtUserIdValidationFilter constructor. Ensure that the constructor in JwtUserIdValidationFilter properly accepts this parameter.

Also applies to: 20-22


🏁 Script executed:

#!/bin/bash
# Description: Verify JwtUserIdValidationFilter constructor accepts allowedOrigins parameter
# Expected: Constructor should have parameters (JwtAuthenticationUtil, String)

ast-grep --pattern $'public JwtUserIdValidationFilter($_, $_) {
  $$$
}'

Length of output: 73


🏁 Script executed:

#!/bin/bash
# Locate JwtUserIdValidationFilter class and its constructor signatures
rg --type java "class JwtUserIdValidationFilter" -n .
rg --type java "JwtUserIdValidationFilter(" -n .
rg --type java "allowedOrigins" -n .

Length of output: 2004


Constructor Signature Verified

The JwtUserIdValidationFilter class defines a constructor

public JwtUserIdValidationFilter(
    JwtAuthenticationUtil jwtAuthenticationUtil,
    @Value("${cors.allowed-origins}") String allowedOrigins
)

which exactly matches the usage in FilterConfig:

new JwtUserIdValidationFilter(jwtAuthenticationUtil, allowedOrigins);

No further action is needed.

src/main/java/com/iemr/helpline104/utils/DynamicCorsFilter.java (1)

17-18: ⚠️ Potential issue

Fix type inconsistency in @value injection.

The @Value annotation typically injects a String, but the field is declared as String[]. This will likely cause a ClassCastException at runtime.

-    @Value("${cors.allowed-origins}")
-    private String[] allowedOrigins;
+    @Value("${cors.allowed-origins}")
+    private String allowedOrigins;

Then update the origin checking logic:

-        if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
+        if (origin != null && isOriginAllowed(origin)) {
             response.setHeader("Access-Control-Allow-Origin", origin);
         }

And add the helper method:

+    private boolean isOriginAllowed(String origin) {
+        if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
+            return false;
+        }
+        return Arrays.stream(allowedOrigins.split(","))
+            .map(String::trim)
+            .anyMatch(pattern -> origin.matches(pattern.replace(".", "\\.").replace("*", ".*")));
+    }

Likely an incorrect or invalid review comment.

src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (2)

43-55: CORS implementation is well-structured.

The CORS handling logic is comprehensive and correctly placed before JWT validation. The approach of handling OPTIONS requests early and setting appropriate CORS headers is good practice.


131-140: Robust origin validation with pattern matching.

The isOriginAllowed method correctly implements pattern matching with wildcard support and proper input validation. The regex transformation for wildcards is appropriate.

logging.path=logs/
logging.file.name=logs/helpline104-api.log
logging.file.name=logs/helpline104-api.log
cors.allowed-origins=http://localhost:*
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify CORS origin pattern validity and consider security implications.

The addition of externalized CORS configuration is a good approach for centralization. However, please verify that the wildcard pattern http://localhost:* is supported by your CORS implementation, as many CORS libraries don't support port wildcards.

Additionally, consider the security implications of allowing all localhost ports, as this could potentially allow access from unintended local applications running on different ports.


🌐 Web query:

Does Spring Boot CORS configuration support wildcard ports in origin patterns like "http://localhost:*"?

💡 Result:

Based on the search results, Spring Boot's CORS configuration does not natively support wildcard ports in origin patterns like "http://localhost:*". However, there are several approaches to handle this scenario.

CORS Configuration Options in Spring Boot

Spring provides multiple ways to configure CORS with varying levels of flexibility:

Method-Level and Class-Level Configuration

Using the @CrossOrigin annotation, you can specify allowed origins for specific endpoints or controllers:

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class MyController {
    // Controller methods
}

This approach requires you to explicitly specify each allowed origin port (e.g., "http://localhost:4200")[5][7].

Global Configuration

For application-wide CORS settings, you can implement WebMvcConfigurer:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://localhost:4200")
            .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

This configuration also requires explicit origin specification[4][5].

Alternative Solutions for Localhost Development

Since Spring Boot doesn't directly support wildcard ports in origins, here are alternatives for local development:

1. Using allowedOriginPatterns

Since Spring Boot 2.4.0, there's a more flexible allowedOriginPatterns option that provides more pattern-matching capabilities than the standard allowedOrigins[3]. While it doesn't explicitly support port wildcards, it offers more flexibility.

2. Multiple Origin Configuration

You can specify multiple localhost origins with different ports:

registry.addMapping("/api/**")
    .allowedOrigins(
        "http://localhost:3000", 
        "http://localhost:4200", 
        "http://localhost:8080"
    );

3. Feature Request

There is recognition of this need in the community. For instance, there's a feature request in the Kubernetes ingress-nginx project (issue #8264) to allow wildcard ports specifically for localhost origins[6]. This suggests that wildcard port support for localhost would be valuable, but it's not currently a standard feature in Spring Boot.

Best Practices for CORS in Development vs. Production

For development environments:

  • Configure multiple specific localhost origins as needed
  • Consider using a more permissive CORS policy during development

For production environments:

  • Use specific, restrictive origin lists
  • Avoid wildcards entirely for security reasons
  • If using allowCredentials = true, you cannot use wildcards for origins[7]

If you need to test with varying localhost ports, the most straightforward approach is to list all the specific ports you might use during development rather than relying on a wildcard pattern that isn't supported.

Citations:


Update CORS configuration to use supported origin patterns

The pattern http://localhost:* isn’t recognized by Spring Boot’s allowedOrigins. Please adjust as follows:

• In Spring Boot 2.4+ you can use allowedOriginPatterns with Ant-style patterns:

# src/main/environment/104_example.properties (line 25)
cors.allowed-origin-patterns=http://localhost:[*]

(This lets you match any localhost port.)

• Or explicitly list the ports you need:

cors.allowed-origins=http://localhost:3000,http://localhost:4200,http://localhost:8080

Security note: avoid wildcards in production—only whitelist specific origins when allowCredentials=true and lock down CORS in your prod environment.

🤖 Prompt for AI Agents
In src/main/environment/104_example.properties at line 25, the CORS origin
pattern "http://localhost:*" is not supported by Spring Boot's allowedOrigins
configuration. To fix this, replace it with either the allowedOriginPatterns
property using an Ant-style pattern like "http://localhost:[*]" to match any
localhost port, or explicitly list the allowed localhost origins with specific
ports separated by commas. Ensure this change aligns with your Spring Boot
version (2.4+) and consider restricting origins in production for security.

import io.swagger.v3.oas.annotations.Operation;

@CrossOrigin

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Verify class-level CORS configuration for sensitive authentication controller.

The removal of the class-level @CrossOrigin annotation from this authentication controller requires careful verification that the centralized CORS configuration maintains proper access controls while preserving security.

Ensure that authentication flows work correctly with the new CORS setup, especially for login and password reset operations.


🏁 Script executed:

#!/bin/bash
# Verify centralized CORS configuration handles authentication endpoints securely
rg -A 15 -B 5 "cors.*authentication\|authentication.*cors" --type java

# Check if JWT filter integration handles CORS properly
ast-grep --pattern 'class JwtUserIdValidationFilter {
  $$$
  cors
  $$$
}'

# Look for CORS configuration that might affect authentication flows
rg -A 10 "CorsConfig\|cors.*config" --type java

Length of output: 200


Global CORS configuration missing for authentication endpoints

I searched for any centralized CORS setup (e.g. CorsConfig, WebMvcConfigurer implementations, or addCorsMappings overrides) and found nothing. By removing the class-level and method-level @CrossOrigin annotations, all browser requests to your login, password-reset and other sensitive endpoints will now be blocked by default.

• No CorsConfig or similar bean in the codebase
• No WebMvcConfigurer–style addCorsMappings(...) implementation
• No alternative CORS filter or security config handling these paths

Please add or restore a global CORS configuration that covers your authentication routes (or re-apply @CrossOrigin where appropriate) to ensure legitimate browser clients can still reach the login and administration endpoints.

🤖 Prompt for AI Agents
In src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java
at line 49, the removal of the class-level @CrossOrigin annotation has left
authentication endpoints without CORS support, causing browser requests to be
blocked. To fix this, implement a global CORS configuration by creating a
CorsConfig class or a WebMvcConfigurer bean that overrides addCorsMappings to
allow CORS requests specifically for login, password reset, and other
authentication-related paths. Alternatively, re-apply the @CrossOrigin
annotation on the controller or its methods to restore CORS support for these
sensitive endpoints.

Comment on lines +16 to +17
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins.split(","))
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

Consider validation for empty origins configuration.

The code splits allowedOrigins by comma without checking if it's null or empty, which could lead to unexpected behavior.

-        registry.addMapping("/**")
-                .allowedOriginPatterns(allowedOrigins.split(","))
+        registry.addMapping("/**")
+                .allowedOriginPatterns(allowedOrigins != null && !allowedOrigins.trim().isEmpty() 
+                    ? allowedOrigins.split(",") 
+                    : new String[0])
📝 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
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins.split(","))
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins != null && !allowedOrigins.trim().isEmpty()
? allowedOrigins.split(",")
: new String[0])
🤖 Prompt for AI Agents
In src/main/java/com/iemr/helpline104/config/CorsConfig.java around lines 16 to
17, the code splits the allowedOrigins string by commas without validating if
allowedOrigins is null or empty. To fix this, add a check before splitting to
ensure allowedOrigins is not null or empty; if it is, handle it appropriately by
either setting a default value or skipping the configuration to avoid unexpected
behavior.

Comment on lines +18 to +22
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
.allowCredentials(true)
.maxAge(3600)
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

Review security implications of CORS configuration.

The current configuration has several security considerations:

  1. allowCredentials(true) with potentially broad origin patterns could be risky
  2. allowedHeaders("*") is very permissive
  3. Exposing Authorization and Jwttoken headers increases attack surface

Consider more restrictive settings:

                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
-                .allowedHeaders("*")
+                .allowedHeaders("Authorization", "Content-Type", "Accept", "Jwttoken")
                .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
                .allowCredentials(true)
                .maxAge(3600)
📝 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
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
.allowCredentials(true)
.maxAge(3600)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Authorization", "Content-Type", "Accept", "Jwttoken")
.exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
.allowCredentials(true)
.maxAge(3600)
🤖 Prompt for AI Agents
In src/main/java/com/iemr/helpline104/config/CorsConfig.java around lines 18 to
22, the CORS configuration is overly permissive and poses security risks by
allowing credentials with broad origins, permitting all headers, and exposing
sensitive headers like Authorization and Jwttoken. To fix this, restrict allowed
origins to specific trusted domains instead of allowing all, specify only
necessary headers in allowedHeaders instead of "*", and avoid exposing sensitive
headers unless absolutely required. Adjust allowCredentials accordingly to match
the restricted origins and minimize exposure.

Comment on lines +26 to +35
String origin = request.getHeader("Origin");
if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}

if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
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

Incomplete CORS header configuration and potential conflicts.

This filter sets minimal CORS headers compared to the comprehensive configuration in CorsConfig. This could lead to inconsistent CORS behavior and potential conflicts.

Consider either:

  1. Removing this filter since CorsConfig already handles CORS globally, or
  2. Completing the CORS implementation to match CorsConfig:
         String origin = request.getHeader("Origin");
-        if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
+        if (origin != null && isOriginAllowed(origin)) {
             response.setHeader("Access-Control-Allow-Origin", origin);
+            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
+            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
+            response.setHeader("Access-Control-Allow-Credentials", "true");
+            response.setHeader("Access-Control-Max-Age", "3600");
         }

Having both CorsConfig (WebMvcConfigurer) and DynamicCorsFilter could lead to conflicts. Consider consolidating CORS handling into a single approach.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/iemr/helpline104/utils/DynamicCorsFilter.java around lines
26 to 35, the current CORS header setup is minimal and inconsistent with the
comprehensive CORS configuration in CorsConfig, which may cause conflicts. To
fix this, either remove the DynamicCorsFilter entirely to rely solely on the
global CorsConfig for CORS handling, or update the filter to fully implement all
necessary CORS headers consistent with CorsConfig. Prefer consolidating CORS
logic into one place to avoid overlapping configurations and potential issues.

import org.springframework.stereotype.Component;

import com.iemr.helpline104.utils.http.AuthorizationHeaderRequestWrapper;
import org.springframework.beans.factory.annotation.Value;
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

Unusual constructor parameter annotation pattern.

Using @Value directly in constructor parameters is unconventional and may not work as expected. The typical pattern is to inject via field or use constructor injection without annotations.

Consider refactoring to use field injection:

 @Component
 public class JwtUserIdValidationFilter implements Filter {
 
     private final JwtAuthenticationUtil jwtAuthenticationUtil;
     private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
-	private final String allowedOrigins;
+    
+    @Value("${cors.allowed-origins}")
+    private String allowedOrigins;
 
-	public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil, @Value("${cors.allowed-origins}") String allowedOrigins) {
+	public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) {
 		this.jwtAuthenticationUtil = jwtAuthenticationUtil;
-		 this.allowedOrigins = allowedOrigins;  
-	}	
+	}

However, since FilterConfig explicitly passes the parameter, keep the current approach but remove the @Value annotation from the constructor parameter.

Also applies to: 27-27, 29-32

🤖 Prompt for AI Agents
In src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java
around lines 10, 27, and 29-32, remove the @Value annotation from the
constructor parameters because using @Value directly on constructor parameters
is unconventional and may not work properly. Instead, keep the constructor
parameters plain and rely on explicit passing of values (e.g., from
FilterConfig), or alternatively use field injection with @Value on fields if
appropriate.

Comment on lines +43 to +55
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
response.setHeader("Access-Control-Allow-Credentials", "true");
}

if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
logger.info("OPTIONS request - skipping JWT validation");
response.setStatus(HttpServletResponse.SC_OK);
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Potential conflicts with multiple CORS implementations.

This filter sets CORS headers, but you also have CorsConfig (global Spring MVC CORS) and DynamicCorsFilter. Multiple CORS implementations can lead to conflicts or inconsistent behavior.

Consider consolidating CORS handling:

  1. Option 1: Remove CORS logic from this filter and rely solely on CorsConfig
  2. Option 2: Remove CorsConfig and DynamicCorsFilter, keeping CORS logic only in this security filter
  3. Option 3: Ensure all CORS implementations use identical configuration

🏁 Script executed:

#!/bin/bash
# Description: Check for potential CORS configuration conflicts
# Expected: Should identify all CORS-related configurations in the codebase

echo "=== Searching for CORS configurations ==="
rg -A 5 -B 2 "cors|CORS|Cross-Origin" --type java

echo "=== Searching for @CrossOrigin annotations (should be removed) ==="
rg "@CrossOrigin" --type java

Length of output: 4043


Consolidate CORS configuration across filters and global config

The codebase currently applies CORS rules in three places, which can lead to conflicting headers or unexpected behavior:

• src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java
• src/main/java/com/iemr/helpline104/utils/DynamicCorsFilter.java
• src/main/java/com/iemr/helpline104/config/CorsConfig.java

Recommended approaches:

  1. Remove all CORS-header logic from JwtUserIdValidationFilter and DynamicCorsFilter, and rely solely on the Spring MVC–based CorsConfig.
  2. Alternatively, decommission CorsConfig and DynamicCorsFilter and centralize CORS handling in your security filter.
  3. If you must keep multiple implementations, ensure they pull from the same properties and expose exactly the same methods, headers, origins, and credentials settings.

Choose one strategy to eliminate overlap and prevent inconsistent CORS responses.

🤖 Prompt for AI Agents
In src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java
around lines 43 to 55, the filter sets CORS headers which conflicts with other
CORS implementations in DynamicCorsFilter and CorsConfig. To fix this, remove
all CORS header-setting logic from JwtUserIdValidationFilter and rely solely on
the centralized CorsConfig for CORS handling, or alternatively remove CorsConfig
and DynamicCorsFilter and keep CORS logic only in this filter. Ensure only one
consistent CORS configuration exists to avoid conflicting headers and
inconsistent behavior.

@vishwab1 vishwab1 closed this Jun 17, 2025
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.

3 participants