为了账号安全,请及时绑定邮箱和手机立即绑定

Jpa @Converter 获取实体的 id

Jpa @Converter 获取实体的 id

烙印99 2021-10-27 18:52:32
问题我需要在实体级别(而不是控制器级别)散列用户密码,@Converter 似乎是正确的选择,使用 JavaEE,没有 spring。给我看代码这里使用 Jpa AttributeConverter 的代码:import java.nio.charset.StandardCharsets;import javax.inject.Inject;import javax.persistence.AttributeConverter;import javax.persistence.Converter;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.google.common.hash.Hashing;@Converterpublic class JPACryptoConverter implements AttributeConverter<String, String> {    private static Logger logger = LoggerFactory.getLogger(JPACryptoConverter.class);    private String salt = "helloWorld";    @Inject    private UserRepository userRepository;    @Override    public String convertToDatabaseColumn(String sensitive) {        return Hashing.sha512().hashString(salt + sensitive, StandardCharsets.UTF_8).toString();    }    @Override    public String convertToEntityAttribute(String sensitive) {        String tmp = Hashing.sha512().hashUnencodedChars(sensitive).toString();        return tmp.substring(0, salt.length());    }}我想将 salt 字符串替换为用户表上实体定义的 salt,但如何获取此信息?为了获取此信息,我需要使用实体 id 访问 userRepository 并获取 salt,有没有办法使用 @Converter 查找此信息?注意:我尝试过使用生命周期侦听器、预加载、预更新、预持久化,但是因为我使用的是 jpa Criteria,所以在查询之后调用侦听器
查看完整描述

2 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

我不知道你到底想要什么,是你想要在存储到数据库之前散列用户的密码?您创建了一个转换器并想使用它?要做的是添加@Convert(converter = JPACryptoConverter.class)


@Entity

class UserEntity {


    @Column(name = "pw")

    @Convert(converter = JPACryptoConverter.class)

    private String pw;

}

并请从您的 JPACryptoConverter 中删除 @Converter。它只是:


public class JPACryptoConverter implements AttributeConverter<String, String>...

不是:


@Converter

public class JPACryptoConverter implements AttributeConverter<String, String>...


//To using Strong pw hash 

public static String hash(String plainPassword) {

    if (StringUtils.isBlank(plainPassword)) {

        throw new EmptyPasswordException("Password could not be empty");

    }

    return BCrypt.hashpw(plainPassword, BCrypt.gensalt());

}


public static boolean checkPassword(String plainPassword, String hash) {

    return BCrypt.checkpw(plainPassword, hash);

}


查看完整回答
反对 回复 2021-10-27
?
RISEBY

TA贡献1856条经验 获得超5个赞

如果用于 SpringBoot 中的身份验证,那么您应该使用 WebSecurityConfigurereAdapter 并实现配置方法。并有这样的事情:


@Override

public void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(passwordEncoder());

}


private PasswordEncoder passwordEncoder() {


    return new PasswordEncoder() {

        @Override

        public String encode(CharSequence charSequence) {

            return charSequence.toString();

        }


        @Override

        public boolean matches(CharSequence charSequence, String s) {

            return charSequence.toString().equals(s);

        }

    };

}


查看完整回答
反对 回复 2021-10-27
  • 2 回答
  • 0 关注
  • 143 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信