上一篇文章: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,利用其自身内置加密的方式老是调试不成功,只有将密码加密部分单独实现。 函数