Spring boot AngularJs $http.get is empty - java

I am creating a resource monitor that retrieves typical info about a machine on a different domain but same port. When accessing the url directly the data is returned successfully. However if we try it using angularJs the $http.get request would return a "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource". We decided to use the chrome CORS extension to allow the connection. Only problem is now the $http.get request is always empty despite the data existing. Not sure why this is happening as no error is produced.
Angular Controller
app.controller("ServerResourcesController", [ "$scope", "$http", function($scope, $http) {
$http.get("http://000.000.0.0:8080/testing")
.then(function(data){
console.log(data);
})
}]);
Controller
#RestController
public class ServerRestController {
Logger logger = LoggerFactory.getLogger(ServerRestController.class);
ServerQueryController sqc = new ServerQueryController();
#RequestMapping("/server-service-info")
public String ServiceInfo() {//Welcome page, non-rest
return "Server Resource Monitor Service";
}
//rest end point
#GetMapping("/server-resources-info")
public ServerInformation ServerInformation() {
ServerInformation serverInformation = sqc.CurrentServerResourceInformation();
return serverInformation;
}
}
Object Class
#Getter #Setter
#JsonIgnoreProperties(ignoreUnknown = true)
public class ServerInformation {
private String name;
private String ipAddress;
private double systemCpuLoad;
private double freePhysicalMemory;
private double totalPhysicalMemory;
private String operatingSystem;
private double freeDiskSpace;
private double diskUsage;
public ServerInformation() {
}
#Override
public String toString() {
return "Values{ systemCpuLoad: "+systemCpuLoad+
", freePhysicalMemory: "+freePhysicalMemory+
", totalPhysicalMemory: "+totalPhysicalMemory+
", operatingSystem: "+operatingSystem+
", freeDiskSpace: "+freeDiskSpace+
", diskUsage: "+diskUsage+
" }";
}
}

It seems your ServerRestController needs to have cross-origin, add this
#RestController
#CrossOrigin(origins = "*")
public class ServerRestController {
...
}
Also, If you want to allow a specific origin you could do it like this:
#CrossOrigin(origins = "http://stackoverflow.com", maxAge = 3600)
You can set #CrossOrigin with the origins to allow and max age either on each method or on the RestController.
Moreover, if you have multiple RestController it's not a best practice to write #CrossOrigin on each and every controller you may just create a Filter like this:
#Component
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void destroy() {
}
}
See the example here: spring cors

Related

Enable CORS support Spring Boot

