package com.hbue.demo2;
import com.hbue.demo2.model.Permission;
import com.hbue.demo2.model.Role;
import com.hbue.demo2.model.User;
import com.hbue.demo2.service.UserService;
import org.apache.shiro.authc.*;
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 org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* 定义自定义授权类
*/
public class AuthRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user=(User) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
List<String> permissionList=new ArrayList<>();
Set<Role> roleSet=user.getRoles();
if (!CollectionUtils.isEmpty(roleSet)){
for (Role role:roleSet){
Set<Permission> permissionSet=role.getPermissions();
if (!CollectionUtils.isEmpty(permissionSet)){
for (Permission permission:permissionSet){
permissionList.add(permission.getName());
}
}
}
}
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
info.addStringPermissions(permissionList);
return info;
}
//认证登陆
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
String username=usernamePasswordToken.getUsername();
User user=userService.finByUsername(username);
return new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName());
}
并没有将 前端获取的值传入到 UsernamePasswordToken中导致空指针异常