-
Notifications
You must be signed in to change notification settings - Fork 26
Cors configuration for helpline 104 api service #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis change centralizes and enhances Cross-Origin Resource Sharing (CORS) configuration for the application. It removes all 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
Suggested reviewers
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 (
|
value assign:- @CORS_ALLOWED_ORIGINS@
|
There was a problem hiding this 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 unusedCrossOriginimport.
Since the@CrossOriginannotation was deleted, you can remove the now-unusedimport org.springframework.web.bind.annotation.CrossOrigin;.src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)
53-58: Centralized CORS configuration forgetBenDirectoryHistory
Removing the method-level CORS annotation is correct. Confirm that/beneficiary/getdirectorySearchHistoryis covered by the global CORS configuration.
Nitpick: The import forCrossOriginon 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 coverageAll four endpoints (
startCall,updateBeneficiaryIDInCall,getServices,setServiceHistory) no longer have@CrossOriginannotations. Ensure that your centralized CORS configuration (inCorsConfigand/orDynamicCorsFilter) includes mappings for/beneficiary/**, correctly handles preflightOPTIONSrequests, 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: removeCrossOriginThe import
org.springframework.web.bind.annotation.CrossOriginis no longer used after removing all@CrossOriginannotations. Please delete this import to clean up unused code.
54-54: Removed method-level @crossorigin annotations – confirm centralized CORS configThe methods
saveEpidemicOutbreakComplaint,getEpidemicOutbreakComplaint, andupdateEpidemicOutbreakComplainthave had their@CrossOriginannotations removed. Verify that the global CORS settings inCorsConfig(andDynamicCorsFilter) 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 applyBoth
fetchQuestionsandfetchAnswersendpoints have had their@CrossOriginannotations removed. Please confirm that your centralized CORS configuration inCorsConfigor viaDynamicCorsFilterproperly registers these/beneficiary/get/**endpoints, handlesOPTIONSpreflights, 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 coverageAll five
getDrugGroups,getDrugList,getDrugFrequency,getDrugStrength, andgetDrugNameListendpoints no longer carry@CrossOrigin. Make sureCorsConfigor 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 coveredThe class-level
@CrossOriginannotation 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
📒 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: Addedcors.allowed-originsproperty 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 corresponding104_example.propertiesfile 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@CrossOriginannotation was removed to defer to the global CORS configuration (CorsConfig/DynamicCorsFilter). Verify thatWebMvcConfigurermappings and the filter chain correctly apply CORS to all/master/**endpoints, including OPTIONS preflight.
59-59: Removed method‐level@CrossOrigin; using global CORS config.
ThesaveBenCovidDoctorDatamethod no longer needs explicit CORS annotations. Confirm that dynamic origin validation inDynamicCorsFilterhandles this POST endpoint.src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java (1)
37-37: Removed class‐level@CrossOriginannotation.
CORS is now managed centrally viaCorsConfigandDynamicCorsFilter. 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@CrossOriginonversionInformation.
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@CrossOriginongetNatureOfComplaintTypesis no longer needed; CORS is handled by the centralized config. Verify that the/beneficiary/get/natureOfComplaintTypesPOST 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@CrossOriginto rely on the new global CORS setup is appropriate. Ensure the globalCorsConfigcovers the/beneficiary/getSioHistoryendpoint and handles preflight requests.src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java (4)
61-66: Centralized CORS configuration forfeedbackReuestmethod
The@CrossOriginannotation removal is correct. Confirm that the global CORS policy applies to/beneficiary/getfeedbacklistand supports both preflight and actual requests.
78-83: Centralized CORS configuration forgetFeedbackByPostmethod
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 forupdateFeedbackmethod
The@CrossOriginremoval here is aligned with the centralized approach. Ensure the global filter handles/beneficiary/updatefeedbackcorrectly.
118-123: Centralized CORS configuration forsaveBenFeedbackmethod
Good removal of@CrossOrigin. Confirm that/beneficiary/saveBenFeedbackis covered by the new global CORS setup.src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java (2)
51-56: Centralized CORS configuration forsaveCallqamappingmethod
Removing the method-level CORS annotation is correct. Verify that/beneficiary/save/callqamappingis included in the globalcors.allowed-origins.
72-76: Centralized CORS configuration forgetCDIqamappingmethod
The removal of@CrossOriginaligns with the global strategy. Ensure that preflight OPTIONS and actual requests to/beneficiary/get/CDIqamappingare handled by the centralized filter.src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)
75-80: Centralized CORS configuration fordirectorySearchHistory
Removing@CrossOriginhere is appropriate. Verify that/beneficiary/save/directorySearchHistorypreflight 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 forgetSnomedCTRecord
The removal of the method-level CORS annotation is correct. Ensure that/snomed/getSnomedCTRecordis properly handled by the new global CORS setup.
87-91: Centralized CORS configuration forgetSnomedCTRecords
Removing@CrossOriginaligns with the centralized approach. Confirm that/snomed/getSnomedCTRecordsrequests (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
@CrossOriginannotation has been removed beforesaveBloodComponentDetails. CORS is now handled via the globalCorsConfigandDynamicCorsFilter, 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
@CrossOriginannotation has been removed beforegetBloodComponentDetails. Centralized CORS configuration covers this endpoint now.src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java (3)
57-64: Removed@CrossOriginabovesaveIMRMMR—consistent with global CORS approach.CORS will be applied via the externalized
cors.allowed-originsand filters. No further per-method configuration is needed.
81-87: Removed@CrossOriginabovefetchSupportServices—consistent with global CORS approach.Global CORS rules will cover preflight and runtime headers for this GET endpoint.
108-113: Removed@CrossOriginabovefeedbackReuest—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@CrossOriginabovesaveDisease—aligned with centralized CORS config.
60-64: Removed@CrossOriginabovedeleteDisease—aligned with centralized CORS config.
78-82: Removed@CrossOriginabovegetDisease—aligned with centralized CORS config.
96-100: Removed@CrossOriginaboveupdateDisease—aligned with centralized CORS config.
114-118: Removed@CrossOriginabovegetAvailableDiseases—aligned with centralized CORS config.
131-135: Removed@CrossOriginabovegetDiseasesByID—aligned with centralized CORS config.src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java (2)
53-60: Removed@CrossOriginabovesaveFoodComplaintDetails—centralized CORS applies globally.Controlled via
CorsConfigandDynamicCorsFilter.
83-88: Removed@CrossOriginabovegetFoodComplaintDetails—centralized CORS applies globally.src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java (3)
48-54: Removed@CrossOriginabovesaveBalVivahComplaint—centralized CORS applies globally.
63-69: Removed@CrossOriginabovegetBalVivahList—centralized CORS applies globally.
82-88: Removed@CrossOriginaboveupdateBalVivahComplaint—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
@CrossOriginannotations from thegetCountry()andgetCities()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 javaLength 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 -A3Length of output: 1391
Centralized CORS configuration in CorsConfig covers all endpoints
Verified that
src/main/java/com/iemr/helpline104/config/CorsConfig.javaimplementsWebMvcConfigurerand callsregistry.addMapping("/**")with the configured origin patterns and HTTP methods. This global mapping ensures CORS is applied to thegetCountry()andgetCities()endpoints, making the removal of their@CrossOriginannotations 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
@CrossOriginannotations 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 javaLength 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 withSC_OKand CORS headers (Access-Control-Allow-Methods, etc.) are set.- In
DynamicCorsFilter.java: theOriginheader is validated, allowed origins are echoed, and OPTIONS requests are handled before the filter chain.- Removal of
@CrossOriginfromgetSymptomsPost,getQuestion,getResult, andsaveSymptomis 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
@CrossOriginannotations removed:
userAuthenticate- Core authenticationforgetPassword- Password recoverysetForgetPassword- Password resetchangePassword- Password changesaveUserSecurityQuesAns- Security questionsgetSecurityts- Security questions retrievalgetrolewrapuptime- Role managementThese endpoints are critical for user security. Please thoroughly test:
- Login flows from browser-based applications
- Password reset workflows
- Cross-origin preflight handling for POST requests
- 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 javaLength 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.javaconfirms 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 requiringAuthorizationheaderIf you haven’t already, review your global
CorsConfigurationorWebMvcConfigurersetup 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 forgetROSummaryReportByDateEnsure your centralized CORS setup handles
/crmReports/getROSummaryReportByDatecorrectly, including preflight support.
80-80: Removed method-level @crossorigin forgetHAOSummaryReportByDateConfirm the global CORS config allows cross-origin requests to this HAO summary report endpoint.
108-108: Removed method-level @crossorigin forgetMOSummaryReportByDateValidate that
/crmReports/getMOSummaryReportByDateis covered by the centralized CORS rules.
136-136: Removed method-level @crossorigin forgetMedicalAdviseReportConfirm global CORS mappings include this medical-advise report URI.
164-164: Removed method-level @crossorigin forgetCOSummaryReportByDateEnsure CORS is configured for the counselling-service summary endpoint.
193-193: Removed method-level @crossorigin forgetMentalHealthReportVerify this mental-health report path is included in global CORS mappings.
221-221: Removed method-level @crossorigin forgetGrievanceReportByDateCheck that
/crmReports/getGrievanceReportByDateis permitted via centralized CORS.
249-249: Removed method-level @crossorigin forgetPrescriptionReportByDateConfirm cross-origin rules cover prescription report requests.
277-277: Removed method-level @crossorigin forgetCDIResponseReportEnsure CORS config includes the Surveyor report endpoint.
305-305: Removed method-level @crossorigin forgetSchemesReportByDateValidate
/crmReports/getSchemesReportByDatein your global CORS policy.
334-334: Removed method-level @crossorigin forgetDirectoryServiceReportByDateConfirm directory-service report URI is covered by CORS mappings.
362-362: Removed method-level @crossorigin forgetFoodSafetyReportByDateVerify food-safety report path is permitted cross-origin.
391-391: Removed method-level @crossorigin forgetBloodOnCallReportByDateEnsure
/crmReports/getBloodOnCallReportByDateis included in global CORS rules.
419-419: Removed method-level @crossorigin forgetBloodOnCallCountReportByDateConfirm count report path is configured for cross-origin access.
450-450: Removed method-level @crossorigin forgetEpidemicReportByDateValidate epidemic-outbreak report endpoint in your centralized CORS setup.
476-476: Removed method-level @crossorigin forgetOrganDonationReportByDateEnsure organ-donation report URI is in the global CORS mappings.
504-504: Removed method-level @crossorigin forgetPDSummaryReportByDateVerify 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@CrossOriginannotations 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@CrossOriginannotations 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@CrossOriginannotations have been dropped. The endpoints will now adhere to global CORS rules defined inCorsConfig, 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 fromsaveSchemeSearchHistoryandgetBenSchemeHistory. 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 newCorsConfigand 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
@Valueimport and theallowedOriginsfield 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
allowedOriginsto theJwtUserIdValidationFilterconstructor. Ensure that the constructor inJwtUserIdValidationFilterproperly 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
JwtUserIdValidationFilterclass defines a constructorpublic 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 issueFix type inconsistency in @value injection.
The
@Valueannotation typically injects a String, but the field is declared asString[]. 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
isOriginAllowedmethod 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:* |
There was a problem hiding this comment.
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:
- 1: https://spring.io/guides/gs/rest-service-cors
- 2: https://www.stackhawk.com/blog/spring-cors-guide/
- 3: https://www.baeldung.com/spring-cors
- 4: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
- 5: https://www.mymiller.name/wordpress/spng_security/spring-cors-configuration-a-comprehensive-guide/
- 6: Allow wildcard port for localhost in cors-allow-origin kubernetes/ingress-nginx#8264
- 7: https://dev.to/brandonwie/cors-in-spring-boot-with-kotlin-4ge2
- 8: https://reflectoring.io/spring-cors/
- 9: https://www.springcloud.io/post/2022-04/spring-cors/
- 10: https://www.baeldung.com/spring-cloud-gateaway-configure-cors-policy
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:8080Security 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 | ||
|
|
There was a problem hiding this comment.
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 javaLength 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.
| registry.addMapping("/**") | ||
| .allowedOriginPatterns(allowedOrigins.split(",")) |
There was a problem hiding this comment.
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.
| 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.
| .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") | ||
| .allowedHeaders("*") | ||
| .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed | ||
| .allowCredentials(true) | ||
| .maxAge(3600) |
There was a problem hiding this comment.
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:
allowCredentials(true)with potentially broad origin patterns could be riskyallowedHeaders("*")is very permissive- Exposing
AuthorizationandJwttokenheaders 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.
| .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.
| 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); | ||
| } |
There was a problem hiding this comment.
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:
- Removing this filter since
CorsConfigalready handles CORS globally, or - 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; |
There was a problem hiding this comment.
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.
| 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; | ||
| } |
There was a problem hiding this comment.
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:
- Option 1: Remove CORS logic from this filter and rely solely on
CorsConfig - Option 2: Remove
CorsConfigandDynamicCorsFilter, keeping CORS logic only in this security filter - 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 javaLength 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:
- Remove all CORS-header logic from
JwtUserIdValidationFilterandDynamicCorsFilter, and rely solely on the Spring MVC–basedCorsConfig. - Alternatively, decommission
CorsConfigandDynamicCorsFilterand centralize CORS handling in your security filter. - 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.



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