Spring Security可以运行在不同的身份认证环境中,当我们推荐用户使用Spring Security进行身份认证但并不推荐集成到容器管理的身份认证中时,但当你集成到自己的身份认证系统时,它依然是支持的。
1. Spring Security中的身份认证是什么?
现在让我们考虑一下每个人都熟悉的标准身份认证场景:
(1)用户打算使用用户名和密码登陆系统
(2)系统验证用户名和密码合法
(3)得到用户信息的上下文(角色等信息)
(4)为用户建立一个安全上下文
(5)用户接下来可能执行一些权限访问机制下的受保护的操作,检查与当前安全上下文有关的必须的权限
上面前三步是身份认证的过程,接下来看看身份认证的详细过程:
(1)用户名和密码获得之后组合成 UsernamePasswordAuthenticationToken 的实例(前文讨论过的Authentication接口的实例)
(2)将该令牌传递给 AuthenticationManager 实例进行验证
(3)验证成功后,AuthenticationManager 会返回填充好的 Authentication 实例
(4)通过调用 SecurityContextHolder.getContext().setAuthentication(...) 建立安全上下文的实例,传递到返回的身份认证对象上
下面是进行身份认证的代码片段:
import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
public class AuthenticationExample {
private static AuthenticationManager am = new SampleAuthenticationManager();
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 SampleAuthenticationManager implements AuthenticationManager {
static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
static {
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
}
public Authentication authenticate(Authentication auth) throws