Spring Security系列-Spring Security运行机制分析(二)

前言

接着上篇Spring Security系列-Spring Security运行机制分析(一)
这次,不再使用我们自定义的SampleAuthenticationManager,而使用Spring Security提供的ProviderManager来实现用户认证。

从一个小程序开始

在上篇的代码上,我进行了调整,运行结果一样。不了解的读者请看上篇Spring Security系列-Spring Security运行机制分析(一)

public class AuthenticationExample {
    public static AuthenticationProvider provider = new SimpleAuthenticationProvider();
    public static List<AuthenticationProvider> providers = Arrays.asList(provider);
    public static AuthenticationManager am = new ProviderManager(providers);

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            System.out.println("Please enter your username:");
            String name = in.readLine();
            System.out.println("Please enter your password:");
            String password = in.readLine();
            try {
                Authentication request = new UsernamePasswordAuthenticationToken(name, password);
                Authentication result = am.authenticate(request);
                SecurityContextHolder.getContext().setAuthentication(result);
                break;
            } catch (AuthenticationException e) {
                System.out.println("Authentication failed: " + e.getMessage());
            }
        }
        System.out.println("Successfully authenticated. Security context contains: " +
                SecurityContextHolder.getContext().getAuthentication());
    }
}

class SimpleAuthenticationProvider implements AuthenticationProvider {
    static final List<GrantedAuthority> AUTHORITIES = new ArrayList<>();

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
    }

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        if (auth.getName().equals(auth.getCredentials())) {
            return new UsernamePasswordAuthenticationToken(auth.getName(),
                    auth.getCredentials(), AUTHORITIES);
        }
        throw new BadCredentialsException("Bad Credentials");
    }

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

从上面的代码可以看到,ProviderManager初始化时,需要提供一个AuthenticationProvider集合。这就比上一篇我们使用的SampleAuthenticationManager更复杂了一点,也更接近Spring Security的真实运行机制。

ProviderManager

上面的小程序,我们为ProviderManager初始化了AuthenticationProvider集合,它会去遍历子Provider,来进行Authenticate。
然而,真实情况更加复杂,ProviderManager不仅有子Provider,而且还有父Provider,结构大致像下面那样:
在这里插入图片描述
这样看来,Spring Security会往下一层层的调用子Provider去判断认证结果,如果没有结果再去找不断向上找认证结果,运行起来还是很复杂的。
当调用ProviderManager的Authentication方法时,就会调用集合中的每一个AuthenticationProvider的Authenticate方法。源代码大致如下,只保留了关键代码。

public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		for (AuthenticationProvider provider : getProviders()) {
			if (!provider.supports(toTest)) {
				continue;
			}

			result = provider.authenticate(authentication);
			if (result != null) {
				break;
			}
		}

		if (result == null && parent != null) {
			result = parentResult = parent.authenticate(authentication);
		}

		if (result != null) {
			return result;
		}
		throw lastException;
	}
}

从上面的代码可以看出,ProviderManager的Authenticate方法进行用户认证时,

  1. 调用它下面集合providers中每个AuthenticationProvider的Authenticate方法
  2. 在providers没有认证结果的情况下,调用parent(也是一个AuthenticationManager)中的Authenticate方法

源代码

github源代码:https://github.com/camellibby/security-demo

结语

ProviderManager让我们离真相又近了一步,但离真相还一大段距离,下篇继续。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值