How to send bearer token through header of axios call in react redux

9.8k views Asked by At
  [HttpPost("xxxxxxxxxx")]
        [Authorize(Roles = "xxxxxxxxx")] 
        public IActionResult Post([FromBody]xxxxxxx xxxxxxxxxxxxxx)
        { 
            if (s == null)
            {

            }

        }

the above code is attribute Authorize(Roles ="Director"). My application roles are student, Director,Manager. This particular method has to be accessed only by director, and for the above method It is giving me back 401 unauthorized.

export function xxxxxxxxxxxx(token, formValues) {

        return axios.post(`${ROOT_URL}/xxxxxxx/xxxxxxxx`, formValues);

    }
}

I am not sure how to send bearer token in header through axios call.

3

There are 3 answers

0
Dominique Alexandre On

If sending requests to a Web API controller, you need to send the authorization token in the header Authorization, eg : "Bearer xxxxxxxx".

0
Sankar On

You just need to pass the Bearer jwt token as the third parameter.

axios.post(url, data, {
'headers': {
  'Authorization': 'Bearer ' + jwtStr
});
0
JorUge Ferrari On

You can try configuring it in API const declaration like this:

apiClient.ts content:

import axios from 'axios';

const token = 'POINT YOUR TOKEN LOCATION HERE'

const api = axios.create({
  baseURL: 'http://127.0.0.1:3333'
});

axios.defaults.headers = {
  Authorization: 'Bearer ' + token
}

export default api;