1. 用戶名和密碼被過濾器獲取到,封裝成 Authentication ,通常情況下是 UsernamePasswordAuthenticationToken 這個實現類。
2. AuthenticationManager 身份管理器負責驗證這個 Authentication
3. 認證成功后, AuthenticationManager 身份管理器返回一個被填充滿了信息的(包括上面提到的 權限信息,身份信息,細節信息,但密碼通常會被移除) Authentication 實例。
4. SecurityContextHolder 安全上下文容器將第3步填充了信息的 Authentication ,通過 SecurityContextHolder.getContext().setAuthentication(…)方法,設置到其中。
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"));
}
@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");
}
}
認證流程

推薦閱讀
技術總體方案設計思路
如何評價代碼的質量-CSDN博客
領域分解識別服務