I am trying to enable the CORS support in Spring Boot app but I am not getting successful. I looked into a lot of solutions but none seems to be working for me.
When I try to make a call from the Angular app to Java backend I see the error in chrome:
Access to XMLHttpRequest at 'http://localhost:8080/..' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I have enabled CORS in controller method level by adding the following annotation but still I get the preflight request error.
#CrossOrigin(origins = "http://localhost:4200")
My Spring Security configuration:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
}
My custom filter:
#Configuration
public class AuthFilter implements Filter {
#Autowired
private Environment env;
private static final ApplicationLogger logger = ApplicationLogger.getInstance();
#Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.debug("Initializing authentication filter.");
}
public boolean checkHeader(HttpServletRequest httpRequest) {
boolean flag = false;
String applicationName = httpRequest.getHeader("bar");
if (applicationName != null && applicationName.equalsIgnoreCase("foo")) {
flag = true;
}
return flag;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// HttpSession httpSession = httpRequest.getSession();
List<String> excludedUrls = null;
String excludePattern = env.getProperty("excludedUrls");
excludedUrls = Arrays.asList(excludePattern.split(","));
String path = ((HttpServletRequest) request).getServletPath();
String loginPathURL = env.getProperty("loginPathURL");
if (excludedUrls.contains(path)
|| path.contains("/file/..")
|| path.contains("/file/...")
|| path.contains("/file/....")) {
chain.doFilter(request, response);
} else if (checkHeader(httpRequest)) {
// Authenticate the request through LDAP
logger.info("Authenticating the request ...");
chain.doFilter(request, response);
} else {
logger.debug("User is not authenticated");
httpResponse.sendRedirect(loginPathURL);
}
/*
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession httpSession = httpRequest.getSession();
List<String> excludedUrls = null;
String excludePattern = env.getProperty("excludedUrls");
excludedUrls = Arrays.asList(excludePattern.split(","));
String path = ((HttpServletRequest) request).getServletPath();
if (excludedUrls.contains(path)) {
// Authenticate the request through LDAP
logger.info("Authenticating the request ...");
chain.doFilter(request, response);
}
else if(checkHeader(httpRequest)) {
else if (httpSession != null && httpSession.getAttribute(WorkpermitConstants.CLIENT_AUTH_TOKEN_KEY) != null) {
List<Map<String,Object>> res = (List<Map<String,Object>>) jdbcTemplate.queryForList("some select query") ;
if(!AppUtil.isObjectEmpty(res.size())) {
for (Map<String, Object> row : res) {
//currentUserEmail
//empType
//userId
//username
}
}
chain.doFilter(request, response);
} else {
logger.debug("User is not authenticated.");
HttpServletResponse httpResponse = (HttpServletResponse) response;
//httpResponse.sendRedirect(httpRequest.getContextPath() + "/");
httpResponse.sendRedirect("http://..");
}
*/
// comment below code
// chain.doFilter(request, response);
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}
I added the following code in my class after looking into few solutions but it did not work for me either.
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));
// NOTE: setAllowCredentials(true) is important,
// otherwise, the value of the 'Access-Control-Allow-Origin' header in the response
// must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// NOTE: setAllowedHeaders is important!
// Without it, OPTIONS preflight request will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(Arrays.asList(
"Authorization",
"Accept",
"Cache-Control",
"Content-Type",
"Origin",
"ajax",
"x-csrf-token",
"x-requested-with"
));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Spring Boot Version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
add #CrossOrigin("http://localhost:4200") on main method, if you want it for specific controller then add annotation on controller.
Add a #CrossOrigin annotation to any of the following:
Controller Method level - This restricts / enables cross-origin resource sharing only for this specific method.
#CrossOrigin(origins = "http://localhost:4200")
Global CORS
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:8080");
}
};
}
Note: Its important to share the complete URL (with http://) in origin
For more refer: https://spring.io/guides/gs/rest-service-cors/

Can't fix CORS error (angular + java spring)

I'm trying to request data from my backend through my frontend, but I'm getting the error:
Access to XMLHttpRequest at 'http://localhost:8081/api/transactions/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am able to get the data with postman, but not my frontend. I'm using angular and spring boot.
My application.java:
#EnableJpaRepositories
#EntityScan
#SpringBootApplication
public class KoalaTreeAccountingApplication {
public static void main(String[] args) {
SpringApplication.run(KoalaTreeAccountingApplication.class, args);
}
}
My security config:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.permitAll()
.and().csrf().disable();
}
}
My service to make the http call in angular:
#Injectable({
providedIn: 'root'
})
export class TransactionService {
baseUrl = 'http://localhost:8081/api/';
transactionUrl = this.baseUrl + 'transactions/';
constructor(private http: HttpClient, private logger : Logger){ }
getAllTransactions() : Observable<Transaction[]> {
this.logger.log("Request all transactions");
return this.http.get<Transaction[]>(this.transactionUrl);
}
getTransactionById(id : number) : Observable<Transaction> {
this.logger.log("Request transaction " + id);
return this.http.get<Transaction>(this.transactionUrl + id);
}
}
Edit: I've tried
https://spring.io/guides/gs/rest-service-cors/
Spring Security CORS filter not working
Security configuration with Spring-boot
https://stackoverflow.com/a/31748398/12025088
Protip: clean install before re-running the application after a change. I'm an idiot.
Fixed by using this instead of SecurityConfig.java:
#Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "36000");
response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
You need to configure CORS on the methods of your RestController that you want to allow it. CORS is a server response.
#CrossOrigin(origins = "http://localhost:4200")
#GetMapping("/")
public List<Transaction> findAllTransactions() {
return transactionService.findAllTransactions(); }
}

Request to one API endpoint causes 500 response; other API endpoints work

