• 通过重写loadUserByUsername方法查询对应用户的关键代码


    package com.tszr.security;
    
    import com.tszr.entity.Authority;
    import com.tszr.entity.MyUser;
    import com.tszr.repository.MyUserRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Service
    public class MyUserSecurityService implements UserDetailsService {
        @Autowired
        private MyUserRepository myUserRepository;
    
        /**
         * 通过重写loadUserByUsername方法查询对应的用户
         * UserDetails是Spring Security的一个核心接口
         * UserDetails定义了可以获取用户名、密码、权限等与认证相关信息的方法
         */
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            //根据用户名(页面接收的用户名)查询当前用户
            MyUser myUser = myUserRepository.findByUsername(username);
            if(myUser == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            //GrantedAuthority代表赋予当前用户的权限(认证权限)
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            //获得当前用户权限集合
            List<Authority> roles = myUser.getAuthorityList();
    
            //将当前用户的权限保存为用户的认证权限
            for (Authority authority : roles) {
                GrantedAuthority sg = new SimpleGrantedAuthority(authority.getName());
                authorities.add(sg);
            }
            //org.springframework.security.core.userdetails.User是Spring Security的内部实现,
            //专门用于保存用户名、密码、权限等与认证相关的信息
            User su = new User(myUser.getUsername(), myUser.getPassword(), authorities);
            return su;
        }
    }
  • 相关阅读:
    向量旋转公式推导
    atan函数与atan2函数
    UVALive 7040 Color (容斥原理+逆元+组合数+费马小定理+快速幂)
    关于source insight、添加.s和.S文件,显示全部路径、加入项目后闪屏幕
    linux内核设计与实现--进程调度 系统调用
    linux内核设计与实现--进程管理
    linux命令行与shell脚本编程大全---bash shell命令
    linux内核设计与实现--从内核出发
    Linux内核学习之路
    NAND FLASH均衡算法笔记(转)
  • 原文地址:https://www.cnblogs.com/tszr/p/15984385.html
Copyright © 2020-2023  润新知