Sensei Logo Sensei Hub

Recipe - Spring Security recommends DelegatingPasswordEncoder for best practices (BCrypt)

Description:
DelegatingPasswordEncoder allows more flexibility when using several encoders, for code changes, and for migrating
Level:
info
Language:
  • java
Tags:
  • Spring
  • security
  • framework specific
  • Spring Security
Documentation
Best practices for password encoding are bound to change. Spring Security provides DelegatingPasswordEncoder to facilitate implementing the recommended password storage practices. It allows easy upgrading to a newer encoding, and at the same time permit legacy encoding that cannot be migrated, to remain in the code base. PasswordEncoderFactories.createDelegatingPasswordEncoder() will create an instance of DelegatingPasswordEncoder that will default to the use of BCrypt.
Before:BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
After:PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

Resources

Recipe
id: scw:spring:security:DelegatingPasswordEncoder-bean-assignment
version: 10
metadata:
  name: Spring Security recommends DelegatingPasswordEncoder for best practices (BCrypt)
  shortDescription: DelegatingPasswordEncoder allows more flexibility when using several encoders, for code changes, and for migrating
  level: info
  language: java
  enabled: true
  descriptionFile: descriptions/SpringSecurityrecommendsDelegatePasswordEncoderforbestpracticesBCrypt.html
  tags: Spring;security;framework specific;Spring Security
search:
  assignment:
    not:
      in:
        method:
          annotation:
            type: Bean
          returnType: '{{{ type }}}'
    expressionType: org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
availableFixes:
- name: Use a customizable instance of DelegatingPasswordEncoder
  actions:
  - rewrite:
      to: |-
        java.util.Map<String, org.springframework.security.crypto.password.PasswordEncoder> encoders = new java.util.HashMap<>();
        encoders.put("{{#sed}}s/passwordencoder//g,{{#lowerCase}}{{{ typeElement }}}{{/lowerCase}}{{/sed}}", {{{ assignedExpression }}});

        org.springframework.security.crypto.password.PasswordEncoder {{{ qualifier }}} = new org.springframework.security.crypto.password.DelegatingPasswordEncoder("{{#sed}}s/passwordencoder//g,{{#lowerCase}}{{{ typeElement }}}{{/lowerCase}}{{/sed}}", encoders);
      target: self
- name: 'Create an instance of DelegatingPasswordEncoder using PasswordEncoderFactories (default: bcrypt)'
  actions:
  - rewrite:
      to: org.springframework.security.crypto.password.PasswordEncoder {{{ qualifier }}} = org.springframework.security.crypto.factory.PasswordEncoderFactories.createDelegatingPasswordEncoder();