KeycloakOIDCFilter to protect rest-api should return 401 on unauthorized request instead of login page

I’m registering a KeycloakOIDCFilter in front of a servlet within an OSGI container to protect a rest-api. Authentication via token and subsequent usage of the api works fine.

Now everytime I UNAUTHENTICATED connect to a protected resource, the filter redirects me to the login page. For an API this is not what I want. The filter should return with HTTP code 401.

How (resp. where) can I configure the filter to do this? Is this done within keycloak configuration, or at the point I register the filter? I did some research on the webs but could not really find something - a quick link would be enough!

Thanks guys

This is just a long shot, but I suppose you can try (if not already) setting a "Accept: application/json" header to see if it changes behavior.

I see, you refer to Securing Applications and Services Guide autodetect-bearer-only I tried. I even tried some setting combinations - but none made the filter return 401 on an unauthenticated request. It always returns the login page!

1 Like

I found it. It was an error in my implementation of the KeycloakConfigResolver - it was not correctly
used by the KeycloakOIDCFilter. After fixing this, and setting the parameter isBearerOnly(true) - for unauthenticated users http 401 is returned!

1 Like