上一篇文章: JFinal 整合 Shiro 补充Realm类和数据库
增加密码加密及修改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"); }
主要利用用户名将密码进行盐值加密,在用户注册时同样需要用此方法先处理用户密码后保存。
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的值。
初学shiro,利用其自身内置加密的方式总是调试不成功,只有将密码加密部分单独实现。