zeromemos
最好的学习方法就是输出所学的知识

Spring Security权限校验 修改loadUserByUsername方法

需要将用户权限数据封装成SimpleGrantedAuthority类型集合传到用户对象里

没有存权限数据的方法http://www.zeromemos.com/index/article/read.html?id=368

新增代码后如下

package com.atguigu.auth.service.impl;

import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.model.system.SysUser;
import com.atguigu.security.custom.CustomUser;
import com.atguigu.security.custom.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //getByUsername方法需要在sysUserService里定义
        SysUser sysUser = sysUserService.getByUsername(username);
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在!");
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }

        //根据用户ID查询操作权限数据 findUserPermsByUserId()是查询用户权限的方法,需要自己定义
        List<String> userPermsList = sysMenuService.findUserPermsByUserId(sysUser.getId());

        //创建SimpleGrantedAuthority list集合用于封装最终权限数据
        ArrayList<SimpleGrantedAuthority> authList = new ArrayList<>();

        //封装最终权限数据
        for (String perms : userPermsList) {
            authList.add(new SimpleGrantedAuthority(perms.trim()));
        }
        //自定义的CustomUser类,实现了UserDetails接口
        return new CustomUser(sysUser, authList);
    }
}
评论区

关于我们

本站主要用于记录个人学习笔记,网站开发中,如需以前站内资料请加QQ群272473835索取。注册账号仅提供回帖功能,可不注册!

微信公众号