Home > Back-end >  Spring boot - holding authenticated user through many server instances
Spring boot - holding authenticated user through many server instances

Time:01-31

I have got spring security STATELESS application based on JWT tokens. 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. Then I use this saved user to e.g. secure my app before retrieving data of user A by user B like this:

    @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.

CodePudding user response:

For any request the ServletFilter (authentication) is ALWAYS on the same server as the ServletController that processes it. The filterChain passes the request on to the controller and has the same security context. With JWT every single request is authenticated (because every request goes through the filter) and allows the service to be stateless. The advantage of this is scalability - you can have as many instances as you need.

  • Related