•12 months ago
A common point of interest when integrating Stream is how to authenticate users, in addition to generating a token for use on the frontend side of the application. Whether you’re using Stream for feeds or for chat, generating an auth token is actually rather simple, and it’s easy to accomplish in just a few lines of code.
In this tutorial, we are going to cover client-side auth, which is what you need if you are using a component-based library, such as React, React Native, etc. In addition to component-based integrations, Stream supports server-side auth, which is extremely easy and only requires your application’s key and secret (we won’t be covering server-side auth in this tutorial).
To use Stream directly on your web or mobile application, you need to initialize the SDK with a user token – which must be generated server-side.
The most straightforward approach to generate tokens is to have your login/signup API endpoints return Stream’s user token together with the token/session ID that they already have:
- User signs up or logs in from your web or mobile app
- An HTTP request is made to your auth API endpoint
- Authentication proceeds as usual (validate password or session cookie, etc.)
- If the user was able to successfully authenticate, you generate a Stream token and pass it as part of the API response
- Client-side, you can use Stream’s token to initialize the UI components
Here’s an example of how you would generate the user token as explained in step 4:
Once you’ve obtained a server-side token for a user and retrieved it on your frontend, you can authenticate the user with the following code:
If you use React or React Native components, you would do something like this:
For detailed and in-depth information regarding user auth, please visit the docs located at https://getstream.io/docs/#setup.
Happy coding! ✌️