Spring Security 自定义身份认证处理器

概述

我们可以通过继承AuthenticationProvider或者其实现来完成自定义身份认证处理器

通常身份验证处理器主要是完成对用户名密码的验证和判断用户时候可用等

实现案例

以下是实现方法

1. 继承于AuthenticationProvider

new AuthenticationProvider() {
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
	    // 进行身份认证的方法
		if ("admin".equals(authentication.getPrincipal()) && "123456".equals(authentication.getCredentials())) {
			List<GrantedAuthority> grantedAuthorities = Arrays.asList(new SimpleGrantedAuthority("admin"));
			UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getAuthorities(), grantedAuthorities);
			token.setDetails(authentication.getDetails());
			return token;
        }else{
			throw new BadCredentialsException("账号密码错误");
        }
      }

    @Override
    public boolean supports(Class<?> aClass) {
        // 支持何种类型的身份认证
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

2. 在AuthenticationManager中使用这个Provider处理器即可

// 提交给实现 ProviderManager 使用
new ProviderManager(providers);
Spring Security 6 中的认证失败处理器主要用于处理用户身份验证过程中出现的错误,例如密码错误、权限不足等。它允许你在用户尝试访问受保护资源时提供定制化的反馈信息。配置步骤如下: 1. **创建自定义的`AuthenticationFailureHandler`**: - 定义一个实现`AuthenticationFailureHandler`接口的类,比如`MyAuthenticationFailureHandler`。 ```java public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { // 这里编写处理失败登录的逻辑,如发送错误消息到前端 } } ``` 2. **添加到全局安全过滤器链**: 在`WebSecurityConfigurerAdapter`中,使用`formLogin()`方法设置认证失败处理器: ```java @Autowired private MyAuthenticationFailureHandler authenticationFailureHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .failureHandler(authenticationFailureHandler); } ``` 3. **启用HTTP基本认证失败处理**: 如果需要处理基于HTTP基本认证的失败,可以在`http`元素中指定`httpBasic()`: ```java http.httpBasic().authenticationEntryPoint(new CustomEntryPoint()); ``` 4. **处理异常详细程度**: 可以通过`AbstractAuthenticationProcessingFilter.setDefaultFailureResponse`设置默认的失败响应,或者在每个具体的过滤器中单独配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值