'How to disable auto login redirect in Spring Boot Keycloak Adapter

I am writing an API in Spring Boot that I want to secure using Keycloak. After doing some setting up, I managed to get the keycloak adapter to work. While I was expecting a 403 on any non-authenticated request, I get an HTTP 302 redirect to login page instead. As I am working on an API, how can I disable the auto login-redirect and provide a 403 error message, so that I could add some frontend logic to start on the login process?



Solution 1:[1]

In your config, you do

http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint())

It will start returning 403 on every failed call and you can then catch it and whatever logic you need.

Solution 2:[2]

You need to add the propery keycloak.bearer-only: true in the application.properties or application.yml to avoid redirect to login page when there is one error You will get one 401 error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2137817
Solution 2 Jose Luis Santos Blanco