Hi All I am using Machine to Machine Auth Method ...
# suitescript
g
Hi All I am using Machine to Machine Auth Method but if i kept my server more then an hour then it gives me "invalid_grant" error at this point can any one help me with this (if i restart the server then i am getting access token correctly but once its expired i cannot refetch another access token)
Copy code
console.error("Error requesting access token:", error);
Copy code
const jwtHeader = {
  alg: "PS256",
  typ: "JWT",
  kid: CERTIFICATE_ID,
};

const jwtPayload = {
  iss: CONSUMER_KEY,
  scope: ["restlets", "rest_webservices"],
  iat: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + 3600,
  aud: TOKEN_URL,
};

const token = jwt.sign(jwtPayload, CERTIFICATE_PRIVATE_KEY, {
  algorithm: "PS256",
  header: jwtHeader,
});

const requestData = new URLSearchParams();
requestData.append("grant_type", "client_credentials");
requestData.append("client_assertion_type", CLIENT_ASSERTION_TYPE);
requestData.append("client_assertion", token);

const getAccessToken = async () => {
  try {
    const response = await <http://axios.post|axios.post>(TOKEN_URL, requestData, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    if (response.status === 200) {
      const accessToken = response.data.access_token;
      return accessToken;
    } else {
      console.error(
        "Error getting access token:",
        response.status,
        response.data
      );
    }
  } catch (error) {
    console.error("Error requesting access token:", error);
  }
};

const api = axios.create({
  baseURL: process.env.NETSUITE_URL,
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.NETSUITE_TOKEN}`,
  },
});

api.interceptors.response.use(
  (response) => {
    const expirationTimeMillis = jwtPayload.exp * 1000;

    console.log(
      "Token expiration time:",
      new Date(expirationTimeMillis).toLocaleString()
    );

    return response;
  },
  async (error) => {
    const originalRequest = error.config;
    if (
      error.response &&
      error.response.status === 401
      // &&!originalRequest._retry
    ) {
      originalRequest._retry = true;
      const accessToken = await getAccessToken();
      if (accessToken) {
        api.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
        originalRequest.headers["Authorization"] = `Bearer ${accessToken}`;
        return api(originalRequest);
      } else {
        return Promise.reject("invalid Access Token");
      }
    }

    return Promise.reject(error);
  }
);
b
the iat and exp parameters in your jwtPayload control when your payload was created and how long it can be used for
you need to generate a new payload (and signature) whenever the exp date has been reached
although most of time you should just generate a new payload everytime you try and get an access token
g
Thanks @battk 🙌