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

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.

Related

Sign-up/Sign-in between SPA and a REST API with OpenID Connect

Consider:
An SPA or a statically generated JAMStack website (written in Vue/Nuxt).
A REST API (Node + Express) running in the cloud.
The website is being served through a CDN.
We are required to add a Social Sign-On functionality for user convenience. The API already authenticates users with a credential based JWT (access/refresh) token flow. Social sign-on will be in addition to that.
We have selected the Authorization Code Flow as the mechanism for this implementation (instead of PKCE, because we want the SPA to use the API's access tokens instead of the authorization provider's).
Our flow is as follows:
The user clicks on a button and is directed to the Identity Provider's (in our case, Google) website to prove its identity. We provide a randomly generated state token as a request parameter to prevent CSRF attacks.
On the IdP's authentication page, the user submits their credentials and if successful, the user is redirected back to our website (the SPA) with the state token and a code as url parameters.
We then match the state value with the one that we generated on our app to defeat CSRF attacks.
We send the code value to our API in an AJAX request.
The API takes this code and our client secret and exchanges them for an identity taken with the identity provider (disregarding the access tokens as we only require proof of identity).
If the user identity is verified, the API generate a pair of access and refresh token and sends them to the SPA. (If the user does not exist in our database, it is added and similarly returned tokens for our API).
NOTE: We do not store the identity token received from the IdP on the server at all.
One receiving the response, the SPA stores the access token in localStorage, (the refresh token is stored in an HTTP only cookie by the API).
All further requests to our API from the SPA are made with the access token issued by our API, once both the refresh token and access tokens expire (through logout or timeout), the user has to re-initiate the authentication flow from step 1.
I have two questions:
Assuming that all communication between the IdP and SPA, the SPA and the API, and the API and the IdP is happening over TLS, are there any security vulnerabilities present in our process?
This one perplexes me more, how do you persist the state token that we generate during the initial request to the authentication server between page redirects? (from when we leave our SPA to authenticate on IdP's webpage to when the IdP redirects us back to our SPA). Is localStorage a secure enough option? If not, would sessionStorage suffice?
For a new project I would consider using the BFF pattern to avoid dealing with tokens at all in the SPA/browser. Because there is no secure way to deal/store tokens in the browser.
Do check out these resources for more details about why this pattern is recommended for new projects:
alert‘OAuth 2 0’; // The impact of XSS on OAuth 2 0 in SPAs
Using the BFF pattern to secure SPA and #Blazor Applications
The BFF Pattern (Backend for Frontend): An Introduction

Securing a public REST API used by one app

I need to build a REST API that will be used by one private SPA web application. The problem is that the REST API must be on a different server than the SPA, so it must allow CORS. For two layers of security, the API can require Basic Authentication over SSL plus check for the correct client IP address.
It will not be possible to have a user login process for the API, since it is a service used by the SPA. The user is already logged into the client that hosts the SPA. I will not have access to anything other than the user's ID, and the REST API will have no way to validate this user ID.
Because the user is logged into the client's server, the API can be restricted to requests from the SPA's IP address, but that still potentially could allow anyone on that server to use the API other than the SPA.
Is this adequate protection?
I am considering adding a third layer of protection in the way of an access token, but this would be also fairly simple to uncover. If you know the basic authentication information (easily obtainable) and your IP address matches the expected client IP, then you are able to call the API to get an access token.
Also, with an access token comes the complexity of dealing with expired tokens.
Is it impossible to completely secure an API that requires a web-based client?
How many layers of security are enough?

How to protect bearer tokens in a web app

I am trying to implement the Authorization Code flow described in RFC 6749 (OAuth 2.0) for a JavaScript-based application. I understand that I should use a web server back-end as a confidential client so that it can protect the access token and refresh token returned by the authorization server and not pass them on to the JavaScript front-end. Then all requests from the front-end to any protected resources go via the web server back-end, which attaches the access token to the request and proxies it on.
My question is how do I let the JavaScript front-end make use of these tokens in a secure way? I assume that I have to do something like set up a session on the web server and pass back a cookie that identifies the session. But this means that the JavaScript application then has a cookie that gives them the same privileges as if they just had direct access to the bearer tokens stored in the web server. How does having a web server to hold the tokens give extra security?
I understand that I should use a web server back-end as a confidential client so that it can protect the access token and refresh token returned by the authorization server and not pass them on to the JavaScript front-end.
No, it is a misunderstanding of the OAuth2 flows and goals.
Here is the OAuth2 main goal: your application (which can for instance be a JavaScript program running in the browser, a web server, both, etc.) MUST NOT need to know the user's credentials (most of the time a login/password pair) to access the service on behalf of the user.
Here is the way OAuth2 must be used to achieve this goal:
according to your needs, that is having a Javascript-based application running in the browser (i.e. not a node.js application), you need to use the OAuth2 implicit flow, not the authorization code flow. But of course, because your application is running in the browser, it will not be able to persist the credentials to access the resource offered by the service provider. The user will have to authenticate to the service provider for each new session on your application.
when your application needs to access the service provider when the user is not logged in, or when your application is able to persist credentials (because your application has its own credential system to identify its users), your application does not only rely on a JavaScript program running in the browser. It may rely only on a web server, or on both a web server and a JavaScript program that talks to this server. So, in those cases, you must use the authorization code flow.
So, as a conclusion, you have decided to add a web server to your application because you thought you had to use the authorization code flow. But in your case, you probably do not have to use this code flow, therefore you should select the appropriate code flow for your application: implicit code flow. And this way, you do not have to add a web server to run your application.
How does having a web server to hold the tokens give extra security?
This does not give extra security. Having a web server to hold the tokens is simply a way to let your application access the service on behalf of the user, in the background, when the user is not logged on your application.
While I agree with Alexandre Fenyo's comments, I just want to add the 2021 version. You should no longer be using the implicit flow as this is no longer considered secure.
For scenarios such as this where a JavaScript application has to handle tokens I would suggest using the Authorization Code flow with PKCE instead: https://auth0.com/docs/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce

Is it possible or even advisable to use OAuth 1.0 to secure a RESTful web API without redirecting the user to a separate provider?

I am in the process of building a RESTful web service using ASP.NET Web API, and I am considering using OAuth 1.0 as an authentication mechanism to secure the service. Our API would also be maintaining the credentials store and would therefore be the OAuth provider. Client applications using our API would be used by end users who would have to authenticate using a username and password, so I assume the client app is considered to be an OAuth consumer. The client application would make an API call to retrieve an unauthorized request token, then send along the user's credentials with the token to get an access token.
Ultimately, I could see other 3rd party applications wanting to access our application through my API, and they would use OAuth with the redirection with our application being the credentials provider.
Is this a viable way to use OAuth? Will something like DotNetOpenAuth support this scenario?
We have decided to implement OAuth 2.0, which supports various workflows, one of which includes a Resource Owner Credentials flow that allows the client to pass user credentials to the authorization server in exchange for an access token. This will serve our purposes.

OAuth2 security considerations for client_id

When using User-agent flow with OAuth2 for mobile platform, there is no way for Authorization server to authenticate the client_id of the application.
So, anyone can impersonate my app by copying the client_id (and so get all access tokens on my behalf), and this is applicable to Facebook, Foursquare,...
This is not managed by OAuth2 ? Or I missed something ?
For Web applications (Web server flow), access token is stored on the server side, and the client is authenticated using secret key.
There's no good answer. Native app callbacks typically happen via custom registered URI schemes (e.g.: callback redirection URI is something like: myapp://oauth?code=xyz123). Unfortunately, any app can claim ownership of a given protocol scheme and receive the callback.
This problem is very synonymous with trying to lock down any protocol with "trusted clients". Think of the IM networks battle to lock out 3rd party clients (in early 2000's). Eventually they gave up - since whatever client & protocol endpoints are deployed could be reverse engineered by 3rd party developers.
Note: There is also some active discussion on this topic on the OAuth WG mailing list: http://www.ietf.org/mail-archive/web/oauth/current/msg08177.html
Normally client_id is associated with site's URL - OAuth responses/redirects will be sent only to the registrated Url. So attacker will not be able to receive results of the request on own site (unless somehow your and attacker pages are on the same domain).