Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOriginPatterns(
allowedOrigins != null && !allowedOrigins.trim().isEmpty() ? Arrays.stream(allowedOrigins.split(","))
.map(String::trim).filter(s -> !s.isEmpty()).toArray(String[]::new) : new String[0])
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("Authorization", "Content-Type", "Accept", "Jwttoken",
"serverAuthorization", "ServerAuthorization", "serverauthorization", "Serverauthorization")
.exposedHeaders("Authorization", "Jwttoken").allowCredentials(true).maxAge(3600);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,34 +97,58 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
}
}

/**
* Handles CORS headers by validating the origin and setting appropriate
* headers.
* AMM-1927: Only sets CORS headers if the origin is from an allowed domain.
*
* @param request The HTTP request
* @param response The HTTP response
*/
private void handleCorsHeaders(HttpServletRequest request, HttpServletResponse response) {
String origin = request.getHeader("Origin");

logger.debug("Incoming Origin: {}", origin);
logger.debug("Allowed Origins Configured: {}", allowedOrigins);

if (origin != null && isOriginAllowed(origin)) {
// Only set CORS headers if the origin is allowed
if (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, Jwttoken");
response.setHeader("Vary", "Origin");
response.setHeader("Access-Control-Allow-Credentials", "true");

logger.debug("CORS headers set for allowed origin: {}", origin);
} else {
logger.warn("Origin [{}] is NOT allowed. CORS headers NOT added.", origin);
}

}

/**
* Validates if the request origin is in the allowed origins list.
* AMM-1927: Aligns with Admin-API implementation for consistent origin
* validation.
*
* @param origin The Origin header value from the HTTP request
* @return true if the origin is allowed, false otherwise
*/
private boolean isOriginAllowed(String origin) {
if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
logger.warn("No allowed origins configured or origin is null");
// Null or empty origin is not allowed
if (origin == null || origin.isEmpty()) {
logger.debug("Origin is null or empty");
return false;
}

// Check if allowed origins are configured
if (allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
logger.warn("No allowed origins configured");
return false;
}

return Arrays.stream(allowedOrigins.split(",")).map(String::trim).anyMatch(pattern -> {
String regex = pattern.replace(".", "\\.").replace("*", ".*").replace("http://localhost:.*",
"http://localhost:\\d+"); // special case for wildcard port
String regex = pattern.replace(".", "\\.").replace("*", ".*");
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

could you keep http://localhost:\\d+ logic

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The removal has also worked with dev with common-api, not sure if it had any effect

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

yes but this is help for digit restrict


boolean matched = origin.matches(regex);
return matched;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@
package com.iemr.common.identity.utils.http;


import java.util.Arrays;

import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
Expand All @@ -42,6 +45,9 @@ public class HTTPRequestInterceptor implements HandlerInterceptor {

Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

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

private SessionObject sessionObject;

@Autowired
Expand Down Expand Up @@ -84,8 +90,13 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
response.getOutputStream().print(output.toString());
response.setContentType(MediaType.APPLICATION_JSON);
response.setContentLength(output.toString().length());
response.setHeader("Access-Control-Allow-Origin", "*");
status = false;
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
} else if (origin != null) {
logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin);
} status = false;
}
}
return status;
Expand Down Expand Up @@ -115,4 +126,19 @@ public void afterCompletion(HttpServletRequest request, HttpServletResponse resp
throws Exception {
logger.debug("In afterCompletion Request Completed");
}

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 -> {
String regex = pattern
.replace(".", "\\.")
.replace("*", ".*");
return origin.matches(regex);
});
}
}