Password encoding with Spring Data REST

前端 未结 3 1397
天涯浪人
天涯浪人 2021-01-13 03:13

How should I encode automatically the subbmitted plain password field of my entity with Spring Data REST?

I\'m using BCrypt encoder and I want to automatically encod

3条回答
  •  难免孤独
    2021-01-13 03:53

    You can implement a Jackson JsonDeserializer:

    public class BCryptPasswordDeserializer extends JsonDeserializer {
    
        public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            ObjectCodec oc = jsonParser.getCodec();
            JsonNode node = oc.readTree(jsonParser);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(node.asText());
            return encodedPassword;
        }
    }
    

    And apply it to your JPA Entity property:

    // The value of the password will always have a length of 
    // 60 thanks to BCrypt
    @Size(min = 60, max = 60)
    @Column(name="password", nullable = false, length = 60)
    @JsonDeserialize(using = BCryptPasswordDeserializer.class )
    private String password;
    

提交回复
热议问题