Propagate HTTP header (JWT Token) over services using spring rest template

后端 未结 3 1597
萌比男神i
萌比男神i 2020-12-14 04:23

I have a microservice architecture, both of them securized by spring security an JWT tokens.

So, when I call my first microservice, I want to take the JWT token and

3条回答
  •  醉话见心
    2020-12-14 05:06

    I think it is better to add the interceptor specifically to the RestTemplate, like this:

    class RestTemplateHeaderModifierInterceptor(private val authenticationService: IAuthenticationService) : ClientHttpRequestInterceptor {
        override fun intercept(request: org.springframework.http.HttpRequest, body: ByteArray, execution: ClientHttpRequestExecution): ClientHttpResponse {
            if (!request.headers.containsKey("Authorization")) {
                // don't overwrite, just add if not there.
                val jwt = authenticationService.getCurrentUser()!!.jwt
                request.headers.add("Authorization", "Bearer $jwt")
            }
            val response = execution.execute(request, body)
            return response
        }
    }
    

    And add it to the RestTemplate like so:

    @Bean
    fun restTemplate(): RestTemplate {
        val restTemplate = RestTemplate()
    restTemplate.interceptors.add(RestTemplateHeaderModifierInterceptor(authenticationService)) // add interceptor to send JWT along with requests.
        return restTemplate
    }
    

    That way, every time you need a RestTemplate you can just use autowiring to get it. You do need to implement the AuthenticationService still to get the token from the TokenStore, like this:

    
    val details = SecurityContextHolder.getContext().authentication.details
    if (details is OAuth2AuthenticationDetails) {
       val token = tokenStore.readAccessToken(details.tokenValue)
       return token.value
    }
    
    

提交回复
热议问题