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);
相关文章
相关标签/搜索