1,概述
在這篇快速文章中,我們將重點介紹如何在 Spring Security 和 Spring MVC 中手動驗證用戶的身份,
2,Spring Security
簡單地說,Spring Security 將每個經過身份驗證的用戶的主體資訊保存在 ThreadLocal 中——表示為 Authentication 物件,
為了構造和設定這個 Authentication 物件——我們需要使用 Spring Security 通常用來在標準身份驗證上構建物件的相同方法,
為此,讓我們手動觸發身份驗證,然后將生成的 Authentication 物件設定為框架用來保存當前登錄用戶的當前 SecurityContext:
UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
在背景關系中設定 Authentication 后,我們現在可以使用 securityContext.getAuthentication().isAuthenticated() 檢查當前用戶是否已通過身份驗證,
3,Spring MVC
默認情況下,Spring Security 在 Spring Security 過濾器鏈中添加了一個額外的過濾器——它能夠持久化安全背景關系(SecurityContextPersistenceFilter 類),
反過來,它將安全背景關系的持久性委托給 SecurityContextRepository 的實體,默認為 HttpSessionSecurityContextRepository 類,
因此,為了對請求設定身份驗證并因此使其可用于來自客戶端的所有后續請求,我們需要在 HTTP 會話中手動設定包含 Authentication 的 SecurityContext:
public void login(HttpServletRequest req, String user, String pass) {
UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
HttpSession session = req.getSession(true);
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
}
SPRING_SECURITY_CONTEXT_KEY 是靜態匯入的 HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
需要注意的是,我們不能直接使用 HttpSessionSecurityContextRepository -- 因為它與 SecurityContextPersistenceFilter. 一起作業
這是因為過濾器使用存盤庫在鏈中定義的其余過濾器執行之前和之后加載和存盤安全背景關系,但它對傳遞給鏈的回應使用自定義包裝器,
所以在這種情況下,您應該知道所使用的包裝器的型別別,并將其傳遞給存盤庫中適當的保存方法,
4,結論
在這個快速教程中,我們討論了如何在 Spring Security 背景關系中手動設定用戶 Authentication 以及如何使其可用于 Spring MVC 目的,重點介紹了說明實作它的最簡單方法的代碼示例,
與往常一樣,可以在 GitHub 上 找到代碼示例,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511887.html
標籤:Java
上一篇:微軟全力擁抱 Java!
下一篇:KTV和泛型(2)
