Skip to content

Commit 3e350ec

Browse files
committed
fix:added cors error api fix
1 parent dfbf623 commit 3e350ec

File tree

4 files changed

+76
-36
lines changed

4 files changed

+76
-36
lines changed

src/main/java/com/iemr/ecd/config/CorsConfig.java

Lines changed: 0 additions & 28 deletions
This file was deleted.

src/main/java/com/iemr/ecd/config/WebConfiguration.java

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,33 @@
2424
import org.springframework.context.annotation.Configuration;
2525
import org.springframework.web.servlet.config.annotation.CorsRegistry;
2626
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
27+
import java.util.Arrays;
28+
import org.springframework.beans.factory.annotation.Value;
29+
import org.slf4j.Logger;
30+
import org.slf4j.LoggerFactory;
2731

2832
@Configuration
2933
public class WebConfiguration implements WebMvcConfigurer {
3034

35+
private static final Logger logger = LoggerFactory.getLogger(WebConfiguration.class);
36+
37+
@Value("${cors.allowed-origins}")
38+
private String allowedOrigins;
39+
3140
@Override
3241
public void addCorsMappings(CorsRegistry registry) {
33-
registry.addMapping("/**").allowedMethods("*");
34-
}
42+
String[] originPatterns = Arrays.stream(allowedOrigins.split(","))
43+
.map(String::trim)
44+
.toArray(String[]::new);
3545

46+
logger.info("Initializing CORS configuration with allowed origins: {}", Arrays.toString(originPatterns));
47+
48+
registry.addMapping("/**")
49+
.allowedOriginPatterns(originPatterns)
50+
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
51+
.allowedHeaders("*")
52+
.exposedHeaders("Authorization", "Jwttoken")
53+
.allowCredentials(true)
54+
.maxAge(3600);
55+
}
3656
}

src/main/java/com/iemr/ecd/utils/mapper/FilterConfig.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,26 @@
33
import org.springframework.boot.web.servlet.FilterRegistrationBean;
44
import org.springframework.context.annotation.Bean;
55
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.core.Ordered;
7+
import org.springframework.beans.factory.annotation.Value;
68

79
@Configuration
810
public class FilterConfig {
911

12+
@Value("${cors.allowed-origins}")
13+
private String allowedOrigins;
14+
1015
@Bean
1116
public FilterRegistrationBean<JwtUserIdValidationFilter> jwtUserIdValidationFilter(
1217
JwtAuthenticationUtil jwtAuthenticationUtil) {
1318
FilterRegistrationBean<JwtUserIdValidationFilter> registrationBean = new FilterRegistrationBean<>();
14-
registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil));
19+
20+
// Pass allowedOrigins explicitly to the filter constructor
21+
JwtUserIdValidationFilter filter = new JwtUserIdValidationFilter(jwtAuthenticationUtil, allowedOrigins);
22+
23+
registrationBean.setFilter(filter);
24+
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
1525
registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints
1626
return registrationBean;
1727
}
18-
1928
}

src/main/java/com/iemr/ecd/utils/mapper/JwtUserIdValidationFilter.java

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import org.slf4j.Logger;
66
import org.slf4j.LoggerFactory;
7-
import org.springframework.stereotype.Component;
87

98
import com.iemr.ecd.utils.constants.Constants;
109
import com.iemr.ecd.utils.http_request_interceptor.AuthorizationHeaderRequestWrapper;
@@ -17,15 +16,18 @@
1716
import jakarta.servlet.http.Cookie;
1817
import jakarta.servlet.http.HttpServletRequest;
1918
import jakarta.servlet.http.HttpServletResponse;
19+
import java.util.Arrays;
2020

21-
@Component
2221
public class JwtUserIdValidationFilter implements Filter {
2322

2423
private final JwtAuthenticationUtil jwtAuthenticationUtil;
2524
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
25+
private final String allowedOrigins;
2626

27-
public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) {
27+
public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil,
28+
String allowedOrigins) {
2829
this.jwtAuthenticationUtil = jwtAuthenticationUtil;
30+
this.allowedOrigins = allowedOrigins;
2931
}
3032

3133
@Override
@@ -34,6 +36,22 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
3436
HttpServletRequest request = (HttpServletRequest) servletRequest;
3537
HttpServletResponse response = (HttpServletResponse) servletResponse;
3638

39+
String origin = request.getHeader("Origin");
40+
if (origin != null && isOriginAllowed(origin)) {
41+
response.setHeader("Access-Control-Allow-Origin", origin);
42+
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
43+
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
44+
response.setHeader("Access-Control-Allow-Credentials", "true");
45+
} else {
46+
logger.warn("Origin [{}] is NOT allowed. CORS headers NOT added.", origin);
47+
}
48+
49+
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
50+
logger.info("OPTIONS request - skipping JWT validation");
51+
response.setStatus(HttpServletResponse.SC_OK);
52+
return;
53+
}
54+
3755
String path = request.getRequestURI();
3856
String contextPath = request.getContextPath();
3957
logger.info("JwtUserIdValidationFilter invoked for path: " + path);
@@ -103,18 +121,39 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
103121

104122
logger.warn("No valid authentication token found");
105123
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Invalid or missing token");
106-
124+
107125
} catch (Exception e) {
108126
logger.error("Authorization error: ", e);
109127
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage());
110128
}
111129
}
130+
131+
private boolean isOriginAllowed(String origin) {
132+
if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
133+
logger.warn("No allowed origins configured or origin is null");
134+
return false;
135+
}
136+
137+
return Arrays.stream(allowedOrigins.split(","))
138+
.map(String::trim)
139+
.anyMatch(pattern -> {
140+
String regex = pattern
141+
.replace(".", "\\.")
142+
.replace("*", ".*")
143+
.replace("http://localhost:.*", "http://localhost:\\d+"); // special case for wildcard port
144+
145+
boolean matched = origin.matches(regex);
146+
return matched;
147+
});
148+
}
149+
112150
private boolean isMobileClient(String userAgent) {
113151
if (userAgent == null)
114152
return false;
115153
userAgent = userAgent.toLowerCase();
116154
return userAgent.contains(Constants.OKHTTP);
117155
}
156+
118157
private String getJwtTokenFromCookies(HttpServletRequest request) {
119158
Cookie[] cookies = request.getCookies();
120159
if (cookies != null) {

0 commit comments

Comments
 (0)