自定义GrantedAuthority
1.工作时需要返回角色的id,这是需要重写GrantedAuthority接口
2.常用SimpleGrantedAuthority类
public final class SimpleGrantedAuthority implements GrantedAuthority { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String role; public SimpleGrantedAuthority(String role) { Assert.hasText(role, "A granted authority textual representation is required"); this.role = role; } public String getAuthority() { return role; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof SimpleGrantedAuthority) { return role.equals(((SimpleGrantedAuthority) obj).role); } return false; } public int hashCode() { return this.role.hashCode(); } public String toString() { return this.role; }
}
这个类不能被继承因此自定义类实现GrantedAuthority接口
3.自定义GrantedAuthority类
import org.springframework.security.core.GrantedAuthority; import java.util.HashMap; import java.util.Map; public class SimpleGrantedAuthorityWithRoleId implements GrantedAuthority { Map<String,Object> role=new HashMap<String,Object>(); public SimpleGrantedAuthorityWithRoleId(String roletext,int id){ role.put("text",roletext); role.put("id",id); } @Override public String getAuthority() { return (String)role.get("text"); } public Map<String,Object> getRole(){ return role; } }
4.service处理权限信息
private List<? extends GrantedAuthority> extractFromRoles(List<Role> roleList) { List<SimpleGrantedAuthorityWithRoleId> authorities = new ArrayList<>(); for(Role role :roleList){ authorities.add(new SimpleGrantedAuthorityWithRoleId("ROLE_"+role.getRoleName(),role.getId())); } return authorities; }
5.给user实体类赋值
public List<User> getAll(PageBean pageBean) { List<User> list=new ArrayList(); for (SimpleUser simpleUser:simpleUserDao.getAll(pageBean)) { User user=new User(simpleUser); user.setRoleList(userRoleServiceTemp.getUserRoles(simpleUser.getId())); List<Role> roleList = roleDao.getRolesByUserID(simpleUser.getId()); user.setGrantedAuthorities(extractFromRoles(roleList)); list.add(user); } return list; }6.前端返回带roleId的List(authorities中的id)