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

Steps for creating a basic prioritized event listener system in JavaScript

I am currently working on an event/listener manager that has the following function: var addListener = function(event, listener) { myListeners[event].push(listener); //assume this code works } However, I now need to modify it so that it appears a ...

determining the quantity within a collection of items

Is there a way to determine the order of an element within a set when clicked? For example, if I click on the third element in a set, can I get it to display as three? Check out this jsfiddle example for reference: http://jsfiddle.net/vtt3d/ ...

The state of XMLHttpRequest always remains in a perpetual state of progress, never

I have come across an MVC Core application. One of the methods in this application currently has the following structure: public IActionResult Call(string call) { Response.ContentType = "text/plain"; return Ok(call); } In addi ...

Ways to match a string against a numeric value

I have a span id with textContent which have their own time(hour/minutes) <div class="here"> <span class="time" >8 min</span> </div> <div class="here"> <span class="time" >22 min&l ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

Received TypeError: Unable to call reset function - issue clearing input field post ajax request

Having Trouble Clearing Input Fields After AJAX Request: $.ajax({ type: "POST", url: "river_flow.php", data: { username: $("#username").val(), idv:$("#idv").val(), comment: $("#comment").val()}, cache: false, success: function(da ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

What steps can I take to resolve the CSP errors I am experiencing?

I am currently working with NextJs@12 and I am attempting to set up CSP for my application. Unfortunately, I keep encountering errors in my console and I cannot figure out where I am going wrong. Below is the current policy that I have in my next.config fi ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

Axios is experiencing challenges in transmitting the cookie

Even after attempting to include {withCredentials: true}, I am still facing issues with sending the cookie to the backend server. return await axios.post(`${API_URL}/posts/category/${id}`, { withCredentials: true }) https://i.stack.imgur.com/Cr8xv.png ...

What causes the malfunction of the save function in express?

Today marks my first venture into using Express. I attempted to create a straightforward route, but unfortunately, my save function is not cooperating. Despite scouring similar inquiries on stackoverflow, I have been unable to find a solution. Any assistan ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...

How can I display lowercase am/pm instead of uppercase AM/PM with angularjs date filtering?

Hi there, I'm a newcomer to AngularJS and I have a specific requirement. The server is sending me two dates: start_date and end_date. In the scenario where both dates are in 'pm', such as Sun 29 Jan 5.00 pm to Sun 29 Jan 6.00 pm, I would li ...

Can you explain the meaning of <!-- in javascript?

Have you ever noticed the <!-- and --> characters being used around JavaScript code like this: <script type="text/javascript"> <!-- function validateForm() { if(document.pressed == 'Submit') { ...

The Angular service encounters issues when interacting with REST API

Within my application, a template is utilized: <div class="skills-filter-input" ng-class="{'hidden-xs': skillsFilterHidden}"> <input type="text" ng-model="skillQuery" ng-change="filterSkills()" placeholder="Filter skills" class="filter- ...

Adding v-model to a button within a child component and then binding it within the parent component: a step-by-step guide

Currently utilizing Vue3 with the options API As displayed in the code snippet below, within the NotifDimsToLSRIncomformability component, there is a button. The NotifDimsToLSRIncomformability component is then nested inside a parent component as illustra ...

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

Vue's inability to compare an object property with a string leads to failure

Conclusion: It was a typo. I am facing an issue in Vue where I cannot seem to compare two values properly. I have an id and an object, but when I loop through the object properties to check if the ids match, it always returns false even though they appear ...

React Object Array Item State management

After spending a considerable amount of time on this task, I have been trying to achieve the functionality of changing a checked value upon checkbox click. Here is how my initial state is set up: const [todoList, setTodoList] = useState({ foundation: ...

What is the correct way to position a material-ui icon within a button for proper alignment?

Is there a way to properly align the <ChevronRightIcon> within the <PrimaryButton>? I want it to appear after the button label on the right side. https://i.stack.imgur.com/dcEWo.png <PrimaryButton style={{ paddingRight: &apo ...