2

I'm new to React. I have already set up small size web service with Django backend on AWS EB. It has custom user model. And most contents are available after user logged in. It works fine.

When I start to make a mobile app with React Native, I set up the Django Rest into same place with sharing same db models with web service. I have chosen a Token authentication way for it. It works fine with React Native app on mobile. Once users log in through a mobile app, API returns auth Token. After getting Token from API, mobile app interacts with API including Token in JSON header.

During learn and develop React Native mobile app. I enjoyed it very much. So, I want to put small react app into one of my web pages, not writing a whole single page app. At this stage, one problem came to my mind that how my react app gets auth Token without inputting user ID and password again.

I spent hours to find any clue through googling, but failed. Can anyone give me a hint? How react app inside already logged web page interact with Token auth based API without log in again?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
mununki
  • 350
  • 4
  • 16
  • you could store your token. that a look at [Where to store Token](https://auth0.com/docs/security/store-tokens) – reisdev Jun 06 '18 at 14:36
  • @MatheusReis Thank you for your reference. After I read, I can't make a decision between cookies vs. localstorage. which one is more secured and suitable for my case? any further advise? – mununki Jun 06 '18 at 15:01
  • @MatheusReis one more thing, How can user get and save API token during user log in Django web page? – mununki Jun 06 '18 at 15:23

5 Answers5

0

I think you can use cookies or localStorage to save your token and then in react part just get this token out of there.

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
  • Can you advise further which one is more suitable and sercured between cookies vs. localstorage? – mununki Jun 06 '18 at 15:06
  • I'd go with localStorage because it's easier to work with. Here is a great video that explains the differences and how to use them: https://www.youtube.com/watch?v=AwicscsvGLg – Aliaksandr Sushkevich Jun 06 '18 at 15:24
  • Thank your for your comment. Can you give me another hint or reference regarding how user can get a token from API during user log in Django web? – mununki Jun 06 '18 at 15:26
  • Have a look at this article: https://medium.com/python-pandemonium/json-web-token-based-authentication-in-django-b6dcfa42a332 – Aliaksandr Sushkevich Jun 06 '18 at 15:58
  • Thank you for your reference. I've read all, thanksfully I barely figure out a direction to solve my case. I think when a user logs in through my web page, store token into cookie or localstorage during log in process, then react app will get the token to communicate with API. is it correct? – mununki Jun 07 '18 at 02:45
0

You can use localStorage to set and get the token

ex:

set - > localStorage.setItem('token', 'dac43hh5r3nd23i4hrwe3i2un32u');

get - > localStorage.getItem('token');

Ivan
  • 34,531
  • 8
  • 55
  • 100
0

For ReactJS, take a look at Where to store token. You can use localStorage or cookies.

Cookie usage:

document.cookie = cookie_name + "=" + value + ";expires=" + expire_date + ";";

PS: The expire date should be on GMT format.

localStorage usage:

// To set the token
localStorage.setItem('token', 'dac43hh5r3nd23i4hrwe3i2un32u');

// To get the token
localStorage.getItem('token');

The Django docs for Session, and read this question, it would help you.

Cookie or localStorage?

I would take cookies. Why? Because you can set expiration date(for automatic deletion, for example), domain, path and other things that can be useful. On the localStorage, you just store the info.

reisdev
  • 3,215
  • 2
  • 17
  • 38
0

I'd like to leave my answer after I solved in my way through my long research and study. My solution is quite simple. 1. set DRF session authentication enable. Adding some code in setting.py

REST_FRAMEWORK = {
# ...
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
    ),
}

2. add 'credentials: "include"' into fetch code to use already logged in session cookie for authentication.

await fetch(API_URL, {
    credentials: "include"
})

this solution solved my case.

mununki
  • 350
  • 4
  • 16
0

React you can use any libray for the calling API, ex- axios is one of them. When you do the login first time save that token in the localstorage or session.

Now we have to add that token in header for that you can user the interceptor i.e when we make API call every time interceptor will get call, at that place you can get the token from the local storage or session add the request header.

below is sample code of interceptor.

import axios from 'axios';
import cookie from 'react-cookies';
import * as utils from './utils';


let axios_instance = axios.create();

axios_instance.interceptors.request.use(
  (configuration) => {
    const config = configuration;
    const authToken = cookie.load('authToken');
    if (authToken) {
      config.headers.Authorization = `Token ${authToken}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

axios_instance.interceptors.response.use((response) => {
  return response;
}, (error) => {

  if (error.response.status == 401) {
    utils.clearCookie();
    window.location.href = '/login';
    return;
  }
  if (error.response.status == 403) {
    utils.clearCookie();
    window.location.href = '/login';
    return;
  }

  if (error.response.status == 404) {
    // window.location.href = '/not-found';
    return;
  }

  if (error.response.status == 500) {
    // window.location.href = '/server-error';
    return;
  }

  return Promise.reject(error);

});

export default axios_instance;
aman kumar
  • 3,086
  • 1
  • 17
  • 24