[英]Spring boot - holding authenticated user through many server instances
I have got spring security STATELESS
application based on JWT
tokens.我有基于JWT
令牌的STATELESS
安全无状态应用程序。 Here is my custom authorization filter这是我的自定义授权过滤器
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)
}
so as you can see, I save the authorizedUser
into SecurityContextHolder
.如您所见,我将authorizedUser
保存到SecurityContextHolder
中。 Then I use this saved user to eg secure my app before retrieving data of user A
by user B
like this:然后我使用这个保存的用户来保护我的应用程序,然后再通过用户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)
}
But it works when the app runs as a single instance while I would like to deploy this app on many intances so the但是当应用程序作为单个实例运行时它会起作用,而我想在许多实例上部署这个应用程序所以
authentication.principal.toString().equals(#employerId.toString()
will no work anymore becuase context holders are different on different instances.将不再起作用,因为上下文持有者在不同的实例中是不同的。
For any request the ServletFilter (authentication) is ALWAYS on the same server as the ServletController that processes it.对于任何请求,ServletFilter(身份验证)始终与处理它的 ServletController 在同一台服务器上。 The filterChain passes the request on to the controller and has the same security context. filterChain 将请求传递给 controller 并具有相同的安全上下文。 With JWT every single request is authenticated (because every request goes through the filter) and allows the service to be stateless.使用 JWT,每个请求都经过身份验证(因为每个请求都通过过滤器)并允许服务无状态。 The advantage of this is scalability - you can have as many instances as you need.这样做的优点是可扩展性——您可以根据需要拥有任意数量的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.