registering a rest API with OAuth - rest

I have written a web application which makes REST API calls to a message broker. The message broker contains already written REST APIs to which can be used to get message broker data. The message broker is written in a way in which each REST API call sends the user name and password which is encoded with base64. I need to make a login to my web app and authenticate it with OAuth.Does anyone know how to do this? How to authenticate the REST APIs with OAuth?

Step 1: Add OAuth 2.0 to your web server. This is very standard with lots of libraries available. You did not specify the Identity Provider that you will use (Google, Facebook, Auth0, Okta, etc), but each vendor has documents and libraries for you to use in your desired language.
Step 2: Add an Authorization Header to your API calls. The standard method is to add the HTTP header Authorization: Bearer access_token when making an API call.
Step 3: Add OAuth token verification to your API. When your API receives a request, it extracts the Authorization header and verifies the Bearer token. How this is done depends on the Identity Provider. For example, some vendors provide a Signed JWT (which you verify with the vendors public certificate), others provide an opaque access token (which you verify by calling the vendor's token endpoint). Add internal caching of tokens so that you don't need to verify on every API call.
If you understand OAuth 2.0 the above steps are straightforward to implement. If you don't Oracle has a set of videos which are excellent for getting started understanding OAuth.
Oracle Cloud Primers
If your desired OAuth implementation does not require users logging in and is a server to server service that you control on both ends, then you can use just part of OAuth which is Signed JWT (JWS). You create a Json data structure with your desired content and sign it with a private key. This creates a token that you can use in the above steps. You would then validate the token using your public key. You can use self-generated keypairs generated by OpenSSL or similar products for your signing and verification.

Related

How to perform user registration and authentication between a single page application and a REST API with OpenID Connect

Consider that we have:
An SPA or a statically generated JAMStack website.
A REST API.
The website is being served with nignx that also reverse proxies to our API.
--
It is required that a user should be able to register/authenticate with an identity provider (say, Google) through the OpenID Connect protocol. For the sake of simplicity, let us assume that the user has already registered with our API.
Talking about authentication using OIDC, from what I have read on the subject, the steps you take are the following:
Register the application with the IdP and receive a client id and a secret.
When the user initiates a login (with Google) request on the API ('/api/loginWithGoogle') the API sets a state variable on the request session (to prevent CSRF) and redirects the user-agent to the IdP's login page.
At this page, the user enters their credentials and if they are correct, the IdP redirects the user to the callback URL on the API callback (/api/callback).
The request received on the callback has the state parameter (which we should verify with the one we set on the session previously) and a code parameter. We exchange the code for the identity token with the authorization server/IdP (we also receive access/refresh tokens from the auth server, which we discard for now because we do not want to access any APIs on the behalf of the user).
The identity token is parsed to verify user identity against our database (maybe an email).
Assume that the identity is verified.
-- The next part is what's giving me trouble --
The documentation that I have read advises that from here we redirect the user to a URL (e.g. the profile page)and start a login session between the user agent and the API. This is fine for this specific architecture (with both the SPA/static-site being hosted on the same domain).
But how does it scale?
Say I want to move from a session based flow to a JWT based flow (for authenticating to my API).
What if a mobile application comes into the picture? How can it leverage a similar SSO functionality from my API?
NOTE: I have read a little on the PKCE mechanism for SPAs (I assume it works for JAMStack as well) and native mobile apps, but from what I gather, it is an authorization mechanism that assumes that there is no back-end in place. I can not reconcile PKCE in an authentication context when an API is involved.
Usually this is done via the following components. By separating these concerns you can ensure that flows work well for all of your apps and APIs.
BACKEND FOR FRONTEND
This is a utility API to keep tokens for the SPA out of the browser and to supply the client secret to the token service.
WEB HOST
This serves unsecured static content for the SPA. It is possible to use the BFF to do this, though a separated component allows you to serve content via a content delivery network, which some companies prefer.
TOKEN SERVICE
This does the issuing of tokens for your apps and APIs. You could use Google initially, though a more complete solution is to use your own Authorization Server (AS). This is because you will not be able to control the contents of Google access tokens when authorizating in your own APIs.
SPA CLIENT
This interacts with the Backend for Frontend during OAuth and API calls. Cookies are sent from the browser and the backend forwards tokens to APIs.
MOBILE CLIENT
This interacts with the token service and uses tokens to call APIs directly, without using a Backend for Frontend.
BUSINESS APIs
These only ever receive JWT access tokens and do not deal with any cookie concerns. APIs can be hosted in any domain.
SCALING
In order for cookies to work properly, a separate instance of the Backend for Frontend must be deployed for each SPA, where each instance runs on the same parent domain as the SPA's web origin.
UPDATE - AS REQUESTED
The backend for frontend can be either a traditional web backend or an API. In the latter case CORS is used.
See this code example for an API driven approach. Any Authorization Server can be used as the token service. Following the tutorial may help you to see how the components fit together. SPA security is a difficult topic though.

Approah on creating clients/realms for separate service (frontend and backend)

I'm new to keycloak and would like to check what is the common design on the said architecture.
I have 1 backend(quarkus) 1 frontend (angular) and 1 flutter.
I would like to see if I could leverage the features of client. My idea is to have a separate client within the realm. For example
REALM = MyAppRealm
Client = backend-client and front-endclient
Is it possible that the token i got from front-endclient can be use to access the api from the backend?
Reason I have this setup is that the front-endclient has a public accesstype while the backend has confidential
to sum up. I would like to see if i can reuse the token i got from front-endclient to my backend-client
Yes of course you can do that.
The purpose of openid is to share authentication and authorization between a diversity of clients without needing to share credentials (no password is known by any of the clients). A trusted third party (here Keycloak) will give back a signed token in exchange for credentials. And this token will be a proof of who the user is and what he is allowed to do in the communications between the frontend and backend.
To sum up :
Your angular frontend authenticates an user using a public client and an implicit flow. When successfully authenticated, the frontend obtains an access token and a refresh token.
When making a REST call to the backend, your frontend needs to set the header Authorization using the access token as a bearer token ('Authorization: Bearer insert access token here'). You can automate this by using an interceptor (example)
Finally, when your backend receive an API request it can check the Authorization header to ensure the request is authenticated and authorized. For how to do that with Quarkus, everything is explained in this documentation page : https://quarkus.io/guides/security-openid-connect

Mobile app authentication using Token based on OAuth2.0

I'm building a REST API using Elixir's Phoenix framework. In the API, I need to authenticate the user by phone number i.e., via sending an SMS OTP code. After authenticating the user, the Auth server sends the Access token and Refresh token to the client. The client(mobile app) stores those tokens locally and sends the Access token in the HTTP header as Authorization: Bearer <Access_Token> in every request to resource server. My actual question is, how do resource server validates the Access token that is received from the mobile app/client?
Does resource server needs to contact Auth server to validate the Access Token? That would a lot of overhead. Please help me understand RestFull API Authentication.
Thanks for taking the time to read my question.
It sounds like you have everything working up to validating the token. You are going to need the public key for the server that signed the token. It depends on what auth server you're working with on how you get that. In some cases you may be able to preload this key as a configuration setting on your backend. Otherwise you can probably get it via https request to the auth server. Most auth servers these days I expect to provide a JWKS api that you can use to get the keys you need. Then with the token and the public key you can use your elixir jwt library to validate that the token you have was signed by the server you trust, meaning the SMS code was validated, and you can proceed with whatever is needed in the backend to handle the request.
If you're using Joken for elixir you can review https://hexdocs.pm/joken_jwks/introduction.html and https://hexdocs.pm/joken/introduction.html for more information.
how do resource server validates the Access token that is received from the mobile app/client?
The same way a nightclub bouncer verifies your driving license as proof-of-age to let you in: by validating the authority and signatures, but it does not need to phone-up your DMV to verify that your license is real because it trusts the signatures (in this case, cryptographic signatures).
That said, some systems do use "reference tokens" which are short (say 32 bytes) of meaningless random data which are used as an unpredictable record identifier for some user-permissions record held by the authorization server. The resource-server will need to contact the auth server initially, but then it can simply cache the auth result itself for some time window.

I want to have Custom Keycloack Authentication/Authorization or Identity Provider

I'm googling since long and i'm bit confused now should i create Custom iDP or Authentication provider in Keycloak.
Below is my requirements.
I have multiple clients and each client having login API which also returns JWT token on successful login so what business needs is that when user try to login i want keycloack to consume client API to Authenticate User and once user successfully authenticated by Client API Keycloack should generate token for further operations.
One more problem is can i use same token return from client as Keycloack token because there are some apis on client side which decode token and use some info from token.
Please suggest and i'm bit stressed to looking for different solution and couldn't help. I will be grateful if you can share sample code with it.
What do you mean by "I have multiple clients and each client having login API" (does that mean different endpoints secured by different realms?? I supose that's not what you want).
What you mention here:
"what business needs is that when user try to login i want keycloack to consume client API to Authenticate User and once user successfully authenticated by Client API Keycloack should generate token for further operations."
that is indeed the standard behaviour of Keycloak, why do you need a custom Authentication (user federated Authentication/ identity Provider)? You haven't made clear from the description of your problem, why do you need a custom Identity Provider SPI /custom Authentication federation? If you really need an Authentication SPI, please read chapter 8 from here:
https://www.keycloak.org/docs/latest/server_development/index.html#_auth_spi
that's the best documentation on that topic. Are you authenticating against a custom Auth service of your company that doesn't support openid connect? If not, then you don't need a custom Authentication SPI.
regarding:
"can i use same token return from client as Keycloack token because there are some apis on client side which decode token and use some info from token."
I don't know exactly what you mean there, but depending on your client adapter there are slight variations on the way you get/extract a bearer token & secure your endpoints in general. Plase read chapter 3.1 from here: https://www.keycloak.org/docs/latest/securing_apps/index.html#_client_registration
There you'll find base implementations/suggestions for the different client adapters, or at least should move you forward in your search.
Hope it helps.

Basic Authentication with a Guid token for REST api instead of username/password

Overview
I am developing a mobile application using PhoneGap with REST API for the backend. The REST API won't be utilised by third-party developers, but will be application-specific, so there is no need for oAuth to be implemented. Hence, I am planning to use Basic Authentication where in the User enters their Username/password to access the API resources. All API communication will be on SSL.
Basic Authentication with Token
Instead of letting the application store the username/password and send it with every request to the API, I would rather authenticate username/password on the first login request and send a GUID token back. The client stores this GUID token and sends the token back to the API with each request through the Authorization header, like this:
Authorization: Basic e1d9753f-a508-46cc-a428-1787595d63e4
On the server side, the username/GUID combination will be stored on the server with a expiration date along with device settings. This will allow to keep track of the number of devices a user has logged in from as well as expire the session once the Guid has reached expiration.
Does this approach sound reasonable and secure?
There is no need for you to create custom headers or authentication schemes at all.
The Bearer authentication scheme is designed exactly for your use case:
Authorization: Bearer e1d9753f-a508-46cc-a428-1787595d63e4
Basic authentication must be as follows:
Authorization: Basic base64EncodedUsernameAndPassword
where base64EncodedUsernameAndPassword is equal to the output of:
base_64_encode(username + ':' + raw_password)
Do not use Basic if the trailing text value is not the above exact algorithm.
If you just want to put whatever value you want after the scheme name, use the Bearer scheme - that is what it was invented for.
Warning
While you can use a simple GUID/UUID as your token, this isn't really a secure token. Consider using a JWT instead. JWTs can be digitally signed and assigned a TTL so that only the server setting it can a) create it and validate its authenticity and b) ensure it is not used longer than is allowed. While this may be true of your data stored based on the GUID, the JWT approach does not require server state - so it scales far better - and accomplishes the same thing.
The general "Authentication with Token" approach is very good but you shouldn't try to make Basic Authentication work in different way than it is supposed to (after all it is a defined standard). You should rather use your own header for authentication purposes. You can find a very good description of such scenario here:
Making your ASP.NET Web API’s secure