简体   繁体   中英

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

  [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.

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

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

如果向Web API控制器发送请求,则需要在标头Authorization中发送授权令牌,例如:“ Bearer xxxxxxxx”。

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM