如何执行基本的 Spring Boot 应用程序安全性 [英] How to perform a basic Spring Boot application security

查看:60
本文介绍了如何执行基本的 Spring Boot 应用程序安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在生产环境中部署我的 Spring 应用程序,我希望包含一些基本和可靠的安全措施.

首先,我扩展 WebSecurityConfigurerAdapter到我的SecurityConfiguration.java

@EnableWebSecurity公共类 SecurityConfiguration 扩展了 WebSecurityConfigurerAdapter {@自动连线UserDetailsS​​ervice userDetailsS​​ervice ;@覆盖protected void configure(AuthenticationManagerBuilder auth) 抛出异常 {//TODO 自动生成的方法存根auth.userDetailsS​​ervice(userDetailsS​​ervice);}@覆盖protected void configure(HttpSecurity http) 抛出异常 {//TODO 自动生成的方法存根http.csrf().disable().authorizeRequests().antMatchers("/admin").hasAuthority("ADMIN").antMatchers("/ekab").hasAuthority("EKAB").antMatchers("/dimos").hasAuthority("DIMOS").antMatchers("/","/users/**","/aeds/**","/events/**","/reports/**","*/static/**").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/dashboard",true).permitAll().and().注销().permitAll();}@豆公共密码编码器 getPasswordEncoder() {返回 NoOpPasswordEncoder.getInstance();}}

在生产环境 CSRF 应该启用,虽然我现在不处理任何 csrf 令牌

  • GET 端点:请注意,/users/** 包含一些 GET 端点,其中包含用户信息,我可以限制访问他们的人吗?

  • POST 端点:我还找到了一些方法来保护 POST,使用JSON Web Token ,这是最佳实践吗?

Spring 还提供了 OAuth2.0RSALDAP 等依赖项以增强安全性.

我应该使用哪个?这些是否可以防止 DDOS 攻击以及蛮力攻击?

我是否必须在应用程序的部署环境中进行修改?

解决方案

Spring Security 提供了各种默认的安全攻击实现来确保应用程序的安全.

既然你要求包括一些基本和可靠的安全措施.下面是我的一些想法,可以稍微改进一下.

  1. 如您所说,您已禁用CSRF 令牌",当您认为您的应用程序应该高度安全时,这并不好.通常,大多数人禁用(在演示代码中),因为他们将无法使用 GET 方法调用 /logout URL,因为它要求您通过POST 带有 _csrf 令牌.很好,你已经在生产中照顾到了.

  2. 会话固定攻击:这是一种攻击类型,可以通过提供同一网站的 URL 并将 JSESSIONID 附加到 URL 中来窃取您当前的会话,使用 URL 重写方法.Spring Security Framework 默认会处理这个问题,一旦用户登录它就会迁移 session.相应的配置是 -

    http.sessionManagement().sessionFixation().migrateSession()

  3. 保护会话 cookie:恶意脚本可以从浏览器端读取您的 cookie 信息,因此您需要确保您的 cookie 是安全的并且可以通过服务器端代码访问它们HttpOnly.为此,您可以在 application.properties 中使用以下配置 -

    server.servlet.session.cookie.http-only=true

  4. 在 Https 上运行您的应用:确保您在生产中使用 https,在这种情况下,您只能通过在应用程序中添加以下配置来强制您的 cookie 通过 https 协议传输.属性.

     server.servlet.session.cookie.secure=true

    并强制 https 连接在 configure() 方法中添加以下行(但这还不够,因为您还必须使用 keytool 设置公钥/私钥)

     http.requiresChannel().requiresSecure();

  5. 应用 CSP: 用户内容安全策略可避免任何 XSS 攻击.Spring security 默认提供各种安全头.但它不添加内容安全策略标头,您可以将它们添加到您的安全配置文件中,如下所示

     @EnableWebSecurity公共类 WebSecurityConfig 扩展WebSecurityConfigurerAdapter {@覆盖受保护的无效配置(HttpSecurity http)抛出异常{http.headers().contentSecurityPolicy("script-src'自我' https://myclientscriptlocation.example.com;对象源https://myclientsideplugins.example.com;报告-uri/cspreport-端点/");}

    }

  6. 密码散列:您没有使用安全配置.在将密码存储到数据库中时,您必须保持密码散列.

  7. 保护您的 application.properties' 安全性不仅应防止外部人员使用,还应防止内部人员使用.像数据库密码或任何其他配置密码的加密和解密.按照此处了解如何保护您的应用程序属性.

<块引用>

GET 端点:注意/users/** 包含一些 GET 端点包含用户信息,我可以限制谁访问他们?

是的,您可以申请.但这取决于您在这里想要什么.我能想到的一个例子是,IP 地址过滤.例如,如果您希望只有美国境内的用户可以访问,或者您知道用户的 IP 范围等.

 .antMatchers("/foos/**").hasIpAddress("xx.xxx.xxx.xx")

<块引用>

POST Endpoints:我还找到了一些方法来使用JSON Web Token ,这是最佳实践吗?

JWT 主要用于 RESTful Web 服务.如果您的应用程序暴露了其余端点并需要经过身份验证的访问,那么 JWT 是最佳选择.

<块引用>

Spring 还提供了 OAuth2.0、RSA、LDAP、依赖项来增强安全.

这些是不同的身份验证和授权方式.其中一些有多个流程来进行身份验证和授权,但当它们被外部用户访问时,将应用相同的安全因素.

这完全取决于您的项目需求是否需要它们.例如,如果您正在开发一个供内部组织使用的应用程序,其中用户/员工在组织级别设置了所有内容,并且您希望每个人都访问此应用程序,那么 LDAP 集成会更好.

当您有多个微服务时,OAuth2.0 更好

<块引用>

这些是否可以防止 DDOS 攻击以及蛮力攻击?

没有.这应该通过调整各种安全参数来解决,例如限制会话时间、检查安全标头、处理内存泄漏、为 POST 请求应用超时以便没有人可以发布巨大的请求负载等.你必须做一些为减轻此类安全攻击而开展的工作.

PS:从安全配置中删除 permitAll().

.defaultSuccessUrl("/dashboard",true).permitAll()

I'm looking forward to deploying my Spring Application on a production environment and i'd like to include some basic and solid security measures.

First things first, i extended WebSecurityConfigurerAdapter into my SecurityConfiguration.java

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService ;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable().authorizeRequests()
        .antMatchers("/admin").hasAuthority("ADMIN")
        .antMatchers("/ekab").hasAuthority("EKAB")
        .antMatchers("/dimos").hasAuthority("DIMOS")
        .antMatchers("/","/users/**","/aeds/**","/events/**","/reports/**","*/static/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin().loginPage("/login")
    .defaultSuccessUrl("/dashboard",true)
        .permitAll()
        .and()
    .logout()
        .permitAll();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }


}


