使用Java配置禁用csrf

时间:2015-04-26 08:52:27

标签: java spring

美好的一天,

我正在努力学习Spring。 我目前正在执行此指南:http://spring.io/guides/gs/consuming-rest/

我已按照所有说明操作,但是,当我尝试运行该应用程序时, 显示403 Forbidden。

我在网上搜索,发现这是由于csrf保护。 所以,我继续搜索网络如何禁用csrf。 这是我的Java配置:

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

我的问题是,如何使用此配置? 具体来说,我应该在哪部分代码中插入它?

以下是教程中所述的其他2个类。所有这些都属于同一个包(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());
    }

}

2 个答案:

答案 0 :(得分:1)

@Configuration类上添加WebSecurityConfig,当您启动Spring应用程序时,它将自动扫描。您不需要编写任何代码。

以下是@Configuration

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

答案 1 :(得分:0)

确保您的网址有效。

在我的情况下,url是由代码生成的,并且在不同的情况下因此我得到403禁止错误。花费大量时间尝试通过启用安全配置来解决问题。

相关问题