[英]Spring Boot: Is it safe to pass many Instances for CommandLineRunner
[英]Spring boot - holding authenticated user through many server instances
我有基於JWT
令牌的STATELESS
安全無狀態應用程序。 這是我的自定義授權過濾器
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
chain: FilterChain,
) {
val header = request.getHeader(Objects.requireNonNull(HttpHeaders.AUTHORIZATION))
if (header != null) {
val authorizedUser = tokensService.parseAccessToken(header)
SecurityContextHolder.getContext().authentication = authorizedUser
}
chain.doFilter(request, response)
}
如您所見,我將authorizedUser
保存到SecurityContextHolder
中。 然后我使用這個保存的用戶來保護我的應用程序,然后再通過用戶B
檢索用戶A
的數據,如下所示:
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@PreAuthorize("authentication.principal.toString().equals(#employerId.toString())")
annotation class IsEmployer
@IsEmployer
@GetMapping("/{employerId}")
fun getCompanyProfile(@PathVariable employerId: Long): CompanyProfileDTO {
return companyProfileService.getCompanyProfile(employerId)
}
但是當應用程序作為單個實例運行時它會起作用,而我想在許多實例上部署這個應用程序所以
authentication.principal.toString().equals(#employerId.toString()
將不再起作用,因為上下文持有者在不同的實例中是不同的。
對於任何請求,ServletFilter(身份驗證)始終與處理它的 ServletController 在同一台服務器上。 filterChain 將請求傳遞給 controller 並具有相同的安全上下文。 使用 JWT,每個請求都經過身份驗證(因為每個請求都通過過濾器)並允許服務無狀態。 這樣做的優點是可擴展性——您可以根據需要擁有任意數量的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.