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

Spring Security自定义loadUserByUsername

根据用户名查询出用户对象:loadUserByUsername


使用接口+实现类的形式

接口UserDetailsService,要继承Spring Security里的UserDetailsService

package com.atguigu.security.custom;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public interface UserDetailsService extends org.springframework.security.core.userdetails.UserDetailsService {
    //返回是的流程中的用户对象:UserDetails
    @Override
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

实现类UserDetailsServiceImpl,传入String username,返回UserDetails对象

这个实现类也可以直接实现Spring Security里的UserDetailsService,就不需要上面自己创建的UserDetailsService接口了

package com.atguigu.auth.service.impl;

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.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

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

    @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("账号已停用");
        }
        //自定义的CustomUser类,实现了UserDetails接口
        return new CustomUser(sysUser, Collections.emptyList());
    }
}

sysUserService.getByUsername(username)的定义,就是根据用户名查询数据库中的用户

@Override
    public SysUser getByUsername(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = baseMapper.selectOne(wrapper);
        return sysUser;
    }

CustomUser类的定义:http://www.zeromemos.com/index/article/read/id/369.html

评论区

关于我们

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

微信公众号