java - 使用 Java 配置禁用 csrf

标签 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 个类。它们都属于同一个包(你好)。

@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());
    }

}

最佳答案

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

这是带有@Configuration的代码

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

关于java - 使用 Java 配置禁用 csrf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875589/

相关文章:

Java - 解析字符串 - String.split() 与 Pattern 和 Matcher

导出为 jar 后,Java 找不到文件

java - org.hibernate.hql.ast.QuerySyntaxException : TABLE NAME is not mapped

Spring Boot 2 - 将 Mono 转换为 rx.Observable?

spring - 让 Spring RestTemplate 使用内存中的 pem 证书(不在磁盘上)

java - 在 spring Roo > 1.1.5 中找不到 RooEntity 注释

java - Thymeleaf Rich HTML 电子邮件错误

java - TestNG:如何在命令行上放置 java 方法的参数?

java - 在 Java 中避免 'instanceof'

java - Spring Boot 数据 JPA : No qualifying bean of type 'java.util.Set<javax.persistence.EntityManager>' available