1.什么是spring security?
是一个基于spring安全服务框架,主要功能是认证和授权。
2.核心组件
(1)SecurityContextHolder
用于存储安全上下文的信息(用户名,密码,角色权限)
使用ThreadLocal策略来存储信息
获取当前用户信息:SecurityContextHolder.getContext().getAuthentication().getPrincipal().getusername()xx
(2)Authentication
顶级接口
- getAuthorities(),权限信息列表(通常是代表权限信息的一系列字符串)
- getCredentials(),密码信息,用户输入的密码字符串,在认证过后通常会被移除,用于保障安全。
- getDetails(),细节信息(访问者的ip地址和sessionId的值)
- getPrincipal(),身份信息
(3)AuthenticationManager(接口)是认证相关的核心接口,也是发起认证的出发点,因为在实际需求中,我们可能会允许用户使用用户名+密码登录,同时允许用户使用邮箱+密码,手机号码+密码登录,甚至,可能允许用户使用指纹登录(还有这样的操作?没想到吧),所以说AuthenticationManager一般不直接认证,AuthenticationManager接口的常用实现类ProviderManager 内部会维护一个List<AuthenticationProvider>列表,存放多种认证方式
(4)UserDetails与UserDetailsService
UserDetailsService只负责从特定的地方(通常是数据库)加载用户信息
加载到的用户信息就是UserDetails
(5)DaoAuthenticationProvider:对比获取到的输入信息和数据库中的信息。如果正确,返回一个数据库中的信息
3.spring security是如何完成身份认证的?
1 用户名和密码被过滤器获取到,封装成Authentication,通常情况下是UsernamePasswordAuthenticationToken这个实现类。
2 AuthenticationManager 身份管理器负责验证这个Authentication
3 认证成功后,AuthenticationManager身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除)Authentication实例。
4 SecurityContextHolder安全上下文容器将第3步填充了信息的Authentication,通过SecurityContextHolder.getContext().setAuthentication(…)方法,设置到其中。
4.DaoAuthenticationProvider?
AuthenticationProvider最最最常用的一个实现便是DaoAuthenticationProvider。顾名思义,Dao正是数据访问层的缩写