2

I'm not sure I'm right on track. Please give me a hint or direction.

I set up my Web service using Django and also made mobile app with React Native using Django REST framwork. Django uses the basic session authentication, but Django REST API uses token authentication to process the request from mobile app.

I want to implement small ReactJS app into my existing Django web. At this stage, I think my small react app will need auth token to communicate with REST api for itself.

So, my idea is that when user logs in web login page, user's API token needs to be received from API and save into cookie or localStorage while normal log in process is processing in Django Web service. Because I don't want to let users log in again to run react app on my web page to get auth token.

Am I right on track? if so, how can I make it works? Please refer to my code in Django login view.py Do i need to some code in order to get API auth token and save it into client side?

def Login(request):
    if not request.user.is_authenticated:
        if request.method == "POST":
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(email = email, password = password)

            if user is not None:
                login(request, user)
                messages.add_message(request, messages.SUCCESS, request.user.nickname + ' Welcome!')
                return redirect('Search')
            else:
                messages.add_message(request, messages.WARNING, 'Please check Email / Password again')
                return redirect('login')
        else:
            form = LoginForm()
            return render(request, 'login.html', {'form': form })
    else:
        return redirect('main')
mununki
  • 350
  • 4
  • 16

3 Answers3

0

You have done some useless in your login function. you can use jwt. it has some good function for supporting login. In its login function, when send username and password with post, it return token to client. http://getblimp.github.io/django-rest-framework-jwt/

You just need set urlpattern

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]

It return token

$ curl -X POST -d  "username=admin&password=password123" http://localhost:8000/api-token-auth/

In other request, if you need authentication, use following request

$ curl -H "Authorization: JWT <your_token>" http://localhost:8000/protected-url/
Ali
  • 2,541
  • 2
  • 17
  • 31
  • If I understand correctly, it doesn't matter the way of authentication of Django REST API in my case. I want to implant the seperated small react app into my existing web page, so I need somehow auth way for react app to use once user logged in Django web in order to avoid input id/pw again. – mununki Jun 07 '18 at 04:59
  • I have not worked with react. But in angular, we store received token in localStorage, and for each request needs to auth, first check that if the localStorage stored token or not. And if stored, we use it in the request. – Ali Jun 07 '18 at 05:58
0

They both carrying out similar tasks with few differences.

Token

DRF's builtin Token Authentication

  1. One Token for all sessions
  2. No time stamp on the token

DRF JWT Token Authentication

  1. One Token per session
  2. Expiry timestamp on each token

Database access

DRF's builtin Token Authentication

  1. Database access to fetch the user associated with the token
  2. Verify user's status
  3. Authenticate the user

DRF JWT Token Authentication

  1. Decode token (get payload)
  2. Verify token timestamp (expiry)
  3. Database access to fetch user associated with the id in the payload
  4. Verify user's status
  5. Authenticate the user

Pros

DRF's builtin Token Authentication

  1. Allows forced-logout by replacing the token in the database (ex: password change)

DRF JWT Token Authentication

  1. Token with an expiration time
  2. No database hit unless the token is valid

Cons

DRF's builtin Token Authentication

  1. Database hit on all requests
  2. Single token for all sessions

DRF JWT Token Authentication

  1. Unable to recall the token without tracking it in the database
  2. Once the token is issued, anyone with the token can make requests
  3. Specs are open to interpretations, no consensus on how to do refresh

Reference: Django : DRF Token based Authentication VS JSON Web Token

Ali
  • 2,541
  • 2
  • 17
  • 31
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