0

I have token authentication setup with DRF and VueJS. However, I can't seem to login using the combo of VueJS, axios, and the DRF token system and I don't understand why. I have CORS installed and if I manually set the token into the VueJS code, all my requests from VueJS to the DRF backend API work fine. It's just the login and getting the initial token that isn't working.

Here's my code:

Django URLs:

from rest_framework.authtoken import views
url(r'^api/token-auth/', views.obtain_auth_token)

Django middleware

class SiteLogin:
  def process_request(self, request):
    url = request.path.split('/')

    # Don't require password for the URL /api/token-auth/
    if url[1] == 'api' and url[2] == 'token-auth':
      return None

auth Service -- VueJS:

  // ... other code ...
  login (context, creds, redirect) {
    console.log(creds)
    axios.post(LOGIN_URL, creds).then((response) => {
      localStorage.setItem('token', response.data.token)
      this.user.authenticated = true

      // If a redirect link is provided
      if (redirect) {
        router.push(redirect)
      }
    }).catch((err) => {
      console.log(err)
    })
  },

Login Component - VueJS:

<template>
  <div>
    <div class='container-fluid container-fullw bg-white'>
      <div class='row'>
        <div class='col-md-4'>
          Login<br>
          <br>
          <input type='text' class='form-control' placeholder="Username" v-model='credentials.username'><br>
          <input type='password' class='form-control' placeholder="Password" v-model='credentials.password'><br>
          <button class='btn btn-primary btn-sm' @click='submit()'>Login</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import auth from '../../services/auth'

export default {
  name: 'login',
  data () {
    return {
      credentials: {
        username: '',
        password: ''
      },
      error: ''
    }
  },
  methods: {
    submit () {
      auth.login(this, this.credentials, '/')
    }
  }
}
</script>

Upon clicking "Submit" the DRF backend always returns a 401.

Edit:

Also, if I add print(request.POST) into the SiteLogin section of the Django middleware, I can see that a) the if statement returns true (it's acknowledging that it's a login URL) and b) the QueryDict is empty -- I see: <QueryDict: {}>

1 Answer 1

1

I solved it over here: https://stackoverflow.com/a/45850775/717682

Problem was that the TokenAuthentication was preventing my axios POST request from being called at all -- immediately returning a 401.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.