首页 > 解决方案 > SpringBoot 2.0基础认证如何加速?

问题描述

我最近将 Spring Boot 应用程序从 v1.5 更新到 v2.0.3。它是一个应用程序,其方法公开为 REST 端点并受基本 HTTP 身份验证保护。用户名和密码硬编码在应用程序加载的属性文件中。

自更新以来,响应时间增加了近 200 毫秒,处理请求的 98% 时间都花在了 BasicAuthenticationFilter.doFilter() 中。

新遗物交易明细

更具体地说,花费时间对请求中的密码进行编码,以将其与配置提供的密码进行比较。

视觉虚拟机详细信息

这是 SecurityConfig 类的摘录:

@EnableWebSecurity
@PropertySource("classpath:auth/auth.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

     @Value("${user.name}")
     private String userName;
     @Value("${user.password}")
     private String userPassword;
     @Value("${user.roles}")
     private String[] userRoles;

     @Override
     protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        UserDetails user = User.withUsername(userName).password(encoder.encode(userPassword)).roles(userRoles).build();
        auth.inMemoryAuthentication().withUser(user);
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        //make sure that the basic authentication header is always required
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //set the correct authentication entry point to make sure the 401 response is in JSON format
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint());

        //enable http basic authentication
        http.httpBasic();

        //make sure authentication is required for all requests except /actuator/info
        http.authorizeRequests().antMatchers("/actuator/info").permitAll().anyRequest().authenticated();
        http.authorizeRequests().antMatchers("/actuator/**").hasAnyRole("MONITOR", "ACTUATOR");

        //disable the form login since this is a REST API
        http.formLogin().disable();

        //disable csrf since this is a REST API
        http.csrf().disable();
    }
}

为了验证这是由于 Spring Boot 更新,我在本地恢复了更改并运行了一些测试。响应时间除以 4。

我已经尝试了一些方法,但都没有改善响应时间:

我可以做些什么来加快身份验证过滤器的速度吗?

标签: spring-bootspring-security

解决方案


bcrypt 是一个故意缓慢的散列函数。虽然在密码散列方面这种缓慢听起来很矛盾,但这并不是因为好人和坏人都变慢了。如今,大多数密码攻击都是暴力字典攻击的某种变体。这意味着攻击者将像好人一样通过散列来尝试许多候选密码。如果匹配,则密码已被破解。

但是,如果坏人每次尝试都放慢速度,那么在进行数百万次尝试时会放大,通常会阻止攻击。然而,好人在尝试登录时可能不会注意到一次尝试。

所以基本上 brypt 编码器内额外的 200 毫秒处理时间是故意的,并且是安全的一部分 通过加速它(如使用缓存),您会降低应用程序的安全级别。

- - 编辑:

顺便提一句。仍然有一种快速且安全的方法来评估密码匹配:使用一些缓存服务(就像这里的其他答案一样),但将匹配的值存储在缓存中!!!这样,如果用户提供了一个有效的密码,它只会被缓慢评估一次——在第一次——但他随后的所有登录都会很快。但是,如果攻击者尝试使用暴力破解,那么他的所有尝试将花费 200 毫秒。


推荐阅读