03.Spring Security
Spring Security CheatSheet
- 对身份验证和授权的全面且可扩展的支持
- 防御会话固定、点击劫持,跨站请求伪造等攻击
- 支持
Servlet API 集成 - 支持与
Spring Web MVC 集成
目前
- HTTP basic access authentication
- LDAP system
- OpenID identity providers
- JAAS API
- CAS Server
- ESB Platform
- ……
- Your own authentication system
在进入

核心组件
-
用户登陆,会被
AuthenticationProcessingFilter 拦截,调用AuthenticationManager 的实现,而且AuthenticationManager 会调用ProviderManager 来获取用户验证信息(不同的Provider 调用的服务不同,因为这些信息可以是在数据库上,可以是在LDAP 服务器上,可以是xml 配置文件上等) ,如果验证通过后会将用户的权限信息封装一个User 放到Spring 的全局缓存SecurityContextHolder 中,以备后面访问资源时使用。 -
访问资源(即授权管理
) ,访问url 时,会通过AbstractSecurityInterceptor 拦截器拦截,其中会调用FilterInvocationSecurityMetadataSource 的方法来获取被拦截url 所需的全部权限,在调用授权管理器AccessDecisionManager ,这个授权管理器会通过spring 的全局缓存SecurityContextHolder 获取用户的权限信息,还会获取被拦截的url 和被拦截url 所需的全部权限,然后根据所配的策略(有:一票决定,一票否定,少数服从多数等) ,如果权限足够,则返回,权限不够则报错并调用权限不足页面。
SecurityContextHolder,SecurityContext 和Authentication
最基本的对象是
获取当前用户的信息
因为身份信息与当前执行线程已绑定,所以可以使用以下代码块在应用程序中获取当前已验证用户的用户名:
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
调用
// org/springframework/security/core/context/SecurityContext.java
public interface SecurityContext extends Serializable {
Authentication getAuthentication();
void setAuthentication(Authentication authentication);
}
Authentication
在
// org/springframework/security/core/Authentication.java
public interface Authentication extends Principal, Serializable {
// 权限信息列表,默认是GrantedAuthority接口的一些实现类,通常是代表权限信息的一系列字符串。
Collection<? extends GrantedAuthority> getAuthorities();
// 密码信息,用户输入的密码字符串,在认证过后通常会被移除,用于保障安全。
Object getCredentials();
Object getDetails();
// 最重要的身份信息,大部分情况下返回的是UserDetails接口的实现类,也是框架中的常用接口之一。
Object getPrincipal();
boolean isAuthenticated();
void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}
以上的