On a production environment CSRF should be enabled, although i don't handle any csrf tokens for now

  • GET Endpoints: Note that /users/** contains some GET endpoints containing User Information, can i apply limitations to who visits them?

  • POST Endpoints: I've also found some ways to secure POST by using a JSON Web Token , is it a best practice?

Spring also provides OAuth2.0 , RSA, LDAP, dependencies to enhance security.

Which one should i use? Does these prevent DDOS attacks as well as brute force attacks?

Do i have to make modifications in the application's deployment environment?

解决方案

Spring Security provides various default security attack implementation to make sure the application is secured.

Since you asked to include some basic and solid security measures. Below are a few of my thoughts which can improve a bit.

  1. As you told, You have disabled 'CSRF token' which is not good when you think your application should be highly secured. Usually, most of the people disable(in demo code) because they won't be able to call /logout URL with the GET method as it requires you to submit it via POST with _csrf token. Good that you have taken care of in production.

  2. Session Fixation Attack: This is the type of attack where one can steal your current session by offering their URL of the same website and append JSESSIONID into URL, with the URL rewrite approach. Spring Security Framework has taken care of this by default and it migrates the session once the user logs in. The corresponding configuration would be -

    http.sessionManagement()
      .sessionFixation().migrateSession()
    

  3. Securing session cookie: Malicious script can read your cookie information from the browser end so you need to make sure that your cookie is secured and are accessible by server-side code by making them HttpOnly. For that, you can use the below config in your application.properties -

    server.servlet.session.cookie.http-only=true
    

  4. Running your app on Https: Make sure that you use https in production and also in that case you can force your cookies to travel over https protocol only by adding below config in your application.properties.

     server.servlet.session.cookie.secure=true
    

    and to force https connection add below lines in configure() method (this won't be enough though because you have to get your public/private key setup also using keytool)

       http.requiresChannel().requiresSecure();
    

  5. Applying CSP: User Content security policy to avoid any XSS attacks. Spring security by default provides various security headers. But it does not add Content security policy headers you can add them in your security config file like below

     @EnableWebSecurity
     public class WebSecurityConfig extends
     WebSecurityConfigurerAdapter {
     @Override
     protected void configure(HttpSecurity http)
     throws Exception {
     http.headers().contentSecurityPolicy("script-src
    'self' https://myclientscriptlocation.example.com; object-src
     https://myclientsideplugins.example.com; report-uri /cspreport-endpoint/");
    }
    

    }

  6. Password hashing: Which you are not using your security config. You have to keep password hashed while storing them into the database.

  7. Securing your application.properties' Security should be applied not only from outsiders, but it should also be protected from insiders as well. Like encryption and decryption of database passwords or any other config passwords. Follow here on how to secure your application properties.

GET Endpoints: Note that /users/** contains some GET endpoints containing User Information, can I apply limitations to who visits them?

Yes, you can apply. But that depends on your requirement what you want here. One example that I can think of is, IP Address filtering. Like if you want only those users can access which are in the US or if you know the IP range of user etc.

  .antMatchers("/foos/**").hasIpAddress("xx.xxx.xxx.xx")

POST Endpoints: I've also found some ways to secure POST by using a JSON Web Token , is it a best practice?

JWT mostly used in RESTful web services. If your application is exposing rest endpoints and requires authenticated access then JWT is the best option.

Spring also provides OAuth2.0, RSA, LDAP, dependencies to enhance security.

These are different ways of authentication and authorization. Some of them has multiple flows to do authentication and authorization but The same security factors would be applied to these when they are accessed by outside the users.

It totally depends on your project requirement whether you need them or not. For example, if you are developing an application for internal organization use where user/employee has everything set up at the organization level and you want everyone to access this application then LDAP integration is better.

OAuth2.0 is better when you have multiple microservices + you want any social login implementation like Login with Google or Login with Facebook then you can follow OAuth2.0 integration

Does these prevent DDOS attacks as well as brute force attacks?

No. This should be taken care of by tuning various security parameters like limiting the session time, checking security headers, handling memory leaks, applying timeout for POST requests so that no one could post a huge request payload, etc. You have to do a bit of leg work to mitigate such security attacks.

PS: Remove permitAll() from security configuration.

.defaultSuccessUrl("/dashboard",true)
    .permitAll()

这篇关于如何执行基本的 Spring Boot 应用程序安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