The goal of the post is to share an idea how can we provide the basic authentication and OAuth 2 authentication for the APIs, meaning with new technologies we need to support the OAuth2 for new clients, but at the same time we still need to support the basic authentication way of securing the APIs maybe for time for existing API Users.

Basic Auth

In general, in basic auth clients call API keeping username:password in the Authorization header for the APIs. By standard basic auth annotation, the username:password will be Base 64 encoded string.

HTTP

GET /book/{id} HTTP/1.1
Host: mybooks.com
Content-Type: application/json
Authorization: Basic MzMzOjQ0NA==

OAuth 2.0

Now for the new clients, you would want to keep the API the same and change the authorization part of the API, maybe the OAuth2 token in the authorization header instead of the basic auth header, something like.

HTTP

GET /book/{id} HTTP/1.1
Host: mybooks.com
Content-Type: application/json
Authorization: Bearer eyJraWQiOiJRWk1WZ01sUGJzVkhuYk9pOGVXMWlDazVES1VGT...

With this you want your Spring Java Rest APIs to have support both authentication, depending on the client header type let the application decide the route to take for authentication.

For this to work, we will have to understand the Spring security a bit. In the Spring security, you will find the filter chain the gets executed upon any request from the client, which could be requested from web browsers, mobile clients, or Rest clients.

For the request handling, we need to configure the WebSecurityConfigureAdapter in the Spring configuration, like

#java #spring #rest api #basic authentication #spring secuirty 5 #oauth2.0

Java Spring OAuth2 and Basic Auth Support
16.55 GEEK