spring security 5 (5)-自定义认证

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangb_java/article/details/86636352

第3篇讲过,用户登录时,系统会读取用户的UserDetails对其认证,认证过程是由系统自动完成的,主要是检查用户密码。而在现实中,登录方式并不一定是检查密码,也可能是验证码或其他,此时就需要自定义认证。

AuthenticationProvider

自定义认证逻辑在AuthenticationProvider的authenticate方法中完成,第4篇讲过,认证的入参是一个未认证Authentication,出参是一个已认证Authentication,formLogin的默认Authentication实现是UsernamePasswordAuthenticationToken。

	public void configure(AuthenticationManagerBuilder auth){
		auth.authenticationProvider(authenticationProvider());	
	}
	@Bean
	public AuthenticationProvider authenticationProvider() {
		return new AuthenticationProvider() {
			//检查入参Authentication是否是UsernamePasswordAuthenticationToken或它的子类
			public boolean supports(Class<?> authentication) {
				return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
			}

			public Authentication authenticate(Authentication authentication) throws AuthenticationException {
				//第4篇讲过的其他参数,默认details类型中包含用户ip和sessionId
				WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
				//用户名和密码
				String username = authentication.getName(); 	
				String password = authentication.getCredentials().toString(); 
				//根据以上参数,自定义认证逻辑,系统默认实现就是在此读取UserDetails认证密码
                //这里只给个简化逻辑,验证密码是否是123,实际中要根据具体业务来实现
				if(!password.equals("123")){
					throw new BadCredentialsException("密码错误");				
				}
				// 认证通过,从数据库中查询用户权限 
				List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
				authorities.add(new SimpleGrantedAuthority("ROLE_role1"));
				//生成已认证Authentication,系统会将其写入SecurityContext
				return new UsernamePasswordAuthenticationToken(username, password, authorities);
			}
		};
	}

supports方法用于检查入参的类型,AuthenticationProvider只会认证符合条件的类型,下面会讲

AuthenticationManager

一个AuthenticationProvider对应一种认证逻辑,而有时用户即可选择密码登录,也可选择验证码登录,这就需要有多个认证逻辑同时存在,即多个AuthenticationProvider 。而AuthenticationManager就是用来管理多个AuthenticationProvider的。

public void configure(AuthenticationManagerBuilder auth)

以上configure方法的作用是快速自动构建AuthenticationManager,而此时要自定义AuthenticationManager,就不再需要这个方法了。而是在security配置类中使用另一个方法初始化AuthenticationManager,如下加载了两个AuthenticationProvider 

	protected AuthenticationManager authenticationManager() throws Exception {
		List list = new ArrayList();
		list.add(authenticationProvider1());
		list.add(authenticationProvider2());
		return new ProviderManager(list);
	}

将前面的authenticationProvider方法复制出第二个方法,修改方法名为authenticationProvider1和authenticationProvider2,现在就有两个authenticationProvider了,AuthenticationManager构建比较简单,此时认证流程如下

多重认证流程

  1. 执行第1个authenticationProvider的supports方法,结果false会跳到下个authenticationProvider。结果true则执行当前authenticationProvider的认证逻辑。
  2. 认证不通过,会抛出相关异常,会直接跳出AuthenticationManager。
  3. 认证通过,返回已认证Authentication,同样跳出AuthenticationManager。
  4. 如果需要进一步认证,可返回null,跳到下一个authenticationProvider,可实现多重认证。

我之前说过,系统默认的Authentication入参都是UsernamePasswordAuthenticationToken类型,所以这里supports必须为true。下篇我会讲自定义认证过滤器,到时候就可以自定义不同的入参类型了,以适用于不同的AuthenticationProvider。

自定义Details

如果要实现对用户/密码以外的参数进行认证,如验证码,还需要自定义Details。上面代码中的WebAuthenticationDetails是默认的Details实现类,其中包括用户ip和sessionId两个参数。以下方式可以添加自定义参数:如验证码code。

public class MyWebAuthenticationDetails extends WebAuthenticationDetails {
	private String code;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public MyWebAuthenticationDetails(HttpServletRequest request) {
		super(request);
		code=request.getParameter("code");
	}

修改上面的代码,WebAuthenticationDetails改成MyWebAuthenticationDetails,就可以对验证码进行认证。

        MyWebAuthenticationDetails details = (MyWebAuthenticationDetails)authentication.getDetails();
        if(!details.getCode().equals("123")){
	        throw new BadCredentialsException("验证码错误");				
        }

上一篇讲过,Details是Authentication的一个参数,而Authentication是在认证过滤器中封装而成的。而formLogin会使用系统默认的认证过滤器,其默认Details也是WebAuthenticationDetails类型,需要以下配置将它改成MyWebAuthenticationDetails类型。

	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests() 
				.anyRequest().authenticated().and() 
			.formLogin() //配置Details源
				.authenticationDetailsSource(authenticationDetailsSource()).and()
			.csrf().disable();
	}
	@Bean
	public AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource() {
		return new AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails>() {
			public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
				return new MyWebAuthenticationDetails(context);//配置Details类型
			}
		};
	}

猜你喜欢

转载自blog.csdn.net/wangb_java/article/details/86636352