JFinal 整合 Shiro 補充密碼簡單加密方法及其餘

上一篇文章:http://my.oschina.net/stu51/blog/168739 JFinal 整合 Shiro 補充Realm類和數據庫 java

增長密碼加密及修改shiro.principal輸出值爲用戶名 數據庫

public void checklogin() {
		String pwd = new Sha256Hash(getPara("pwd"), getPara("name"), 1024).toBase64(); // 將用戶輸入密碼與用戶名salt加密
		UsernamePasswordToken token = new UsernamePasswordToken(getPara("name"), pwd);
		try {
			SecurityUtils.getSubject().login(token);
		} catch (AuthenticationException e) {
			System.out.println("用戶密碼錯誤或用戶名不存在!");
		}
		redirect("/manage/index");
	}

主要利用用戶名將密碼進行鹽值加密,在用戶註冊時一樣須要用此方法先處理用戶密碼後保存。 apache

String pwd = new Sha256Hash(getPara("pwd"), getPara("name"), 1024).toBase64(); // 將用戶輸入密碼與用戶名salt加密

 

修改Realm 緩存

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.ac.las.common.model.Adminrole;
import cn.ac.las.common.model.Adminuser;


public class ShiroDbRealm extends AuthorizingRealm {

	/**
	 * 認證回調函數, 登陸時調用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String password = String.valueOf(token.getPassword());
		// 調用操做數據庫的方法查詢user信息
		Adminuser user = Adminuser.dao.findFirst(
				"select * from adminuser where username = ?", token.getUsername());
		if (user != null) {
			if (password.equals(user.getStr("password"))) {
				return new SimpleAuthenticationInfo(user.getStr("username"), user.getStr("password"), getName());
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 受權查詢回調函數, 進行鑑權但緩存中無用戶的受權信息時調用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		Adminuser user = Adminuser.dao.findFirst("select * from adminuser where username = ?", (String) principals.fromRealm(getName()).iterator().next());
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			Adminrole role = Adminrole.dao.findById(user.getInt("roleid"));
			info.addRole(role.getStr("rolename"));
			// info.addStringPermissions( role.getPermissions()
			// );//若是你添加了對權限的表,打開此註釋,添加角色具備的權限

			return info;
		} else {
			return null;
		}
	}

}

頁面是使用 <@shiro.principal/>將會輸出username的值。 ide

初學shiro,利用其自身內置加密的方式老是調試不成功,只有將密碼加密部分單獨實現。 函數

相關文章
相關標籤/搜索