How to get an OAUth Access Token (to authorize) and use Spotify Web API in your React Native (Expo) App
How to get an OAUth Access Token (to authorize) and use Spotify Web API in your React Native (Expo) App

How to get an OAUth Access Token (to authorize) and use Spotify Web API in your React Native (Expo) App

Date
Jun 17, 2022
Tags
React
Expo

What is OAuth?

OAuth 2.0 is the industry-standard protocol for authorization (not authentication) - it allows a 3rd party app to have limited access to a user’s account without providing the password.
The OAuth method is a little different depending on the platform, so this article is only for Spotify. While other platforms such as Facebook, Instagram, Youtube (Google) are similar, it took me a some time to figure it out the differences so I’m posting it here - hopefully it will help you save time.

OAuth flow drawn by me

notion image
 

Watch the demo video below

Note: For this to work, you must create an app with Spotify Developers (login here: https://developer.spotify.com/)

Here’e the code:

import { useAuthRequest, makeRedirectUri } from 'expo-auth-session'; const **Spotify** = () ⇒ { const discovery = { authorizationEndpoint: 'https://accounts.spotify.com/authorize', tokenEndpoint: 'https://accounts.spotify.com/api/token' }; const generatedRedirectUri = makeRedirectUri({ useProxy: true }); const [request, response, **promptAsync**] = useAuthRequest( { clientId: 'GET YOUR CLIENT ID FROM SPOTIFY', clientSecret: 'GET YOUR CLIENT SECRET FROM SPOTIFY', scopes: ['user-read-email', 'playlist-modify-public'], redirectUri: generatedRedirectUri }, discovery ); const setAuth = async () => { try { promptAsync({ useProxy: true }); } catch (error) { console.log(error); } }; useEffect(() => { if (response?.type === 'success') { fetchAccessToken(response.params.code, request.codeVerifier); } }, [response]); const fetchAccessToken = async (authcode, codeVerifier) => { const body = { code: authcode, redirect_uri: generatedRedirectUri, grant_type: 'authorization_code', client_id: 'YOUR CLIENT ID', code_verifier: request.codeVerifier }; let formBody = []; Object.keys(body).forEach(function(key) { const encodedKey = encodeURIComponent(key); const encodedValue = encodeURIComponent(body[key]); formBody.push(`${encodedKey}=${encodedValue}`); }); formBody = formBody.join('&'); const defaultConfig = { method: 'POST', body: formBody, headers: { Authorization: `Basic ${Buffer.from( 'CLIENT_ID:CLIENT_SECRET', 'utf-8' ).toString('base64')}`, 'Content-Type': 'application/x-www-form-urlencoded' } }; const tokenObject = await fetch( 'https://accounts.spotify.com/api/token', defaultConfig ); tokenObject .json() .then(async (result) => { const { access_token, refresh_token } = result; if (access_token && refresh_token) { userData(result); } }) .catch((error) => { console.log(error); }); }; async function userData(result) { const data = await fetch('https://api.spotify.com/v1/me', { headers: { Authorization: `Bearer ${result.access_token}` } }); data.json().then((userInfo) => { // DO SOMETHING WITH USERINFO in your app! }); } }
references: