shiro自定義密碼驗證

首先創建一個自定義的驗證類

package com.wsmail.shiroController;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha384Hash;

/**
 * 自定義 密碼驗證類
 * @author q
 *
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
	 @Override
	    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
	        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

	        Object tokenCredentials = encrypt(String.valueOf(token.getPassword()));
	        Object accountCredentials = getCredentials(info);
	        //將密碼加密與系統加密後的密碼校驗,內容一致就返回true,不一致就返回false
	        return equals(tokenCredentials, accountCredentials);
	    }

	    //將傳進來密碼加密方法
	    private String encrypt(String data) {
	        String sha384Hex = new Sha384Hash(data).toBase64();//這裏能夠選擇本身的密碼驗證方式 好比 md5或者sha256等
	        return sha384Hex;
	    }
}




而後在 ShiroDbRealm類裏 加個


/**
	 * 設定Password校驗.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
//該句做用是重寫shiro的密碼驗證,讓shiro用我本身的驗證
		setCredentialsMatcher(new CustomCredentialsMatcher());

	}



同時在新增用戶的時候密碼保存用 以下方式 以此進行驗證和數據庫裏的密碼的一致

...
psu.setPwd(new Sha384Hash(psu.getPwd()).toBase64());
...
save(psu);
相關文章
相關標籤/搜索