//自定义验证器
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserServiceImpl userServiceImpl;
@Autowired
private PowerServiceImpl powerServiceImpl;
@Autowired
private RoleServiceImpl roleServiceImpl;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//1.获得登录用户
User user = (User)principals.getPrimaryPrincipal();
//2.工具用户id得到用户权限码
Set<String> code = powerServiceImpl.getUserPermissionCode(user.getUserId());
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//根据用户id查找所有的rooles
Set<String> role = roleServiceImpl.findRoleNameByUserId(user);
simpleAuthorizationInfo.setRoles(role);//角色
simpleAuthorizationInfo.setStringPermissions(code);//权限码
return simpleAuthorizationInfo;
}
//登记认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证方法..");
//得到传进来的用户名
String username =(String) token.getPrincipal();
//String password="fromDB";
User user2 = new User();
user2.setUserName(username);
User user = userServiceImpl.findByUserName(user2);
String password=user.getUserPassword();
Object principal=token.getPrincipal();
Object credentials=password;
String realmName=getName();//UserRealm代理类的名字com.test.shiro.UserRealm_0,可能是线程名
ByteSource salt = ByteSource.Util.bytes(username);
//由shiro完成验证
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, credentials, salt, getName());//
//返回登记信息
return info;
}
public static void main(String[] args) {
ByteSource salt = ByteSource.Util.bytes("admin");
SimpleHash simpleHash = new SimpleHash("MD5", "1234567890", salt, 1024);
System.out.println(simpleHash);
}
public void claerCache(){
super.clearCache(SecurityUtils.getSubject().getPrincipals());
}
}
controller使用
@RequestMapping("/login.do")
public String login(String username,String password,ModelMap map){
System.out.println("username="+username+",password="+password);
//1.获取subject
Subject subject = SecurityUtils.getSubject();
//2.判断是否登录
if(!subject.isAuthenticated()){
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
} catch (AuthenticationException e) {
logger.error("登录失败");
return "redirect:application/common/login.jsp";
}
}
User user = (User)SecurityUtils.getSubject().getPrincipal();//
List<Menu> menuList = menuServiceImpl.getMenusListByUserId(user.getUserId());
HashMap<String, Object> parentMenuMap = new HashMap<String,Object>();
for (Menu menu : menuList) {
parentMenuMap.put(String.valueOf(menu.getMenuParentId()), menu.getMenuName());
}
map.put("menuList", menuList);
map.put("parentMenuMap", parentMenuMap);
return "index";
}