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.
Getting Started
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).
Auth Overview
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.
Note: Stream does not take care of signup/login for your application, but instead, it integrates around your auth solution (e.g., Auth0, Okta, in-house, etc.).
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:
const client = stream.connect(‘<KEY>’, ‘<SECRET>’); const userToken = client.createUserToken(userId);
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:
const client = stream.connect(‘<KEY>’, <USER_TOKEN>, ‘<APP_ID>’); await client.setUser({ name: ‘<USER_NAME>’, });
If you use React or React Native components, you would do something like this:
import React, { Component } from 'react'; import { StreamApp } from 'react-activity-feed'; export default class App extends Component { render() { return ( <StreamApp apiKey="<KEY>" appId="<APP_ID>" token={<USER_TOKEN>} > … </StreamApp> ); } }
For detailed and in-depth information regarding user auth, please visit the docs located at https://getstream.io/docs/#setup.
Happy coding! ✌️