Skip to content
Advertisement

error code 401, HTTP Token: Access denied

I am new to using API’s. I’ve been trying to use this API called Carbon Interface. it supposed to give an estimate of your carbon footprint based on how much electricity you use. I created this quick project to test it but whenever I try to use it I get error code 401, I look it up and it’s Unauthorized / HTTP Token: Access denied. Instead of token, I put my API key, I just used that for this question

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Axios Crash Course</title>
  </head>
  <body>
    <button id="submit">submit</button>
    <script>
        document.getElementById('submit').addEventListener("click", getdata)
        function getdata() {
            fetch('https://www.carboninterface.com/api/v1/estimates', {
              method: 'POST',
              header: {
                'Authorization': 'Bearer Token'
              },
              data: {
                "type": "electricity",
                "electricity_unit": "mwh",
                "electricity_value": 42,
                "country": "us",
                "state": "ca"
              }
              
            }).then(response => response.json())
              .then(data => console.log(data)).catch(error => {
              console.error('There has been a problem with your fetch operation:', error);
  });
        }
    </script>
  </body>
</html>

Advertisement

Answer

In your code,

header: {  'Authorization': 'Bearer Token'   },  

Token that you have written is supposed to be actual value of token. Not just some word. It should be token which is used for checking the authenticity.

Actual value of token looks something like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwYTkzODgxNmQyMGRiMDAxMWVmMjliMSIsInVzZXJuYW1lIjoic2FyaXRhZyIsInVzZXJUeXBlIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4iLCJmaXJzdE5hbWUiOiJzYXJpdGEiLCJsYXN0TmFtZSI6Imdhd2FkZSIsImlhdCI6MTYyNzAxOTI0MiwiZXhwIjoxNjU4NTc2ODQyfQ.JhdwWO_tdkq6M3aYWI-YxqZo7iLOQ9IBmFMb7Jqid5E

Here is one site: https://jwt.io/ where you can enter your payload and get the value of token. This site is at times quiet efficient.

Below is the code as to how I write to set auth token

import axios from “axios”;

const setAuthToken = token => {
  if (token) {
    axios.defaults.headers.common["Authorization"] = "Bearer " + token;
    axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
    axios.defaults.headers['Access-Control-Allow-Origin'] = "*";
  } else {
    delete axios.defaults.headers.common["Authorization"];
  }
};

export default setAuthToken;

Here is the code for generating and sending the token :

var jwt = require('jsonwebtoken');

var createToken = function(tokenObj) {
    const expiresIn = '5 days';
    const secretOrKey = process.env.JWT_TOKEN_SECRET;
    
    const token = jwt.sign(tokenObj, secretOrKey, {
        expiresIn: expiresIn
    });
    return token;
}

module.exports = {
    generateToken: function(req, res, next) {
        req.jwtToken = createToken(req.tokenObj);
        return next();
    },
    sendToken: function(req, res) {
        res.setHeader("Access-Control-Expose-Headers", "X-Auth-Token");
        res.setHeader('x-auth-token', req.jwtToken);
        return res.status(200).send(JSON.stringify(req.tokenObj));
    }
  };

I have shown you one such example. Hope this might help you.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement