自定义GrantedAuthority

该博客介绍了如何在权限管理中自定义GrantedAuthority类,由于原类不可继承,故需要直接实现接口。内容包括自定义类的创建以及在user实体类中赋予权限值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义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)


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值