java - 如何保护已构建的 Spring Web 应用程序免受 XSS 和 CSRF 攻击?

标签 java spring spring-mvc spring-security csrf

我已经使用 spring 4.2.0.RELEASE 完全构建了我的 Web 应用程序。现在在测试过程中,我发现该应用程序容易受到 XSS 和 CSRF 攻击。我需要知道如何以最小的努力来保护它(/更改现有代码)。

我已经引用了这个spring文档:它说,

As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration.

所以我想我需要使用 spring security。所以我添加了 pom 依赖项:

    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${spring.security.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.security.version}</version>
    </dependency>

但是我引用的所有指南和教程都要求配置 Spring 安全性,并更改登录功能。基本上 Spring Security 负责登录。但我不想改变这一点,我只需要使用 Spring Security 的一些功能。基本上 CSRF token 和 XSS 相关功能,我可以这样做吗?

我添加了pom依赖,就是这样。我还需要做什么?有什么好的引用资料我找不到。我在项目中使用STS 我已经提到了this : 但它也要求 spring 身份验证。

最佳答案

首先,您需要将 Spring Security 集成到您的 Web 应用程序中。有很多关于它的教程。然后你就可以启用像

<http>
  <!-- ... -->
  <csrf disabled="true"/>
</http>

在 Spring 安全文档中,http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#csrf-configure ,指出;

As of Spring Security 4.0, CSRF protection is enabled by default with XML 
configuration. If you would like to disable CSRF protection, the corresponding 
XML configuration can be seen below.

<http>
    <!-- ... -->
    <csrf disabled="true"/>
</http>

CSRF protection is enabled by default with Java configuration. If you would like to disable 
CSRF, the corresponding Java configuration can be seen below. Refer to the Javadoc of csrf() 
for additional customizations in how CSRF protection is configured.

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable();
    }
}

关于java - 如何保护已构建的 Spring Web 应用程序免受 XSS 和 CSRF 攻击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33031077/

相关文章:

java - 使用 '%' 将 String 转换为 double

java - Lambda 重载方法

java - @Temporal 在 Spring Boot 中格式化日期

java - spring url 与当前本地日期

java - Spring Boot 单元测试 - 测试失败提示没有定义 "entityManagerFactory"bean

java - 使用 Weka 查找实例分配到的集群

java - 在jsp上通过servlet显示图像

java - 如何在来自 GET 和 POST 请求的 Spring Controller 方法之间共享信息?

java - 如何在Windows上调用与Redis集成的Restful api方法?

Spring MVC jackson消息转换器日期格式不起作用,总是返回长时间戳