我是春天的新手,所以只是在尋找一般的方向/建議。
我正在構建一個小型微服務。服務身份驗證已設定為驗證傳遞給它的 JWT(由不同的微服務發布)。
JWT 包含 sessionid 宣告。我希望能夠獲得該宣告,并驗證會話是否仍處于活動狀態。
現在將通過直接查詢資料庫來實作,盡管將來當我們擁有專用會話服務時,我會將其更改為呼叫該服務。
我顯然可以在每個控制器中獲得應該驗證會話的宣告(基本上所有控制器),但我正在尋找一個更全域的選項,比如請求攔截器(它只在 JWT 被驗證后觸發,并且可以訪問經驗證的 JWT)。
有沒有推薦的方法在春天做這種事情?
uj5u.com熱心網友回復:
您有幾種選擇來做到這一點:使用ControllerAdvice,也許是 AOP,但可能要走的路是使用自定義安全過濾器。
這個想法在本文和這個相關的 SO 問題中得到了例證。
首先,創建一個過濾器來處理適當的宣告。例如:
public class SessionValidationFilter extends GenericFilterBean {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String AUTHORIZATION_BEARER = "Bearer";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
// We will provide our own validation logic from scratch
// If you are using Spring OAuth or something similar
// you can instead use the already authenticated token, something like:
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// if (authentication != null && authentication.getPrincipal() instanceof Jwt) {
// Jwt jwt = (Jwt) authentication.getPrincipal();
// String sessionId = jwt.getClaimAsString("sessionid");
// ...
// Resolve token from request
String jwt = getTokenFromRequest(httpServletRequest);
if (jwt == null) {
// your choice... mine
filterChain.doFilter(servletRequest, servletResponse);
return;
}
// If the token is not valid, raise error
if (!this.validateToken(jwt)) {
throw new BadCredentialsException("Session expired");
}
// Continue filter chain
filterChain.doFilter(servletRequest, servletResponse);
}
// Resolve token from Authorization header
private String getTokenFromRequest(HttpServletRequest request){
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
if (StringUtils.isNotEmpty(bearerToken) && bearerToken.startsWith(AUTHORIZATION_BEARER)) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
// Validate the JWT token
// We can use the jjwt library, for instance, to process the JWT token claims
private boolean validateToken(String token) {
try {
Claims claims = Jwts.parser()
// .setSigningKey(...)
.parseClaimsJws(token)
.getBody()
;
String sessionId = (String)claims.get("sessionid");
// Process as appropriate to determine whether the session is valid or not
//...
return true;
} catch (Exception e) {
// consider logging the error. Handle as appropriate
}
return false;
}
}
現在,假設您正在使用 Java 配置,將過濾器添加到 Spring Security 過濾器鏈中實際執行身份驗證的過濾器鏈之后:
@Configuration
public class SecurityConfiguration
extends WebSecurityConfigurerAdapter {
// the rest of your code
@Override
protected void configure(HttpSecurity http) throws Exception {
// the rest of your configuration
// Add the custom filter
// see https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#filter-stack
// you can name every provided filter or any specified that is included in the filter chain
http.addFilterAfter(new SessionValidationFilter(), BasicAuthenticationFilter.class);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398920.html
