The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login process works smoothly and returns the JWT token, I face a 401 error (

Authentication credentials were not provided
) when trying to fetch data from other endpoints. Interestingly, using curl commands in my terminal works perfectly fine.

For instance, running

curl -X POST -d "username=test&password=test" http://localhost:8000/api/token/auth/
successfully returns the token.

Similarly, executing

curl -H "Authorization: JWT <my_token>" http://localhost:8000/protected-url/
retrieves the desired response from the website.

In my Vue project setup, here's what I have implemented:

Login.vue

<script>
import Vue from 'vue'

export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: ''
    }
  },

  methods: {
    login: function (username, password) {
      let user_obj = {
        "username": username,
        "password": password
      }
      this.$http.post('http://192.168.1.151:8000/api/token/auth', user_obj)
      .then((response) => {
        console.log(response.data)
        this.$session.start()
        this.$session.set('jwt', response.data.token)
        Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token

        // this.$router.push('/')

      })
      .catch((error_data) => {
        console.log(error_data)
      })
    }
  }
}
</script>

HereIWantUserGETRequest.vue

<script>
export default {
  data() {
    return {
      msg: "Welcome",
      my_list: []
    }
  },
  beforeCreate() {
    if (!this.$session.exists()) {
      this.$router.push('/account/login')
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData: function() {
      this.$http.get('http://192.168.1.151:8000/api/user/data')
        .then((response) => {
          console.log(response.data)
          this.my_list = response.data
        })
        .catch((error_data) => {
          console.log(error_data)
        })
    }
  }
}
</script>

Furthermore, I have included VueSession and VueResource in my main.js file:

import VueSession from 'vue-session'
import VueResource from 'vue-resource'

Vue.use(VueResource)
Vue.use(VueSession)

Answer №1

Modify

Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token

to

Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token

I trust this adjustment will be beneficial for you

Answer №2

Storing your JWT token in Vue is done differently than traditional methods using cookies or localStorage. In Vue, the token is held in memory only for the duration of the current page's runtime (in a single-page app scenario) where the token was requested. The default setting in VueSession does not store the token in the browser, but you can enable this feature by setting it to true.

#main.js

var options = {
  persist: true
}

Vue.use(VueSession, options)

Personally, I prefer not to use VueSession and opt to manage tokens manually using axios, Vuex, and localStorage. It's actually quite simple to implement and you can find a good guide on best practices for authentication in Vue here.

Answer №3

The issue was related to the following line of code

Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token
. I resolved it by adding the following snippet to my main.js file:

if (this.$session.exists()) {
      var token = this.$session.get('jwt')
      console.log(token)
      Vue.http.headers.common['Authorization'] = 'JWT ' + token
}

After making this update, everything is functioning as expected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger a method within a component when there is a change in the Vuex state

I need to trigger a method inside a component whenever the vuex state changes in TypeScript and Vue.js. While I can access the vuex state value using getters in the template, I am unsure how to access the data within the component class. The vuex state is ...

Updating the material-ui checkbox state to reflect the checked, unchecked, or indeterminate status, can be achieved in reactjs without relying on state

I am currently using Material-UI checkbox components and I have a requirement to programmatically change the state of checkboxes to be checked, unchecked, or indeterminate based on the click of another checkbox. This action needs to be applied to a list of ...

Display error messages upon submitting the form

I am currently working on an Angular 6 Form with validation. My main goal is to display error messages only after the form has been submitted. It is crucial that these messages remain constant while the user types in the input field. For instance, if a use ...

Creating a message sniping command with Discord.js

I'm having trouble getting my bot to log/snipe a message when someone says 'zsnipe'. I want to make 'zsnipe' a command, but it's not working. Could you let me know what I'm doing wrong? Here is the code snippet: bo ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

How can I generate a list of JavaScript files to be included in a template for both production and development environments using Grunt?

I need a way to organize a list of JavaScript files in one central location, either within gruntfile.js or an external JSON file, and then dynamically implement it into a template for both development and production environments. List of JavaScript files: ...

Is there a method to remove a buffer in threejs in order to minimize GPU memory leakage?

I am facing an issue with a large mesh containing over 5 million triangles. I utilized BufferGeometry with attributes such as position, color, normal, and index. However, there comes a point where I need to remove certain indices from the index attribute. ...

Using JavaScript promises to handle connection pooling and query execution

I am contemplating whether this approach is on the right track or if it requires further adjustments. Should I consider promisifying my custom MySQL getConnection method as well? request: function(queryRequest) { return new Promise(function(re ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Is the current version of NPM React-router too cutting-edge for your needs

When I use the command npm -v react-router on my React app, it shows version 6.9.0. However, when I check the npmjs page for react-router, the latest version available is 5.0.1. How can this discrepancy be explained? ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

"Responding to an Ajax request with a .NET Core server by sending an xlsx

My web application exclusively supports .xlsx files. I have implemented a function in my controller that converts .xls files to .xlsx format successfully. When trying to open a .xls file, I send it via an Ajax request. However, the converted .xlsx file do ...

I possess an array containing objects of different lengths depending on the chosen city. How can I pinpoint the element that contains an object with a specific property?

My dilemma arises from the fact that the length of an array depends on the selected city, making it impossible to select elements using an index. In this scenario, I need to devise a method to choose elements based on the value of one of their properties. ...

Subpar resolution of PNG images displayed in HTML canvas

My attempt to draw a PNG image onto the canvas is resulting in poor quality. I am using the drawImage method as shown below: src = folder+self.cur+".png"; imageObj.src = src; imageObj.onload = function() { context.clearRect(0, 0, cv, ch), context.drawImag ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

Can one retrieve an express session using the sessionID given?

I have a NodeJS Express application with express-session that works well, however, it needs to be compatible with a cookie-less PhoneGap app. My question is: Can I access the data in an express session using the sessionID? I was thinking of adding the se ...

Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate". However, it seems that the server side is blocking any sort ...