Not able to access token using axios and djangorestframework-jwt












0














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.










share|improve this question



























    0














    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.










    share|improve this question

























      0












      0








      0







      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.










      share|improve this question













      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.







      vue.js axios django-rest-framework-jwt






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 13:23









      f1uk3r

      126




      126
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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/>'
          })





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53263132%2fnot-able-to-access-token-using-axios-and-djangorestframework-jwt%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            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/>'
            })





            share|improve this answer


























              0














              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/>'
              })





              share|improve this answer
























                0












                0








                0






                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/>'
                })





                share|improve this answer












                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/>'
                })






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 at 16:33









                f1uk3r

                126




                126






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53263132%2fnot-able-to-access-token-using-axios-and-djangorestframework-jwt%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine