f1uk3r
f1uk3r

Reputation: 317

Not able to access token using axios and djangorestframework-jwt

I am trying to make an application which servers api through django rest framework and the frontend is done in vue.js2.

I am referring this blog to help me authenticating jwt via axios. I also tried this one when I couldn't make the first one run correctly

Here is my settings.py file

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    'admindash',
    'corsheaders',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    ),
    'TEST_REQUEST_RENDERER_CLASSES': (
        'rest_framework.renderers.MultiPartRenderer',
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.TemplateHTMLRenderer'
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 20,
}

JWT_AUTH = {
    'JWT_ALLOW_REFRESH': True,
    'JWT_EXPIRATION_DELTA': timedelta(hours=1),
    'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7),
}

#Cors origin
CORS_ORIGIN_WHITELIST = (
    'localhost:8080'
)
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

Here is my vue store

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

export default new Vuex.Store({
  state: {
    authUser: {},
    isAuthenticated: false,
    jwt: localStorage.getItem('token'),
    endpoints: {
      obtainJWT: 'http://127.0.0.1:8000/api/v1/auth/obtain_token/',
      refreshJWT: 'http://127.0.0.1:8000/api/v1/auth/refresh_token/',
      baseUrl: 'http://127.0.0.1:8000/api/v1'
    }
  },

  mutations: {
    setAuthUser(state, {
      authUser,
      isAuthenticated
    }) {
      Vue.set(state, 'authUser', authUser)
      Vue.set(state, 'isAuthenticated', isAuthenticated)
    },
    updateToken(state, newToken) {
      localStorage.setItem('token', newToken);
      state.jwt = newToken;
    },
    removeToken(state) {
      localStorage.removeItem('token');
      state.jwt = null;
    }
  },

  actions: {
    obtainToken(context, {username, password}) {
      const payload = {
        username: username,
        password: password
      }
      const headers= {
        'Content-Type': 'application/json'
      }

      axios.post(this.state.endpoints.obtainJWT, headers, payload)
        .then((response) => {
          this.commit('updateToken', response.data.token);
          console.log(this.state.jwt);
        })
        .catch((error) => {
          console.log(error);
        })
    },

    refreshToken () {
      const payload = {
        token: this.state.jwt
      }

      axios.post(this.state.endpoints.refreshJWT, payload)
        .then((response) => {
          this.commit('updateToken', response.data.token);
          console.log(this.state.jwt)
        })
        .catch((error) => {
          console.log(error)
        })
    }
  }
})

and here is login.vue

<script>
import axios from 'axios'
import FormInput from './FormInput'

export default {
  name: 'Login',
  components: {
    FormInput
  },
  data () {
    return {
      username: '',
      password: ''
    }
  },
  computed: {
    /* ...mapState([
      'jwt',
      'endpoints'
    ]) */
  },
  methods: {
    /* ...mapActions([
      'obtainToken'
    ]), */

    authenticateBeforeSubmit () {
      this.$store.dispatch('obtainToken', {
        username: this.username,
        password: this.password
      }).then(() => {
        this.$router.push('/')
      }).catch((error) => {
        console.log(error)
      })

      /* const payload = {
        username: this.username,
        password: this.password
      }
      axios.post(this.$store.state.endpoints.obtainJWT, payload)
        .then((response) => {
          this.$store.commit('updateToken', response.data.token)
          console.log(this.$store.state.jwt);
          const base = {
            baseUrl: this.$store.state.endpoints.baseUrl,
            headers: {
              Authorization: `JWT ${this.$store.state.jwt}`,
              'Content-Type': 'application/json'
            },
            xhrFields: {
              withCredentials: true
            }
          }

          const axiosInstance = axios.create(base)
          axiosInstance({
            url: "/user/",
            method: "get",
            params: {}
          })
            .then((response) => {
              this.$store.commit("setAuthUser", 
              {authUser: response.data, isAuthenticated: true}
              )
              this.$router.push({name: 'Home'})
            })
        })
        .catch((error) => {
          console.log(error);
          console.debug(error);
          console.dir(error);
        }) */
    }
  }
}
</script>

Now the problem is I am getting two errors

  1. Just as I load login view in browser, i get this error

    Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined at isURLSameOrigin (VM34519 isURLSameOrigin.js:57) at dispatchXhrRequest (VM34513 xhr.js:109) at new Promise () at xhrAdapter (VM34513 xhr.js:12) at dispatchRequest (VM34521 dispatchRequest.js:59) isURLSameOrigin @ VM34519 isURLSameOrigin.js:57 dispatchXhrRequest @ VM34513 xhr.js:109 xhrAdapter @ VM34513 xhr.js:12 dispatchRequest @ VM34521 dispatchRequest.js:59 18:29:09.976

I don't have slightest idea what this error is about, I searched it and i didn't find anything that works

  1. This I get when I click submit which fires authenticateBeforeSubmit method

    Uncaught TypeError: Cannot read property 'dispatch' of undefined at VueComponent.authenticateBeforeSubmit (VM34576 Login.vue:68) at invoker (VM34494 vue.esm.js:2026) at HTMLButtonElement.fn._withTask.fn._withTask (VM34494 vue.esm.js:1825) authenticateBeforeSubmit @ VM34576 Login.vue:68 invoker @ VM34494 vue.esm.js:2026 fn._withTask.fn._withTask @ VM34494 vue.esm.js:1825 18:29:30.912

What i understand it is saying that i am calling dispatch on action incorrectly but i don't get how to make it work

As I click submit it "redirects" to

http://127.0.0.1:8080/login?username=f1uk3r&password=thisissparta

but it doesn't recieves any token

I have tested token using

curl -X POST -H "Content-Type: application/json" -d '{"username":"f1uk3r","password":"thisissparta"}' http://127.0.0.1:8000/api/v1/auth/obtain_token/

and it gives me a token so there shouldn't be any problem in django part I think. What am I doing wrong, how can I rectify it.

Upvotes: 1

Views: 723

Answers (1)

f1uk3r
f1uk3r

Reputation: 317

I figured it out, so answering for future reference and if anybody else finds this useful

  1. TypeError: Cannot read property 'protocol' of undefined at isURLSameOrigin

this can be solved by importing axios and VueAxios correctly

I initialized it like this

import Vue from 'vue'
import VueAxios from 'vue-axios'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex);
Vue.use(axios, VueAxios);

While it should have been initialized like this

import Vue from 'vue'
import VueAxios from 'vue-axios'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex);
Vue.use(VueAxios, axios);
  1. Cannot read property 'dispatch' of undefined at VueComponent

Again I wasn't initializing store correctly so i made a directory in "src" directory named it "store" and in this directory I made a file named "store.js"

Then in main.js import store and initialize in the instance

import store from './store/store.js';


Vue.use(VeeValidate);


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

Upvotes: 1

Related Questions