Using third-party auth services for user authentication with Sanity.io

13 replies
Last updated: May 17, 2022
Hi all, I hope you have had a great day.I'm new to sanity and I'd like to ask a question that might sound silly.
I have a react application where my users log in to access some data, is it possible to handle my form authentication & authorization (jwt) using sanity or other backend programming languages like node.js and MongoDB are required to do so?
May 17, 2022, 3:51 PM
Don’t quote me on this, but I don’t think you can use Sanity as an access management system.
May 17, 2022, 3:58 PM
The closest I think you could get is crafting your own auth, or using something simple off the shelf, and calling from that back end to Sanity with the user information in place.
Supabase has auth setup with a relatively low barrier to entry, and also uses so-called row-level security; you set up "policies" about who can do what with given rows/cells, and access to perform that function is restricted to the policy (so, for example, if the user is someone besides me, no call for anything that involves someone else is going to work).

Restricting people that way, and then carrying over their data to qualify a query over here in a private dataset might work.

(I realize that completely avoids your intention for Sanity to handle the actual auth but it may be an easily-maintained/controlled fallback solution)
May 17, 2022, 4:17 PM
Hi - as
user S
said, you would likely want to use a third party auth service. Sanity users should only be those whom you intend to access the studio. You can use a separate auth system to log users into your site, and you can, technically, give them write access to sanity (for something like comments). Here is one proof-of-concept: https://www.sanity.io/guides/login-with-netlify-and-write-data-to-sanity
May 17, 2022, 4:47 PM
user F
we use magic.link to handle passwordless authentication and then generate a JWT stored as HTTP cookie using a Netlify serverless function, using profile data like roles, name, email address from our user store. Then we validate the token on Netlify edge to deal with access control when rendering our Sanity content.
The benefit of storing your session data in a client-side JWT is you don't need to constantly go back and forth with your authentication provider or user store on every page request, so you can get CDN, static page performance while still being serving dynamic / personalized content.

As long as you don't need to store sensitive data in your session / token, it works well.
May 17, 2022, 5:38 PM
The benefit of storing your session data in a client-side JWT is you don't need to constantly go back and forth with your authentication provider or user store on every page request, so you can get CDN, static page performance while still being serving dynamic / personalized content.
As long as you don't need to store sensitive data in your session / token, it works well.
May 17, 2022, 5:41 PM
user B
Are you talking about something like this? Where there's a client-side fetch involved, that only works accurately because the user info is stored? The page loading statically and getting hydrated after load with the specific info? Or is it something being built statically on-demand with all the info included and it's just that quick?
May 17, 2022, 6:24 PM
As a structure-less database, you can use Sanity for user account auth, but it is not advised. To be clear as mentioned, there are
accounts IN Sanity
that can access the studio and project management sites• and
Sanity data as an account manager
, which you can query to use as an auth tool for other applications. The later is not advised, just for security concerns. You can lock editing and viewing rights well enough to secure your content, but storing any sensitive data is going to come with an inherent risk compared to oauth, ecommerce, or other trusted platforms.

I’m trying to be clear about what is possible while steering you in the right direction
and not make it seem like there is a security issue. There isn’t an issue, but the platform is made for publishing and sharing. 😄
May 17, 2022, 6:47 PM
I would dig into ecommerce use cases as good examples here. Where you can silo your transaction and payment info that you definitely want super secure - while using sanity schemas as less secure transaction histories, product listings, classifications, and other things that you might want related to displayed info in your frontend apps or editing tools.
May 17, 2022, 6:49 PM
user S
Same concept, except JSON Web Tokens don't encrypt the content, they just provide a signature of the payload using a secret key. So as long as the token doesn't contain sensitive data, that all traffic uses SSL, and we use HTTP-only cookies, it's secure enough for our needs. We store user email, name and roles in the token, that's it.
The token gets generated once on the server during initial log in, which is done in a Netlify serverless function (not on the edge, since it also involves querying both magic.link and our user store and may exceed the 50ms limit on edge functions). Then it just gets passed back and forth in the cookies of every page request.

Our tokens will be valid for a couple of weeks. For refresh, we may do something on the edge to HTTP redirect to the auth flow to refresh the token when getting close to expiration. Not sure about that one yet.

Right now we're still building our solution, our preference would be to use 11ty serverless and assemble the pages on the Netlify edge using the token's claims to assemble the final output, using serverless edge functions to serve 100% static html to the browser. If, however, we end up suffering performance-wise, we'll process all content using 11ty at build time, with 2 flavors for each page: with access / without access, then use the JWT at the edge to pick which version to serve, and then we'll inject personalization on the client (user menu etc...).

I hope that makes sense.
May 17, 2022, 6:56 PM
user B
Thank you for taking the time to flesh that out. I have some awareness of the JWT process (and find it elegant and fascinating) and even had to write a signing function from scratch once for a PHP program. I wasn't sure what you meant by the static production though; I hadn't considered middleware but that makes a ton of sense.
It's still valuable if it's hydrated, of course, because no useful / accurate info is going to be returned from a client-side fetch unless they're armed with what they're provided at login.

In the past year I have run into a few situations with users using things like Safari on mobile that don't necessarily play nice with cookies (or even localStorage) let alone persist correctly so I wasn't sure it was possible to do
unless fully server-side but that's encouraging.
May 17, 2022, 9:39 PM
user S
In theory, worst case scenario if the cookie gets lost between browser sessions we redirect the user to our auth flow, which will start the process over with magic.link. They keep the session active on their end for 7 days after initial log in, so we'd automatically receive an auth token within the 7 day period without the user needing to get a magic link via email, which will re-hydrate the cookie, all transparent to the end user. I can live with that.
One thing I need to figure out is how to re-hydrate user permissions when our user purchases premium content access for instance. Those permissions gets updated asynchronously within seconds of the purchase; at that moment I'll need to have the user's client refresh the token to reflect the new permissions in order to have full access.

To be clear though - there is no client-side fetch. All trusted claims are generated and signed on the server, then validated and used on the edge to serve content, but there's nothing coming form the client.
May 17, 2022, 9:55 PM
user B
Ah, I see, so rather than get impeded by a lack of cookie, you stop the show to make them go get another one. We were trying to do things like remember a state (not in React, though, just literally a condition that got set for them personally because of a query param) and it was super flakey.
As I search on it, mobile devices in general seem to not like cookies (at least proportionately when compared to desktop). Plenty of tools, even major/official ones, have support threads on it. I used to think it was a bit redundant when places with sites also did apps but maybe part of that ties into, if it's on their phone, native, etc. they don't have to worry about it as much -- that perhaps phones beholden to data plans want to store and cache as much as humanly possible and so cookies are kind of a threat to that, where they'd wanna not deal with them as much as possible.

I have some questions about the user permission rehydration but I just learned about magic.link today because of you so I will have to read up first (and not hijack the thread with my curiosity
😃 )
I appreciate, once again, you taking the time to illuminate things!
May 17, 2022, 10:43 PM
Welcome! I've had issues with third party cookies on various devices, but considering all of our request will go to the same domain I'm hopeful things will work as planned. We've operated an MVC site on .Net that leveraged cookies for storing authentication token for many, many years, never had an issue.
By the way, if you're curious about JWTs Auth0 makes heavy use of them. Tons of resources there. In the end we didn't have a need for SAML SSO or a separate IdP so we went with a much leaner solution, but it's worth a look.
May 17, 2022, 10:51 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?