Spring Security OAuth2实现多用户类型认证与多用户类型token刷新(新)

此方法基于覆盖源码路径实现,以最少的配置完成Spring Security OAuth2实现多用户类型认证与多用户类型token刷新

Spring Security OAuth2实现多用户类型认证(新)

1. 在src/main/java目录下新建org/springframework/security文件夹

在这里插入图片描述

2. 继续新建core/userdetails文件夹

在这里插入图片描述

3. 新增UserDetailsService接口方法类。

package org.springframework.security.core.userdetails;

public interface UserDetailsService {
   

    /**
     * 原始方法,建议保留,当然也可以删除,看个人意愿
     * @param var1 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;

    /**
     * 新增接口
     * 如果有更多的用户类型认证,仅需要新增参数,其余以此类推,如下所示
     * @param var1 第一个参数
     * @param var2 第二个参数
     * @param var3 第三个参数
     * @param var4 第四个参数
     * @return
     * @throws UsernameNotFoundException
     */
    UserDetails loadUserByUsername(String var1, String var2) throws UsernameNotFoundException;
}

4. UserDetailsServicesImpl实现类

package com.est.oauth.service;

@Slf4j
@Service
public class UserDetailsServicesImpl implements UserDetailsService {
   

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
   
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String s, String var2) throws UsernameNotFoundException {
   
        return null;
    }
}

5. 复制org.springframework.security.authentication.dao.DaoAuthenticationProvider的代码,自定义 CustomAuthenticationProvider,然后进行修改retrieveUser()方法,其他不需要动

package com.tx.tcm.oauth.security.handler;

import com.tx.tcm.oauth.security.service.UserDetailsServices;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p> 自定义AuthenticationProvider类实现多用户登录 </p>
 **/
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
   
    private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
    private PasswordEncoder passwordEncoder;
    private volatile String userNotFoundEncodedPassword;
    @Resource
    private UserDetailsServices userDetailsServices;
    private UserDetailsPasswordService userDetailsPasswordService;
    public CustomAuthenticationProvider() {
   
        this.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
    }

    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
   
        if (authentication.getCredentials() == null) {
   
            this.logger.debug("Authentication failed: no credentials provided");
            throw new ApiException("身份验证失败");
        } else {
   
            String presentedPassword = authentication.getCredentials().toString();
            if (StringUtils.isBlank(presentedPassword)) {
   
                throw new ApiException("密码不能为空");
            }
            if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
   
                this.logger.debug("Authentication failed: password does not match stored value");
                throw new ApiException("密码错误");
            }
        }
    }

    protected void doAfterPropertiesSet() {
   
        Assert.notNull(this.userDetailsServices, "A UserDetailsService must be set");
    }

    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
   
        this.prepareTimingAttackProtection();
        // 自定义添加
        Map<String,String> map = (Map<String, String>) authentication.getDetails();
        try {
   
            // 自定义添加 type必须和传参是的类型一致;否则会报错
            String userType = map.get("type");
            UserDetails loadedUser = getUserDetailsServices().loadUserByUsername(username, userType);
            if (loadedUser == null) {
   
                throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
            } else {
   
                return loadedUser;
            }
        } catch (UsernameNotFoundException var4) {
   
            this.mitigateAgainstTimingAttack(authentication);
            throw var4;
        } catch (InternalAuthenticationServiceException var5) {
   
            throw var5;
        } catch (Exception var6) {
   
            throw new InternalAuthenticationServiceException(var6.getMessage(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值