springboot在集成shiro的时候,要编写realm。错误实例:
/* //有可能是注入失败的
@Autowired
UserDao userMapper;
@Autowired
MenuService menuService;*/
/**
* 授权
* @param arg0
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
UserDO userDO = (UserDO)SecurityUtils.getSubject().getPrincipal();
Long userId = userDO.getUserId();
MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
Set<String> perms = menuService.listPerms(userId);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(perms);
return info;
}
使用@Autowired注入用户dao有可能失败,是因为Shiro框架初始化比Spring框架的某些部件早,导致使用@Autowire注入Shiro框架的某些类还没有被Spring正确初始化。
解决办法:
使用ApplicationContextRegister.getBean()方法,手动获取需要的注入的类,如下代码:
/**
* 认证
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
Map<String, Object> map = new HashMap<>(16);
map.put("username", username);
String password = new String((char[]) token.getCredentials());
UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
// 查询用户信息
UserDO user = userMapper.list(map).get(0);
// 账号不存在
if (user == null) {
throw new UnknownAccountException("账号或密码不正确");
}
// 密码错误
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("账号或密码不正确");
}
// 账号锁定
if (user.getStatus() == 0) {
throw new LockedAccountException("账号已被锁定,请联系管理员");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}