How to use OpenID Connect for authentication and JWT for everything else - jwt

I want to use the "microservice architecture" https://www.jhipster.tech/api-gateway/ using:
my company OpenID connect provider to authenticate users from the frontend SPA
JWT for authorization (that is, JWT from the moment the user is authenticated)
I'm not sure how that's supposed to be configured, or even if it's possible at all...

There are many architectural decisions you have to take on designing full system. But if you are going to use OpenID Conenct then there are few common aspects.
First, as you have figured out you must have a OpenID Connect provider (IDP). You have several options. You may use your own IDP for this purpose. Or else your micro-services may be controlled by an API gateway (Looking at Hipster architecture it does have one) which have a built in IDP for this. Regardless, from your application endpoint, you must use id token to authenticate the end user.
Now going into micro-service consumption, I see two options you can use. If your api gateway builds security for all micro services, then gateway must do the authorization part based on access tokens. But if you are consuming micro-services directly (without interaction with a gateway) then each micro-service handle authorization individually. Both have pros and cons but it's up to you to investigate and decide.
To sum up, your SPA consume id token for end user authentication. Once authenticated, you consume micro-services using the access token (preferably a JWT as you say). Once a micro-service receive a request, it will authorise the request based on access token JWT. For this one must validate JWT claims, signature of it as well as can use token introspection against IDP which issued the token.

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.

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.

OpenID Connect / oAuth: How to allow OpenId Provider to access user's data at the Relying Party (Client) side

We're planning integration between two services: A and B.
The service A is going to be an OpenID Provider, the service B relies on it to log users in and create new accounts.
The service A also provides access to its resources via REST API using OAuth authorization, the service B uses the OAuth Access Token obtained via OpenID Authorization Code Flow.
However, there are some cases when A wants to get data from B. There is an established agreement between these services, that A can access any data from B in the scope of a user that was created via OpenID Connect.
How could I design authorization for the service B API? What could A provide to B in an HTTP request?
I'm considering things like a classic API Key, but it doesn't look natural in this workflow.
There are no direct solution to your mentioned scenario from OAuth and OpenID Connect protocol perspective.
But from what you have explained, you have OAuth 2.0 access token protected services in service A. Also, A acts as an identity provider (with OpenID Connect support). If this the case, I believe you control token issuing process and validations.
One options is to enable services from B , which are protected from OAuth 2.0 access tokens. Which is similar to what you already have in A. And to consume those services, you will have some service/client implementations bound to A. What they would do is obtain tokens from A itself to communicate with B. This can follow client credential grant from OAuth 2.0 as there is no end user involvement (scenario involve service to service interaction).
This suggested solution is similar to API key usage but with added benefit of OAuth 2.0 protocol.This allows you to generate Access tokens with limited life time and allow refreshing them if required. Also, in case you want B's services to be consumed by another client, then things are straightforward.

How to provide OAuth through services?

I have 3 services (in the real much more):
Authorization service (uses OAuth 2.0)
Frontend service
Resource service
and client (web-browser).
I store session_id, access_token and refersh_token in cookies of the user's web-browser. The user goes to Auth service, signs in and gets these tokens. After his web-browser is redirected to Frontend.
Frontend and Resource services can't validate tokens because they know a nothing about it, so they must make a request to Auth service.
The current scenarios:
The user (web-browser) sends a request to Frontend service, the Frontend sends a request to Auth service to validate access_token. If it's invalid the Frontend sends a request to refresh token using refresh_token.
If the Frontend needs an access to Resource service to process a request then the Frontend sends its client_id and access_token to Resource service. The Resource service sends a request to the Auth service to validate an access_token too.
Are my thoughts right? Or it has simpler schema?
P.S. All services use RESTful architecture.
OAuth talks about how the tokens be exchanged. What you have mentioned it seem liek you are talking about using implicit grant, which is little less secure and you may think of opting for authorisation flow.
Other than that, in microservices when you have many services and one user request pass through many downstream services, verifying the token with auth provider at each and every step might become a bottleneck.
There are ways out there by which you can skip this call to auth server and still validate the sanctity of the token without making an explicit call.
One way is to make use of JWT. These tokens are signed by the Auth provider and your services have keys which can help you validate if the token is modified on it way, and token itself has all the information you need to ensure validity of it, like expiry time, intended audience, clients, roles etc.
On login you get AT and RT. AT could be passed along to downstream for authentication and authorization and RT could be used when AT is expired.
You only need to talk to auth provider at the time of login and when you need to refresh the token.
You can read more about the JWT OAuth2.0 with JWT and OIDC to get more information around it

How to communicate frontend with microservice architecture?

I'm struggling with setting up reliable and performant solution to communicate frontend with different microservices. I do not really now how to maintain (maybe not need) CSRF between my frontend and end services
Solutions stack: PHP, Laravel Passport, JWT, oAuth 2.0, Axios
Current approach:
Actually I've started up with approach from Laravel's passport
https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript
Using oAuth 2.0 to authorize user from website A to service B.
JWT token is returned for further communication.
Token is saved in cookie within website A
Once user is authorized website A uses JWT token to manage requests without additional to oAuth server, by sending JWT token as cookie using HTTP headers (withCredentials) to authorize user.
For each website A's request there was CSRF token created from service B since user is authorized and cookie could be applied by another unauthorized website to access service B. That was killing my performance since it has to retrieve CSRF for each request made. (that what I actually assume from laravel passport approach and need to create CSRF with JWT token - maybe that was mistake)
My concerns:
Regarding to of James Ward post:
http://www.jamesward.com/2013/05/13/securing-single-page-apps-and-rest-services
The easiest way to do authentication without risking CSRF
vulnerabilities is to simply avoid using cookies to identify the user.
Cookies themselves are not the cause of CSRF vulnerabilities. It’s
using the cookies on the server to validate a user that is the cause
of CSRF. Just putting an authentication token into a cookie doesn’t
mean it must be used as the mechanism to identify the user.
From my understanding setting JWT with website A's cookie with its domain set could not be accessed via any other site from outside. Since that there is no possible way to make request to service B without accessing JWT.
So do we really need CSRF then to secure potential attack to service B while using JWT?
If so, how could I achieve the best (in term of performant) way to generate CSRF through different services to be sure that communication would not be vulnerable for attack from different sites?
Any advice will be appreciated!