vertx-web
vertx-web copied to clipboard
oauth2 should not redirect (HTTP 302) XHR requests
Version
4.3.8 and 4.4.9
Context
A browser-based app with a backend support. The Vert.x backend is serving:
- an API that is protected by
OAuth2Authcreated usingKeycloakAuth.discover - a Single Page Application (index.html, served by the backend with a
StaticHandler) using axios to call the API
The problem
When not authenticated, API calls are returning HTTP 302 (+ Location) responses that are blocked by the browser because of the redirect.
From the axios point of view, it is getting a generic AxiosError: Network Error (the browser is "hiding" the redirect).
I think API calls should return HTTP 401 responses when axios is configured to set the X-Requested-With: XMLHttpRequest HTTP header.
If I'm understanding correctly, Springs seems to return 401 responses in that situation: https://github.com/candrews/spring-security/blob/09100daf0fd6cd3a89dded4c962191cff98bb031/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java#L391
Reproducer
https://github.com/bfreuden/vertx-vue-oauth2-example
Basically containing 3 files:
- A docker compose to start a pre-configured Keycloak: https://github.com/bfreuden/vertx-vue-oauth2-example/blob/master/keycloak/docker-compose.yml
- Vue SPA: https://github.com/bfreuden/vertx-vue-oauth2-example/blob/master/src/main/www/index.html
- Vert.x backend: https://github.com/bfreuden/vertx-vue-oauth2-example/blob/master/src/main/java/org/bfreuden/Server.java
Also containing a fix proposal: https://github.com/bfreuden/vertx-vue-oauth2-example/blob/master/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java#L128
Warning: by default the repo is showing the behavior of the fix proposal.
Completely removing the AuthenticationHandlerImpl.java file will show the error: the backend is returning a 302 error and the SPA is unable to detect the the user is not authenticated (axios will get a generic Network Error error)
Could you try to identify why isn't this code being executed: https://github.com/vert-x3/vertx-web/blob/4e9e2c40e0843e7abb4ddc8feae021cdb17d6a41/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java#L129
I saw it wrong, I think @bfreuden fix is correct. the missing check on 302 looks correct. Maybe you can add it and a test to verify the behavior?