I want to authenticate a User in my Java REST endpoint using Keycloak and a Bearer token.
The workflow I want to achieve is the following:
- The client logs to Keycloak with Username and Password.
- Keycloak returns a Bearer token (a JWT one if I'm not wrong, how can I check?).
- The client performs an Http request with
'Authorization' : 'Bearer <token>'
header. - The REST endpoint (written in Java) checks if the received token is correct and authenticates the User receiving a Principal from Keycloak (if I understand correctly).
- Once authenticated, the endpoint will check if User has permission to access that REST api and send back a response.
1, 2, 3 and 5 are already implemented and working but i can't find a way to implement 4.
I have already tried different ways:
My Java endpoint is running in a EAR published on WildFly 10.x so I used a
security-constraint
in myweb.xml
and configured Keycloak viakeycloak.json
.
This works fine but I need to leave some REST endpoints public (accessible even without an 'Authorization' header) in the same web context and as far as I know there is no way to filter only some requests in my security-constraint.I tried implementing a
BearerTokenRequestAuthenticator
with absolutely no success and even if I could I don't think I would receive a Principal as result of my authentication request.
Right now i have already implemented a way to filter the requests and the ones that require authentication are intercepted by a ServiceSecurityInterceptor
class I implemented.
At some point in that class I check if the 'Authorization' header contains a Basic
or Bearer
:
User loggedUser = null;
if (authorizationType.equals("Basic")) {
// ... decode Base64 username and password ...
loggedUser = userManagerBean.login(username, password);
} else if (authorizationType.equals("Bearer")) {
String token = ...; // Get token from header
// ... Here is where I need to send the token to Keycloak and receive a Principal with the username ...
loggedUser = userManagerBean.login(username):
}
I read in some places that I probably need a public key from my Keycloak realm but once I have it, what should I do?