Spring Security 是什麼?

解決了什麼問題?

核心組件有哪些?

1. SecurityContextHolder 和 SecurityContext

//通常在JwtAuthenticationFilter中
//將認證資訊存入SecurityContext
SecurityContextHolder.getContext().setAuthentication(authToken);

2. Authentication 與 GrantedAuthority

//通常出現在兩個地方
//1.login方法
//建立一個已驗證的通行證
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(newLogin.getUsername(), newLogin.getPassword()));

//2.JwtAuthenticationFilter
//UsernamePasswordAuthenticationToken 物件是 Authentication 的一個標準實作。 
// 這張 "通行證" 包含了三樣東西: 
	// - Principal (你是誰): username 字串 
	// - Credentials (憑證): null (因為 JWT 已經驗證過了,不需要密碼) 
	// - Authorities (你能做什麼): 上一步建立的 authorities 列表
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
			username,
			null,
			authorities
		);
//將認證資訊存入 SecurityContext
SecurityContextHolder.getContext().setAuthentication(authToken);
//Token通過認證後直接從Token中提取權限,不訪問資料庫
List<String> roles = jwtService.extractRoles(jwt);

//這裡 "建立" 了 GrantedAuthority 物件
List<SimpleGrantedAuthority> authorities = roles.stream()
.mapnew
.collect(Collectors.toList());

//之後傳入了上方的UsernamePasswordAuthenticationToken

3. UserDetails 與 UserDetailsService


//在JpaUserDetailsService中,實作了UserDetailsService中的方法

@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

// TODO Auto-generated method stub

User user = userRepository.findByUsername(username)

.orElseThrow(()->new UsernameNotFoundException("找不到使用者" + "username"));

return new SecurityUser(user);

}

4. AuthenticationManager 與 AuthenticationProvider

//通常在login方法中
//在這裡authenticationManager在得到UsernamePasswordAuthenticationToken後在內部呼叫了
//authenticationProvider來處理,並返回了經過驗證的authentication
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(newLogin.getUsername(), newLogin.getPassword()));

5. AccessDecisionManager 與 AbstractSecurityInterceptor

6. 過濾器鏈(Filter Chain)

Spring Security 透過一系列過濾器(Filters)來攔截請求並執行安全檢查,可以把「過濾器鏈 (Filter Chain)」想像成一個機場的安檢流程,例如: