8

I have an API hub that I've built in Django and a frontend end application I've built in NextJS. I'm currently working on authenticating to the Django API in Nextjs and I'm curious about best practices.

Currently, the NextJS app posts the users username/password to an endpoint. This endpoint either returns the users token or the error illustrating the issue.

React

  const login = async () => {
    let token = await axios.post('/api/accounts/', {
      email: email,
      password: password
    }).then(r => r.data.token).catch(function (error) { console.log(error) })

      if (token) {
        router.push({
            pathname: '/home/',
            query: { token: token },
          })
        }
      }

nexjs server api/accounts

export default async (req, res) => {
  if (req.method === 'POST') {
    try {
      // retrieve payment intent data
      const {data} = await axios.post('https://website/api/api-token-auth/', req.body)
      res.status(200).send(data)
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message })
    }
  } else {
    res.setHeader('Allow', 'POST')
    res.status(405).end('Method Not Allowed')
  }
}

Django API

@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def obtain_auth_token(request):
    email = request.data.get("email")
    password = request.data.get("password")
    if email is None or password is None:
        return Response({'error': 'Please provide both email and password'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(email=email, password=password)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)

    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)

Once I receive the token I push the user to the homepage.

My questions are:

  1. Is how I'm authenticating users a good way to do this? Am I overlooking something? This is the first time I've attempted to authenticate to something I've built so I want to get this right.

  2. How should I store this token? What is "best practice" when it comes to authentication creds? I've thought about passing the token around to every component that needs it. I've also peeked at using LocalStorage but again am unsure what most people do in these situations.

Any help you all can provide would be much appreciated!

Thanks in advance!

grigs
  • 1,140
  • 3
  • 15
  • 28

1 Answers1

0

Is how I'm authenticating users a good way to do this? Am I overlooking something? This is the first time I've attempted to authenticate to something I've built so I want to get this right.

  • Python Backend looks really good. The only downside of your code is that you are reinventing the wheel. Token authentication is already implemented so you shouldn't worry about implementing it and you could instead directly use TokenAuthentication

  • nexjs server looks... useless? Why do you need this as a intermediate service between frontend and API REST? Anyway, you should notice that response redirection override authentication fails status code with 500 status code :

    try {
        // retrieve payment intent data
        const {data} = await axios.post('https://website/api/api-token-auth/', req.body)
        res.status(200).send(data)
     } catch (err) {
        // if err status code is 404 e.g. bad credentials, response status is 500 where it should be 404.
        res.status(500).json({ statusCode: 500, message: err.message })
     } 
    

How should I store this token? What is "best practice" when it comes to authentication creds? I've thought about passing the token around to every component that needs it. I've also peeked at using LocalStorage but again am unsure what most people do in these situations.

Don't use cookies to avoid CSRF attack. Local Storage is the "quick and easy" answer since your already using HTTPS. A downside of Local Storage is your token would be vulnerable to XSS attack but in case of such attack you would already be heavily compromised. (An XSS attacker could intercept password and login, so what's the point of accessing token?). You can find more information here

Jean Bouvattier
  • 303
  • 3
  • 19