I got a micro-service running behind an API - gateway(Zuul) which has secured endpoints with the use of Keycloak. Keycloak always returns 401 for the secured endpoints when accessed from a public client(eg: postman) even with a valid token. I have done the same scenario without the use of the API gateway and works perfectly fine which isolates the issue to newly added api-gateway.(have configured clients, roles, and users in keycloak).
The gateway service client is confidential and The API service client is public, in keycloak.
All the services, including keycloak is running as docker containers. Below is the keycloak-spring boot configuration in the properties file.
keycloak :
realm : admin-realm
auth-server-url : http://keycloak:8080/auth
ssl-required : external
resource : gateway-service
bearer-only : true
credentials.secret : *********************
#
security-constraints[0] :
authRoles[0] : user
securityCollections[0] :
patterns[0] : /api/*
Solved
The problem was with the mismatch between the issuer URL of the token (http://localhost:8080/auth/) and the keycloak configuration URL in the property file of the micro-service (http://keycloak:8080/auth).
This happens when I tested the microservice from outside the docker network. (From postman). It could be resolved after I added the hostname 'keycloak; to the host file of Windows,
- Open c:\Windows\System32\Drivers\etc\hosts file as Administrator
- Add 127.0.0.1 keycloak
Then from the postman, we could access the keycloak endpoint as,
- http://keycloak:8080/auth......