roberto
roberto

Reputation: 89

Disable csrf using Java configuration

Good Day,

I am trying to learn Spring. I am currently doing this guide: http://spring.io/guides/gs/consuming-rest/

I have followed all instructions, however, when I try to run the application, 403 Forbidden is displayed.

I searched the net and found out that it is due to the csrf protection. And so, I proceeded to search the net how to disable csrf. Here is my Java configuration:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable();
    }
}

My question is, how do I use this configuration? Specifically, at which part of the code should I insert it?

Here are the other 2 classes as stated in the tutorial. All of them belong to the same package (Hello).

@JsonIgnoreProperties(ignoreUnknown = true)
public class Page {
    private String name;
    private String about;
    private String phone;
    private String website;

    public String getName() {
        return name;
    }

    public String getAbout() {
        return about;
    }

    public String getPhone() {
        return phone;
    }

    public String getWebsite() {
        return website;
    }
}

public class Application {

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);
        System.out.println("Name:       " + page.getName());
        System.out.println("About:      " + page.getAbout());
        System.out.println("Phone:      " + page.getPhone());
        System.out.println("Website:    " + page.getWebsite());
    }

}

Upvotes: 4

Views: 4045

Answers (2)

fjkjava
fjkjava

Reputation: 1464

Make sure that your url is valid.

In my case the url was generated by code and was in different case so I got 403 forbidden error. Spend lot of time trying to fix the issue by enabling security config.

Upvotes: 0

Nitin Arora
Nitin Arora

Reputation: 2668

Add @Configuration on the WebSecurityConfig class and it will be automatically scanned when you will launch your Spring Application. You don't need to write any code.

Here is the code with @Configuration

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable();
    }
}

Upvotes: 1

Related Questions