使用PasswordEncoder - 如何存储盐

时间:2017-04-29 08:00:39

标签: java spring

我在Spring启动应用程序中使用以下Web安全配置:

@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired 
    private AccountRepository accountRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/login").permitAll()
            .and()
            .authorizeRequests()
                .antMatchers("/signup").permitAll()
            .and()
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login").deleteCookies("auth_code").invalidateHttpSession(true)
            .and()
            // We filter the api/signup requests
            .addFilterBefore(
                new JWTSignupFilter("/signup", authenticationManager(), accountRepository),
                UsernamePasswordAuthenticationFilter.class)
            // We filter the api/login requests
            .addFilterBefore(
                new JWTLoginFilter("/login", authenticationManager()),
                UsernamePasswordAuthenticationFilter.class)
            // And filter other requests to check the presence of JWT in
            // header
            .addFilterBefore(new JWTAuthenticationFilter(userDetailsServiceBean()),
                UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder());
    }

    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return new CustomUserDetailsService(accountRepository);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
}

如您所见,我使用BCryptPasswordEncoder。

我有两个问题:

1. BCryptPasswordEncoder的盐存储在哪里?根据我的发现,它每次都是随机的,它存储在数据库的某个地方,但我没有为它定义任何列。我对它是如何工作感到困惑。

2.我有一个注册过滤器:

public class JWTSignupFilter extends AbstractAuthenticationProcessingFilter {

    private AccountRepository accountRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public JWTSignupFilter(String url, AuthenticationManager authManager,
            AccountRepository accountRepository) {
        super(new AntPathRequestMatcher(url, "POST"));
        setAuthenticationManager(authManager);
        this.accountRepository = accountRepository;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
            HttpServletResponse res) throws AuthenticationException,
            IOException, ServletException {

        CustomUserDetails creds = new ObjectMapper().readValue(
                req.getInputStream(), CustomUserDetails.class);

        if (accountRepository.findByUsername(creds.getUsername()) != null) {
            throw new AuthenticationException("Duplicate username") {
                private static final long serialVersionUID = 1L;
            };
        }

        CustomUserDetails userDetails = new CustomUserDetails(
                creds.getUsername(), creds.getPassword(), true, true, true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("USER_ROLE"));

        accountRepository.save(userDetails);

        return getAuthenticationManager().authenticate(
                new UsernamePasswordAuthenticationToken(creds.getUsername(),
                        creds.getPassword()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
            HttpServletResponse res, FilterChain chain, Authentication auth) {
        TokenAuthenticationService.addAuthentication(res, auth.getName());
    }
}

如您所见,我创建了一个新的UserDetails并将其保存在帐户存储库中。

如果我在创建UserDetails对象时编码密码,它将创建与登录时不同的密码。(借用的passowrds不同)我认为这应该是因为使用了不同的盐。

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

Bcrypt includes batteries:通常保存在数据库中的文本包含salt和迭代次数。有online generators可以显示它。例如,给定秘密P@ssw0rd这里是如何序列化(4次迭代):

$2a$04$tpwXnhoO89cja8UZw3.hpulcAGzL1ps5cqzTLubh60csfEwna4N3W
$2a$04$VuLYo3y8e1ZITJPgW8LliOzdRa220D0frl5oSPQeFxAOlmvmsTCsK
$2a$04$bkChnYI84W3P3DW8YZrQc.yarPrW9kCDRAEp8ZKlap2BiO2Y.ThNa
...

引用this answer

  
      
  • 2a标识bcrypt算法版本
  •   
  • 04是成本因素;使用密钥导出函数的2 4 次迭代
  •   
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa是salt和密文,在修改后的Base-64中连接和编码。前22个字符解码为盐的16字节值。其余字符是要进行身份验证的密文。
  •