繁体   English   中英

JPA @Converter获取实体的ID

[英]Jpa @Converter get id of entity

问题

我需要在实体级别(而不是在控制器级别)上哈希用户密码,而@Converter似乎是正确的选择,对于JavaEE,没有弹性。

给我看代码

这里使用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;

@Converter
public 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());
    }
}

我想将盐字符串替换为用户表上的实体定义的盐,但是如何获取此信息?

为了获取此信息,我需要使用实体ID访问userRepository并获取salt,有一种方法可以使用@Converter查找此信息?

注意:我已经尝试使用生命周期侦听器,预加载,预更新,预定义器,但是由于我使用的是jpa Criteria,因此在查询后调用侦听器

我不确切知道您想要什么,是要在存储到数据库之前对用户的pw进行哈希处理吗? 您创建了转换器并想使用它吗? 要做的事情是添加@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);
}

如果在SpringBoot中用于身份验证,则应使用WebSecurityConfigurereAdapter并实现configure方法。 并具有以下内容:

@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);
        }
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM