spring security支持多个认证方法

spring security通过定义多个AuthenticationProvider来实现不同的认证方式。

1、自定义认证器

自定义认证器可以通过实现AuthenticationProvider接口来实现,这个接口,一共有两个方法

public interface AuthenticationProvider {

	/**
	 * Performs authentication with the same contract as
	 * {@link org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}
	 * .
	 * @param authentication the authentication request object.
	 * @return a fully authenticated object including credentials. May return
	 * <code>null</code> if the <code>AuthenticationProvider</code> is unable to support
	 * authentication of the passed <code>Authentication</code> object. In such a case,
	 * the next <code>AuthenticationProvider</code> that supports the presented
	 * <code>Authentication</code> class will be tried.
	 * @throws AuthenticationException if authentication fails.
	 */
	Authentication authenticate(Authentication authentication) throws AuthenticationException;

	/**
	 * Returns <code>true</code> if this <Code>AuthenticationProvider</code> supports the
	 * indicated <Code>Authentication</code> object.
	 * <p>
	 * Returning <code>true</code> does not guarantee an
	 * <code>AuthenticationProvider</code> will be able to authenticate the presented
	 * instance of the <code>Authentication</code> class. It simply indicates it can
	 * support closer evaluation of it. An <code>AuthenticationProvider</code> can still
	 * return <code>null</code> from the {@link #authenticate(Authentication)} method to
	 * indicate another <code>AuthenticationProvider</code> should be tried.
	 * </p>
	 * <p>
	 * Selection of an <code>AuthenticationProvider</code> capable of performing
	 * authentication is conducted at runtime the <code>ProviderManager</code>.
	 * </p>
	 * @param authentication
	 * @return <code>true</code> if the implementation can more closely evaluate the
	 * <code>Authentication</code> class presented
	 */
	boolean supports(Class<?> authentication);

}

第一个方法参数是Authencation,通过Authencation我们又可以自定义token,也是通过实现Authencation来自定义token,这个token会在第二个方法中使用;

第二个方法用于判断当前的认证其是否支持指定类型的token;

2、自定义实现一个认证器

/**
 * @author Mr.Wen
 * @version 1.0
 * @date 2021-08-19 14:20
 */
@Service
public class SecurityAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private UserDetailsServiceImpl userDetailsService;
    @Resource
    private SecurityPasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        if(StringUtils.isBlank(username)){
            throw new UsernameNotFoundException("username用户名不可以为空");
        }
        if(StringUtils.isBlank(password)){
            throw new BadCredentialsException("密码不可以为空");
        }
        //获取用户信息
        SecurityUserDetails user = (SecurityUserDetails)userDetailsService.loadUserByUsername(username);
        //比较前端传入的密码明文和数据库中加密的密码是否相等
        if (!passwordEncoder.matches(password, user.getPassword())) {
            //发布密码不正确事件
            throw new BadCredentialsException("password密码不正确");
        }
        //获取用户权限信息
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new SecurityAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(SecurityAuthenticationToken.class);
    }
}

UserDetails和对应的service是自己实现的,密码处理器也是自己实现的,这些都无需关心,换成自己系统的实现就可以了,第一个方法,就是认证,返回一个token交给spring security后续流程处理;第二个方法判断当前token是不是认证其支持的token。

3、配置多认证器

再spring security的配置类中,配置认证器。

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 加入自定义的安全认证
        auth.
            authenticationProvider(securityAuthenticationProvider)
            .authenticationProvider(getKmairCasAuthenticationProvider());
    }

第一个provider是用spring注入的,第二个则是再方法中创建了provider;

到此就可以实现多认证器。

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security支持多个UserDetailsService。你可以通过在配置文件中定义多个UserDetailsService的实现类来实现这一点。在配置文件中,你可以使用<bean>标签为每个UserDetailsService定义一个bean,并使用<alias>标签为每个bean定义一个别名。然后,你可以在Spring Security的配置中使用这些别名来引用不同的UserDetailsService。这样,当Spring Security进行认证时,它将根据配置中指定的别名来选择相应的UserDetailsService来获取用户的认证数据。这种方式可以实现对不同来源的用户数据的支持,例如内存、数据库、LDAP等。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【Spring Security系列】Spring Security 基于内存的多用户支持](https://blog.csdn.net/qq_28248897/article/details/106943017)[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: 33.333333333333336%"] - *2* [Spring Security身份认证之UserDetailsService](https://blog.csdn.net/shehun1/article/details/45394405)[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: 33.333333333333336%"] - *3* [Spring Security:用户服务UserDetailsService源码分析](https://blog.csdn.net/qq_37960603/article/details/122310202)[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: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值