Search code examples
oauth-2.0openid-connect

Where to store ID tokens and which OAuth2 flow to use in a monolithic server-side rendered web app?


I'm having trouble understanding how do I store ID tokens in a regular server-side rendered web app (for example, JSP/Servlet-based). After reading some OAuth2/OIDC guides and documentation, it seems like most of these sources assume the the client and the resource server (in OAuth2 terminology) are different applications. A really clear use case which is often described is if you have a Singe Page App (the client) and you want it to access some APIs (the resource server) on behalf of a user (the resource owner). I do understand that a classic server-side rendered web app can also be the client, but usually it is assumed that it is still separate from the resource server and it does requests to some remote APIs on behalf of a user (same as an SPA would).

My use case, on the other hand, is that I have a monolithic web app which servers as both the client and the resource server, but I just don't want to implement authentication myself (I would like to delegate authentication to an external OIDC authorization server). According to the sources I've read, I am supposed to use Authorization Code flow in the above case, which means that after successful authentication my backend will exchange the received authorization code for an ID token. But where do I store it then? Am I supposed to just create a good old session and set a cookie after that? This is certainly doable, but this defeats the purpose of using ID tokens which are self-contained JWTs. Or should I assume that ID tokens can completely substitute session/cookie combo only if they are stored on the client-side (mobile app or SPA)? Maybe I am missing something.


Solution

  • You need an ID token from an OIDC Provider (the Authorization Server in OIDC is called the OIDC Provider - OP), which means that you only want to authenticate the user. It's important to understand that separation - an OIDC flow is used to authenticate a user, not to perform session management (OIDC does provide features for session management, but I don't think it's what you're after). You get the ID token from OP to learn who the user is. That token will usually be short-lived. You can use that token to either identify the user in your database or create an account for them (if that's needed), and then, create a session. As you have a good ol'fashioned website, then go with a cookie-based session.

    This is certainly doable, but this defeats the purpose of using ID tokens which are self-contained JWTs

    No, it doesn't ;) As I mentioned, ID tokens are not a mechanism for session management. They just carry information about the authenticated user. As such, you don't have to persist them anywhere, you just need to get the information from an ID token.