I want to accept origin as http://192.168.1.35:4200 and I created the CORSFilter like this in the springboot:
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
public CORSFilter() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "http://192.168.1.35:4200");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PATCH, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, X-Auth-Token, Origin, Content-Type, Accept, Auth_Token");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void destroy() {
}
}
And I created the request like this to call the spring rest api from angular:
getAllUsers(): void {
this.accessToken = JSON.parse(window.sessionStorage.getItem('token')).access_token;
this.httpClient.get<User[]>(`${BASE_URL}/fam-users/user?access_token=${this.accessToken}`, httpOptions).subscribe(data => {
this.dataChange.next(data);
},
(err: ApiError) => {
this.snackBar.openSnackBar(err.error.message, 'close', 'red-snackbar');
});
}
When I send request, It says that
Access to XMLHttpRequest at 'http://192.168.1.35:8080/fam-users/user?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTAwNDMwODMsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiRkFfQU1FTkQiLCJGQV9ORVciXSwianRpIjoiOWViMzZjNzAtOGUwOS00YzViLWI0OWQtNDNmZTRhOTkzNDgzIiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsicmVhZCIsIndyaXRlIiwidHJ1c3QiXX0.IETZOJE8tIqNc249HmTcJHuZpZFY1TP4PLcbqUOF3qc' from origin 'http://192.168.1.35:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But all other requests from 'http://192.168.1.35:4200' are working fine.
Can Someone guide me to solve this issue?
There is a #CrossOrigin annotation in spring boo, for example:
#CrossOrigin(origins = "http://localhost:9000")
#GetMapping("/greeting")
public Greeting greeting(#RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
for more please have a look

How to pass GenericFilterBean data to WebSecurityConfigurerAdapter in Spring Boot?

I am trying to redirect http to https in my spring boot application using:
http.requiresChannel().anyRequest().requiresSecure();
But I am getting ERR_TOO_MANY_REDIRECTS. The reason for this is that the load balancer converts all the https to http and directs the http to port 8082, therefore the app never seems to see the https.
I tried to fix this by adding isSecure before the http to https redirection, like this in my configuration:
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
//variables
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/admin/**")
.permitAll().anyRequest().authenticated().and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class)
.formLogin().loginPage("/login").permitAll().and()
.logout().logoutSuccessUrl("/");
//hsts
http.headers().httpStrictTransportSecurity()
.includeSubDomains(true).maxAgeInSeconds(31536000);
http.addFilterBefore(new IsSecureFilter(), ChannelProcessingFilter.class);
//https compulsion
if(!isSecureFilter.isSecure()) {
http.requiresChannel().anyRequest().requiresSecure();
}
}
//rest of the code
}
I am trying to use HttpServletRequestWrapper so that I can repeatedly use isSecure in WebSecurityConfiguration above through the IsSecureFilter I have created below, to prevent infinite redirects:
public class RequestWrapper extends HttpServletRequestWrapper {
private boolean isSecure;
public RequestWrapper(HttpServletRequest request) throws IOException
{
//So that other request method behave just like before
super(request);
this.isSecure = request.isSecure();
}
//Use this method to read the request isSecure N times
public boolean isSecure() {
return this.isSecure;
}
}
Below is the filter that I am trying to inject in WebSecurityConfiguration, to use it's isSecure value above :
#Component
public class IsSecureFilter extends GenericFilterBean {
private boolean isSecure;
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = new RequestWrapper((HttpServletRequest) request);
this.isSecure = req.isSecure();
chain.doFilter(req, response);
}
public boolean isSecure() {
return this.isSecure;
}
}
So running the above code and putting example.com/login in the browser does redirect to https://example.com/login, but i am still getting ERR_TOO_MANY_REDIRECTS.
I can't understand what I am doing wrong?
My first thoughts are:
Can I inject the IsSecureFilter in WebSecurityConfiguration to retrieve isSecure?
Am I adding the IsSecureFilter filter in a correct way to the configuration.
Is the wrapper filter relationship defined correctly?
EDIT
1) I changed http.addFilterAfter(new isSecureFilter(), ChannelProcessingFilter.class); to http.addFilterAfter(isSecureFilter, ChannelProcessingFilter.class);, still no effect.
2) I tried changing http.addFilterBefore(isSecureFilter, ChannelProcessingFilter.class); to http.addFilterAfter(isSecureFilter, ChannelProcessingFilter.class); but that still did not change anything.
Here is the solution to resolve this issue. Based on investigation, since 8080 and 8082 are used to identify HTTP traffic and HTTPS traffic, some code are added to check the port number instead "isSecure" to decide whether redirect HTTP request or not. The code is like following:
public class IsSecureFilter extends GenericFilterBean {
private boolean isSecure;
private int port;
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = new RequestWrapper((HttpServletRequest) request);
HttpServletResponse res = (HttpServletResponse) response;
this.isSecure = req.isSecure();
this.port = req.getLocalPort();
System.out.println("[DEBUG] : isSecure FILTER :: " + isSecure);
System.out.println("[DEBUG] : port FILTER :: " + port);
System.out.println("[DEBUG] : URL :: " + req.getRequestURL());
String url = req.getRequestURL().toString().toLowerCase();
if(url.endsWith("/login") && url.startsWith("http:") && port == 8080){
url = url.replace("http:", "https:");
String queries = req.getQueryString();
if (queries == null) {
queries = "";
} else {
queries = "?" + queries;
}
url += queries;
res.sendRedirect(url);
}
else {
chain.doFilter(req, response);
}
}
public boolean isSecure() {
return this.isSecure;
}
public boolean setIsSecure(boolean isSecure) {
return this.isSecure = isSecure;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
and remove http.requiresChannel().anyRequest().requiresSecure() in WebSecurityConfiguration class.

Enable CORS for OPTIONS request using Spring Framework

Every time I make a PUT Ajax call to my service, it return the following error:
XMLHttpRequest cannot load http://localhost:8080/users/edit. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 403.
After 2 days of investigation, I've reached to try the next solution on my code.
This is the main class where I load the necessary classes and run the application:
#SpringBootApplication
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DispatcherServletInitializer.class, OptionsController.class,Application.class);
}
}
The DispatcherServilet initializer, where I enable the dispatchOptionsRequest:
public abstract class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("dispatchOptionsRequest", "true");
super.customizeRegistration(registration);
}
}
A controller for handle all OPTIONS request:
#Controller
public class OptionsController {
#RequestMapping(method = RequestMethod.OPTIONS)
public HttpServletResponse handle(HttpServletResponse theHttpServletResponse) throws IOException {
theHttpServletResponse.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
theHttpServletResponse.addHeader("Access-Control-Max-Age", "60");
theHttpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
theHttpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
return theHttpServletResponse;
}
}
What I'm doing wrong with the configuration?
Finally, the DispatcheServlet customize initializer was the class that really solved my problem. The OPTIONS request was failing because of the optionsController I had implemented, it was wrong.
So I removed that optionsController, and just by adding the handle method in my Rest Controller for the OPTIONS request, the problem was solved:
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/users")
public class Users {
#RequestMapping(
value = "/edit",
method = RequestMethod.PUT)
public ResponseEntity<?> create(#RequestBody User user){
....
....
}
#RequestMapping(
value = "/**",
method = RequestMethod.OPTIONS
)
public ResponseEntity handle() {
return new ResponseEntity(HttpStatus.OK);
}
}
If you use a modern version of Spring (4.2) you can benefit of the #CrossOrigin.
Indeed if you use Spring < 4.2v you can create a Servlet Filter and put hear the header for CORS support like below:
package it.valeriovaudi.web.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
Copyright 2015 Valerio Vaudi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class CORSFilter implements Filter {
public static final String ACCESS_CONTROL_ALLOW_ORIGIN_NAME = "Access-Control-Allow-Origin";
public static final String DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*";
public static final String ACCESS_CONTROL_ALLOW_METHDOS_NAME = "Access-Control-Allow-Methods";
public static final String DEFAULT_ACCESS_CONTROL_ALLOW_METHDOS_VALUE = "POST, GET, OPTIONS, DELETE";
public static final String ACCESS_CONTROL_MAX_AGE_NAME = "Access-Control-Max-Age";
public static final String DEFAULT_ACCESS_CONTROL_MAX_AGE_VALUE = "3600";
public static final String ACCESS_CONTROL_ALLOW_HEADERS_NAME = "Access-Control-Allow-Headers";
public static final String DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "x-requested-with";
private String accessControlAllowOrigin = DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN_VALUE;
private String accessControlAllowMethods = DEFAULT_ACCESS_CONTROL_ALLOW_METHDOS_VALUE;
private String accessControlAllowMaxAge = DEFAULT_ACCESS_CONTROL_MAX_AGE_VALUE;
private String accessControlAllowHeaders = DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS_VALUE;
/**
* #return the method return a map that associated the name of paramiters in the web.xml to the class variable name for the header binding*/
private Map<String,String> initConfig(){
Map<String, String> result = new HashMap<>();
result.put(ACCESS_CONTROL_ALLOW_ORIGIN_NAME,"accessControlAllowOrigin");
result.put(ACCESS_CONTROL_ALLOW_METHDOS_NAME,"accessControlAllowMethods");
result.put(ACCESS_CONTROL_MAX_AGE_NAME,"accessControlAllowMaxAge");
result.put(ACCESS_CONTROL_ALLOW_HEADERS_NAME,"accessControlAllowHeaders");
return result;
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
String initParameterValue;
Map<String, String> stringStringMap = initConfig();
for (Map.Entry<String, String> stringStringEntry : stringStringMap.entrySet()) {
initParameterValue = filterConfig.getInitParameter(stringStringEntry.getKey());
// if the init paramiter value isn't null then set the value in the correct http header
if(initParameterValue!=null){
try {
getClass().getDeclaredField(stringStringEntry.getValue()).set(this, initParameterValue);
} catch (IllegalAccessException | NoSuchFieldException ignored) { }
}
}
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_NAME, accessControlAllowOrigin);
response.setHeader(ACCESS_CONTROL_ALLOW_METHDOS_NAME, accessControlAllowMethods);
response.setHeader(ACCESS_CONTROL_MAX_AGE_NAME, accessControlAllowMaxAge);
response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_NAME, accessControlAllowHeaders);
filterChain.doFilter(servletRequest, servletResponse);
}
#Override
public void destroy() {
}
}
in Spring boot you can register this filter as spring bean and Spring will register the filter for you.
I hope that this can help you.

Categories

Resources