SpringSecurity 核心类与接口
SecurityContextHolder
程序档安全环境的细节存储在它里边了,也包含了应用当前使用的主体细节,默认情况下,SecurityContextHolder使用ThreadLocal存储这些信息。
我们通过下面这种方法来获取当前用户信息
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
UserDetailsService
接口里的唯一一个方法,接收String类型的用户名参数,返回UserDetails,通常倾向于自己编写,但也可以通过使用官方提供的实现,比如InMemoryDaoImpl,JdbcDaoImpl
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
UserDetails
Spring Security的核心接口,它代表一个主体,是扩展的。通常UserDetails转换成你系统提供的类,这样你就可以直接调用业务相关的方法了(比如getEmail(), getEmployeeNumber()等等)。
public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getPassword();
....
}
核心服务
核心接口和他们的实现
AuthenticationManager
在Spring Security中的默认实现是ProviderManager 不只是处理授权请求自己,它委派了一系列配置好的AuthenticationProvider,每个按照顺序查看它是否可以执行验证。每个供应器会跑出一个异常,或者返回一个完整的 Authentication对象。
AuthenticationProviders
最常用的方式是验证一个授权请求读取 对应的UserDetails,并检查用户录入的密码。 这是通过DaoAuthenticationProvider实现的(见下面), 加载的UserDetails对象 - 特别是包含的 GrantedAuthority - 会在建立Authentication 时使用,这回返回一个成功验证,保存到SecurityContext中。
<bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<!--每个provider能够尝试进行授权,或通过返回null跳过授权。若所有实现都返回null,ProviderManager会抛出一个 ProviderNotFoundException异常-->
<ref local="daoAuthenticationProvider"/>
</list>
</property>
</bean>
<!--最简单的AuthenticationProvider实现-->
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="inMemoryDaoImpl"/>
<!-- 以下都是可选项 用于提供密码的编码和解码以及用于提高密码安全性
<property name="saltSource" ref bean="saltSource"/>
<property name="passwordEncoder" ref="passwordEncoder"/>-->
</bean>