tuha21
tuha21

Reputation: 21

How to debug No 'Access-Control-Allow-Origin' header is present on the requested resource

This is backend configuration

@Override
    public void configure(AuthenticationManagerBuilder auth) {
        try {
            auth.inMemoryAuthentication()
            .withUser("user1").password(bcpe.encode("123")).roles("USER")
            .and()
            .withUser("user2").password(bcpe.encode("123")).roles("USER", "GUEST")
            .and()
            .withUser("user3").password(bcpe.encode("123")).roles("USER", "GUEST", "ADMIN");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void configure(HttpSecurity http) {
        try {
            http.csrf().disable().cors().disable();
            http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().permitAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

This is frontend fetch

var myHeaders = new Headers();
        myHeaders.append("Authorization", "Basic " + base64.encode("user3:123"));
        myHeaders.append("Content-Type", "application/json");
        myHeaders.append("Cookie", "JSESSIONID=9715BDB472F3B44BCE6ADEDD9FE90961");

        var requestOptions = {
            method: 'GET',
            headers: myHeaders,
            redirect: 'follow'
        };

        fetch("http://localhost:8080/admin/account", requestOptions)
            .then(response => response.text())
            .then(result => console.log(result))
            .catch(error => console.log('error', error));

And I recive err Access to fetch at 'http://localhost:8080/admin/account' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Thanks!

Upvotes: 2

Views: 546

Answers (1)

Stefan Etzelstorfer
Stefan Etzelstorfer

Reputation: 29

I assume that you are using Google Chrome. Chrome does not allow this due to security guidelines. Try and install the following plugin: https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc

Upvotes: 1

Related Questions