Spring Security and Keycloak Integration in Spring Boot
As-salamu alaykum, How are you, folks?
While I was learning authentication with spring security and keycloak to perform some action in other services I encountered an issue for post request in Postman. I’ll share that scenario and how I solved it.
Scenario:
Suppose I have an order service, to make orders, the order service also needs to know the current state of stock service. Before I proceed, I need to authenticate the user (for that I use Keycloak as IAM(Identity and Access Management)) and make calls through the api gateway.
Problem: While making a call for order service through api gateway with token, I was always getting keycloak login page. I discovered the token was stuck in the order service but I also need to call the stock service and should verify the token also. I used OpenFeign for service to service communication.
Solution:
First of all, we need to tell the api gateway to use TokenRelay. TokenRelay used to pass a token while proxy downstream service. And at the particular service receive incoming requests and add to outgoing requests.
Api gateway:
gateway: default-filters: - TokenRelay
Order-service:
private final String AUTHORIZATION_HEADER = "Authorization";public static String getBearerTokenHeader() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader( "Authorization"); }@Overridepublic void apply(RequestTemplate template) { template.header(AUTHORIZATION_HEADER, getBearerTokenHeader());}
Source code