Asked  1 Year ago    Answers:  5   Viewed   21 times

i need to add cors filter to my spring boot web application.

i have added cors mappings as described in the following documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html

this is my config:

@configuration
@enablewebmvc
public class webmvcconfig extends webmvcconfigureradapter {

    @override
    public void addcorsmappings(corsregistry registry) {
        // @formatter:off   
        registry
            .addmapping("/**")
            .allowedorigins(crossorigin.default_origins)
            .allowedheaders(crossorigin.default_allowed_headers)
            .allowedmethods("get", "post", "put", "delete", "options")
            .maxage(3600l);
        // @formatter:on
    }

...

}

right now when i'm trying to access my api i receiving a following error:

cross-origin request blocked: the same origin policy disallows reading the remote resource at https://example.com/api/v1.0/user. (reason: cors preflight channel did not succeed).

this is a screenshot from ff console:

what am i doing wrong and how to properly configure cors headers in order to avoid this issue ?

 Answers

5

i have fixed this issue by creating a new cors filter:

@component
public class corsfilter extends onceperrequestfilter {

    @override
    protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception {
        response.setheader("access-control-allow-origin", "*");
        response.setheader("access-control-allow-methods", "get, post, put, delete, options");
        response.setheader("access-control-max-age", "3600");
        response.setheader("access-control-allow-headers", "authorization, content-type, xsrf-token");
        response.addheader("access-control-expose-headers", "xsrf-token");
        if ("options".equals(request.getmethod())) {
            response.setstatus(httpservletresponse.sc_ok);
        } else { 
            filterchain.dofilter(request, response);
        }
    }
}

and added it to securty configuration:

.addfilterbefore(new corsfilter(), channelprocessingfilter.class)

updated - more modern way nowadays which i switched to:

@configuration
@enablewebsecurity
public class websecurityconfig extends websecurityconfigureradapter {

    @override
    protected void configure(httpsecurity http) throws exception {

        http
            .cors()
        .and()

        ...
    }

    @bean
    public corsconfigurationsource corsconfigurationsource() {
        corsconfiguration configuration = new corsconfiguration();
        configuration.setallowedorigins(arrays.aslist("*"));
        configuration.setallowedmethods(arrays.aslist("get", "post", "put", "patch", "delete", "options"));
        configuration.setallowedheaders(arrays.aslist("authorization", "content-type", "x-auth-token"));
        configuration.setexposedheaders(arrays.aslist("x-auth-token"));
        urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
        source.registercorsconfiguration("/**", configuration);
        return source;
    }

}
Wednesday, June 9, 2021
 
Isky
 
1

this is a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=700837

you must enable the certificate on each port individually.

open the url in firefox and accept the certificates for https://169.254.128.2:8443 and https://169.254.128.2:8444

Sunday, August 15, 2021
 
LukeP
 
3

thanks @bavlin

to work oauth2 endpoints in local you have install certs in local jre truststore

use below command to add that in local trust store: (in command prompt)

• keytool -keystore cacerts -import -trustcacerts -file "file path to cert"

• to make it work in postman - in chrome browser , install localhost cert to “trusted root certification authorities”

Friday, October 15, 2021
 
jezrael
 
3

so, as it turns out, my update on my original post was on the right track to assume that spring security and my websecurityconfig was part of the cause.

i found the real solution on an answer here.

i needed to update my httpsecurity config to include the .cors() first:

@override
protected void configure(httpsecurity http) throws exception {
    http.cors().and()
            .authorizerequests()
            .antmatchers("/actuator/**", "/heartbeat", "/register", "/unregister").permitall()
            .anyrequest().authenticated()
            .and()
            .oauth2resourceserver()
            .jwt()
            .jwtauthenticationconverter(this.jwtauthenticationconverter());
}

after doing this, all other cors configurations were unnecessary and could be removed from my app. just add the @crossorigin annotation to any relevant controllers.

with this in place, calling my get /default-theme controller, protected by the @preauthorize(value = "hasrole('role_access')"), got rid of the no access-control-allow-origin error, and resulted in the error i expected which was a 401 response.

the underlying reason for all of this was because i was tasked with migrating this application from ldap auth to azure ad auth.

hopefully this will help someone in the future.

Sunday, December 5, 2021
 
penpen
 
4

as documentation sais :

the defaultserverwebexchange uses the configured httpmessagereader<multivaluemap<string, part>> to parse multipart/form-data content into a multivaluemap.

to parse multipart data in streaming fashion, you can use the flux returned from an httpmessagereader instead.

with few words you need to do something like this:

    @requestmapping(path = "/uploadfile", method = requestmethod.post, 
        consumes = mediatype.multipart_form_data_value)
    public flux<string> uploadfile(@requestbody flux<part> parts) {
    //...
    }

look at this example

Monday, January 3, 2022
 
LOKESH
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :