文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

spring security 自定义Provider 如何实现多种认证

2024-04-02 19:55

关注

我的系统里有两种用户,对应数据库两张表,所以必须自定义provider 和 AuthenticationToken,这样才能走到匹配自定义的UserDetailsService。

必须自定义原因在于,security内部是遍历prodvider,根据其support 方法判断是否匹配Controller提交的token,然后走provider注入的认证service方法。

security内部认证流程是这样的

1、 Controller

用用户名和密码构造AuthenticationToken 并提交给 authenticationManager,


authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));

2、spring security

会遍历自定义和内置provider,根据provider的support方法判断入参Token所匹配provider


public boolean supports(Class<?> authentication) {
   return (EcStaffUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

3、调用匹配的provider内部认证逻辑

过程中会调用UserDetailsService.loadUserByUsername,这个service可以在SecurityConfig中配置注入到provider

4、UserDetailsService

需要我们自己查询数据库中用户对象,返回对象UserDetails,

我返回的是LoginUser ( implements UserDetails ),这样把数据库查出来用户对象加进去,方便前台Controller使用


@Override
public UserDetails loadUserByUsername(String username) //查询数据库

5、继续走spring security内部逻辑

包括判断密码是否匹配等,如果密码不匹配或帐号过期等spring会上抛异常到Controller

6、所有调用完毕就会

回到Controller的方法,并返回authentication。对于异常需要自己捕获,详情可参见后面的代码。


authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();

说明:

大部分人是在流程最前面使用filter实现各种校验,而我的项目全部是前后端分离,所以我的filter只校验token有效性,我把各种非空校验放在controller。

1、基础配置-SecurityConfig


    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;
    
    @Autowired
    @Qualifier("ecStaffDetailsServiceImpl")
    private UserDetailsService ecStaffDetailsServiceImpl;
 
    
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }
 
    
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                // CRSF禁用,因为不使用session
                .csrf().disable()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/captchaImage", "/store-api/ecommerce/login*.html",
                        "*.css",
                        "*.js"
                ).permitAll()
                .antMatchers("/profileapi-docs").anonymous()
                .antMatchers("/druid
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }
 
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
		//自定义provider及service,一套身份认证
        auth.authenticationProvider(getEcStaffUsernamePasswordAuthenticationProvider())
		//使用系统自带provider,及自定义service,另一套认证
            .userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }    
	 
    public EcStaffUsernamePasswordAuthenticationProvider getEcStaffUsernamePasswordAuthenticationProvider() {
        EcStaffUsernamePasswordAuthenticationProvider provider = new EcStaffUsernamePasswordAuthenticationProvider();
        provider.setPasswordEncoder(bCryptPasswordEncoder());
        provider.setUserDetailsService(ecStaffDetailsServiceImpl);
        return provider;
    }

2、基础配置-自定义AuthenticationToken


import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
public class EcStaffUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken{
    public EcStaffUsernamePasswordAuthenticationToken(Object principal, Object credentials) {
        super(principal, credentials);
    }
    private static final long serialVersionUID = 8665690993060353849L;   
}

3、基础配置-自定义provider


import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 
import com.ruoyi.framework.security.authToken.EcStaffUsernamePasswordAuthenticationToken;
public class EcStaffUsernamePasswordAuthenticationProvider extends DaoAuthenticationProvider{
    public boolean supports(Class<?> authentication) {
        return (EcStaffUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}

4、Controller发起身份认证


        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用EcStaffDetailsServiceImpl.loadUserByUsername
            // 因为这个自定token只被自定provider的support所支持
            // 所以才会provider中注入的EcStaffDetailsServiceImpl,在security配置文件注入的
            authentication = authenticationManager.authenticate(new EcStaffUsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {        
                //密码不匹配,需自定义返回前台消息
                throw new UserPasswordNotMatchException();
            }
            else
            {
                throw new CustomException(e.getMessage());
            }
        }        
        //登录成功
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

5、service查询数据库中用户对象


import java.util.HashSet;
import java.util.Set; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ecommerce.constant.StaffStatusConstant;
import com.ruoyi.ecommerce.domain.EcStaff;
import com.ruoyi.ecommerce.service.IEcStaffService;
import com.ruoyi.framework.security.LoginUser;
 

@Service
public class EcStaffDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(EcStaffDetailsServiceImpl.class); 
    @Autowired
    private IEcStaffService ecStaffService; 
    @Autowired
    private SysPermissionService permissionService; 
    @Override
    public UserDetails loadUserByUsername(String username)
    {
        QueryWrapper<EcStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", username);
        EcStaff user = ecStaffService.getOne(queryWrapper);
        
        if (StringUtils.isNull(user))
        {
            log.info("登录用户:{} 不存在.", username);
            throw new BaseException(MessageUtils.message("user.not.exists"));
        }
        else if (Constants.DELETED.equals(user.getDeleted()))
        {
            log.info("登录用户:{} 已被删除.", username);
            throw new BaseException(MessageUtils.message("user.password.delete"));
        }
        return createLoginUser(user);
    }
 
    
    public UserDetails createLoginUser(EcStaff user)
    {
        return new LoginUser(user, permissionService.getMenuPermission(user));        
    }
}

6、service返回的LoginUser

因为有两种用户sysuser和ecstaff,为了基于这个LoginUser统一提供getUsername方法,让他们继承或实现统一BaseUser,

可以不统一封装因为LoginUser构造方法入参是object , 即LoginUser(Object user, Set<String> permissions)


import java.util.Collection;
import java.util.Set; 
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; 
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ruoyi.ecommerce.domain.BaseUser;
 

public class LoginUser implements UserDetails
{
    private static final long serialVersionUID = 1L;
 
    
    private String token;
 
    
    private Long loginTime;
 
    
    private Long expireTime;
 
    
    private String ipaddr;
 
    
    private String loginLocation;
 
    
    private String browser;
 
    
    private String os;
 
    
    private Set<String> permissions;
 
    
    private Object user;
    
    private Class userClass;
 
    public String getToken()
    {
        return token;
    }
 
    public void setToken(String token)
    {
        this.token = token;
    }
 
    public LoginUser()
    {
    }
 
    public LoginUser(Object user, Set<String> permissions)
    {
        this.userClass = user.getClass();
        this.user = user;
        this.permissions = permissions;
    }
 
    @JsonIgnore
    @Override
    public String getPassword()
    {
        return ((BaseUser)user).getPassword();
    }
 
    @Override
    public String getUsername()
    {
        return ((BaseUser)user).getUserName();
    }
 
    
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired()
    {
        return true;
    }
 
    
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked()
    {
        return true;
    }
 
    
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired()
    {
        return true;
    }
 
    
    @JsonIgnore
    @Override
    public boolean isEnabled()
    {
        return true;
    }
 
    public Long getLoginTime()
    {
        return loginTime;
    }
 
    public void setLoginTime(Long loginTime)
    {
        this.loginTime = loginTime;
    }
 
    public String getIpaddr()
    {
        return ipaddr;
    }
 
    public void setIpaddr(String ipaddr)
    {
        this.ipaddr = ipaddr;
    }
 
    public String getLoginLocation()
    {
        return loginLocation;
    }
 
    public void setLoginLocation(String loginLocation)
    {
        this.loginLocation = loginLocation;
    }
 
    public String getBrowser()
    {
        return browser;
    }
 
    public void setBrowser(String browser)
    {
        this.browser = browser;
    }
 
    public String getOs()
    {
        return os;
    }
 
    public void setOs(String os)
    {
        this.os = os;
    }
 
    public Long getExpireTime()
    {
        return expireTime;
    }
 
    public void setExpireTime(Long expireTime)
    {
        this.expireTime = expireTime;
    }
 
    public Set<String> getPermissions()
    {
        return permissions;
    }
 
    public void setPermissions(Set<String> permissions)
    {
        this.permissions = permissions;
    }
 
    public Object getUser()
    {
        return user;
    }
 
    public void setUser(Object user)
    {
        this.user = user;
    }
 
    public Class getUserClass() {
        return userClass;
    }
 
    public void setUserClass(Class userClass) {
        this.userClass = userClass;
    }
 
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities()
    {
        return null;
    }
}

7、另一套用户controller登录认证方法

注意这里换了security提供的AuthToken,这个token会调用security内部的DaoAuthenticationProvider进行认证


        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            // 该方式使用的security内置token会使用内置DaoAuthenticationProvider认证
            // UserDetailsServiceImpl是在security config中配置的
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {               
                throw new UserPasswordNotMatchException();
            }
            else
            {                
                throw new CustomException(e.getMessage());
            }
        }       
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();// 该方法会去调用

8、另一套用户service

可参照上述service写,查询另一张用户表即可,返回UserDetails

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