SpringSecurity配置多种登录方式

进入到ProviderManager这个类当中的authenticate方法。

	// member variable
	private List<AuthenticationProvider> providers;			// provider集合
	
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Class<? extends Authentication> toTest = authentication.getClass();
        Authentication result = null;
        int size = this.providers.size();
        Iterator var9 = this.getProviders().iterator();

		// 遍历 Provider
        while(var9.hasNext()) {
            AuthenticationProvider provider = (AuthenticationProvider)var9.next();
            // 找到和 authentication 匹配的 provider
            if (provider.supports(toTest)) {
                try {
                	// 用匹配的provider去认证
                    result = provider.authenticate(authentication);
                    if (result != null) {
                        this.copyDetails(authentication, result);
                        break;
                    }
                }
            }
        }
    }

包装Authentication(基本就是照抄UsernamePasswordAuthenticationToken)

/**
 *  用于邮箱登录
 */
public class MailAuthenticationToken extends AbstractAuthenticationToken {
    private final Object principal;
    private Object credentials;

    public MailAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

    public MailAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }
}

模仿AbstractUserDetailsAuthenticationProviderDaoAuthenticationProvider,自定义一个AuthenticationProvider ,实现认证逻辑
有些防止攻击,校验参数是否为null,get/set方法,更新密码的东西都删去了。

/**
 *  邮箱登录校验逻辑
 */
@Slf4j
@Component
public class MailProvider implements AuthenticationProvider {

    @Autowired
    private MailUserDetailsServiceImpl mailUserDetailsService;
    @Autowired
    private RedisTemplate redisTemplate;
//    private final Log logger = LogFactory.getLog(this.getClass());

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String username = authentication.getName();
        UserDetails user;

        // 用户名校验(是否可以查得到)
        try {
            user = mailUserDetailsService.loadUserByUsername(username);
        } catch (UsernameNotFoundException var6) {
            log.debug("Failed to find user '" + username + "'");
            throw new BadCredentialsException("MailAuthenticationProvider.badCredentials");
        }

        // 密码校验
        if(authentication.getCredentials() == null){
            log.debug("Failelogd to authenticate since no credentials provided");
            throw new BadCredentialsException("MailAuthenticationProvider.badCredentials");
        }else{
            String presentedPassword = authentication.getCredentials().toString();
            String mail_code = (String)redisTemplate.opsForValue().get(username);
            // 验证码过期
            if(mail_code == null){
                throw new BusinessException(401,"验证码已过期");
            }
            // 验证码错误
            if (presentedPassword != mail_code) {
                log.debug("Failed to authenticate since password does not match stored value");
                throw new BadCredentialsException("MailAuthenticationProvider.badCredentials");
            }
        }

        MailAuthenticationToken token = new MailAuthenticationToken(user,authentication.getCredentials(),user.getAuthorities());
        return token;
    }

    @Override
    public boolean supports(Class<?> authenticaton) {
        return MailAuthenticationToken.class.isAssignableFrom(authenticaton);
    }
}

UserDetailsService实现类

@Component
public class MailUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userDao.findByEmail(email);
        if(user == null){
            throw new UsernameNotFoundException(email);
        }
        return new UserDetailsImpl(user);       // 包装返回
    }
}

在SpringSecurity配置对应的AuthenticationManager

    @Autowired
    private AuthenticationProvider daoProvider;
    @Autowired
    private AuthenticationProvider mailProvider;
  
    @Bean
    public  AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        AuthenticationManager auth = new ProviderManager(Arrays.asList(mailProvider,daoProvider));
        return auth;
    }

Service层登录业务代码

    public Result loginCheck(LoginData loginData){

        Authentication authentication = null;

        if(loginData.getLoginType() == 0){
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginData.getUsername(), loginData.getPassword())
            );
        }

        if(loginData.getLoginType() == 1){
            authentication = authenticationManager.authenticate(
                    new MailAuthenticationToken(loginData.getUsername(), loginData.getPassword())
            );
        }

        // 从loadUserByUsername方法中查到该用户的信息, 封装到UserDetails,
        // 之后又塞到了UsernamePasswordAuthenticationToken的Principal属性中
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        String username = userDetails.getUsername();
        String token = JwtUtils.createToken(username);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);

        redisTemplate.opsForValue().set("token::"+token,userDetails, Duration.ofHours(1));

        userDao.updateLoginStatus(LocalDateTime.now(),1,userDetails.getUser().getId());
        return new Result(200,"ok",map);
    }

UserDetailsPasswordService是用来更新密码的接口
AuthenticationManager,AuthenticationProvider,UserDetailsService的关系
SpringSecurity多种登录方式
配置多个AuthenticationProvider

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security中,我们可以通过配置多个AuthenticationProvider来实现多种登录方式。其中,AuthenticationProvider是一个接口,用于验证用户的身份信息。而AuthenticationManager是Spring Security中的核心接口,用于管理和执行身份验证的过程。 首先,在Spring Security配置文件中,我们可以定义多个AuthenticationProvider,并通过@Autowired注解将它们注入到AuthenticationManager中。在authenticationManager方法中,我们可以使用ProviderManager类来创建一个实例,并将所有的AuthenticationProvider传递给它。ProviderManager会按照它们在列表中的顺序逐个验证用户的身份信息。 然后,在ProviderManager的authenticate方法中,它会遍历所有的AuthenticationProvider,并找到与给定的身份验证对象匹配的Provider。一旦找到匹配的Provider,它会调用该Provider的authenticate方法进行身份验证。如果验证成功,它会返回一个已经通过身份验证的Authentication对象,如果验证失败,则会抛出相应的AuthenticationException异常。 通过这种方式,我们可以实现多种登录方式,每种方式对应一个自定义的AuthenticationProvider。在每个AuthenticationProvider中,我们可以根据特定的登录方式来验证用户的身份信息,例如使用不同的用户信息来源、验证逻辑等。这样就能够灵活地满足不同登录方式的需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringSecurity配置多种登录方式](https://blog.csdn.net/qq_53318060/article/details/127286866)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值