簡體   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