0

I have some code that's supposed to generate a new token if certain conditions are met.

In IE the token generator returns a 200 (and console logs the token) but in Chrome and Firefox I'm getting 401 errors (console logging the token shows null).

I've been looking up reasons as to why this is, but for some reason most of the SO posts I've come across have issues with IE and tokens and not Chrome.

permissionToCallAPI = new Promise(function(resolve, reject) {
      function sessionGet(key) {
        let stringValue = window.sessionStorage.getItem(key);

        if (stringValue !== null) {
            try {
                const { value, expirationDateStr } = JSON.parse(stringValue);

                if (value && expirationDateStr) {

                    let expirationDate = new Date(value.expirationDateStr);

                    if (expirationDate > new Date()) {
                        return value;
                    }

                    isAuthorized(value)
                    .then(resp => {
                        console.log("Valid Token");
                        return value;
                    })
                    .catch(err => {
                        throw "Failed Authentication.";
                    });
                }
            } catch (e) {
                console.log(e);
                window.sessionStorage.removeItem(key);
                return null;
            }
        }
        return null;
      } // sessionGet()

      // add into session
      function sessionSet(key, value, expirationInMin) {
        if (!expirationInMin) {
          expirationInMin = 59;
        }

        var expirationDate = new Date(
          new Date().getTime() + 60000 * expirationInMin
        );

        var newValue = {
          value: value,
          expirationDate: expirationDate.toISOString()
        };
        window.sessionStorage.setItem(key, JSON.stringify(newValue));
      }

      let _token = sessionGet("tokenSet");
      console.log(_token); // null in Chr (not IE)
      if (_token == null) {
        $.ajax({
          url: _RestHost + "/User/GenerateToken",
          method: "GET", // using POST gets an error
          cache: false,
          withCredentials: true,
          headers: { 
            "Content-Type": "application/json",
            "X-Requested-With": "XMLHttpRequest",
            "Authorization": _token
          },
          success: function(data) {
            sessionSet("tokenSet", data.AuthToken);
            resolve(data.AuthToken);
          },
          error: function(err) {
            reject(err);
          }
        });
      } else {
        resolve(_token);
      }
    });
Bodrov
  • 840
  • 1
  • 15
  • 29
  • Seems to me like like a _cache_ issue. – artur grzesiak Sep 13 '19 at 14:35
  • looks like a backend issue. Why and when is your backend producing 401 - Unauthorized errors? – Edwin Krause Sep 13 '19 at 14:53
  • @EdwinKrause It's definitely failing at the GET request in the ajax code block. The url is valid so I'm not sure what's causing it to fail. Probably a cache issue like what artur-grzesiak said. – Bodrov Sep 13 '19 at 14:57
  • There are some problems here. The problem is not about "token generation", but about HTTP requests. `401` error code means that you are not authorized to do that request. Inside your `sessionGet` you are returning INSIDE a `then` function (where it says `console.log("Valid Token");`) so you will never receive that token. You are always receiving a null when reaches that point. You need to check what queries are making the IE browser and the rest of browsers with some kind of inspector tool (fiddler4 for ex if using external tools or by pressing F12 and going to the network tab on the browsers) – Jorge Fuentes González Sep 13 '19 at 14:59
  • 1
    Your authorisation header confuses me: `"Authorization": _token` would be send as `"Authorization": null`... Is that what you want? – Edwin Krause Sep 13 '19 at 15:00
  • You should inspect all the request headers, not only the URL. Also, your `Authorization` header has non sense as `_token` is always null at that point. – Jorge Fuentes González Sep 13 '19 at 15:00
  • @JorgeFuentesGonzález that's what I mean... – Edwin Krause Sep 13 '19 at 15:01
  • @EdwinKrause yeah, sorry. I've written that at the same time haha. Was writting a brick with some problems and got character limit. – Jorge Fuentes González Sep 13 '19 at 15:02
  • No worries :-) . – Edwin Krause Sep 13 '19 at 15:03
  • @Bodrov As a tip, never start the house by the roof. I see some newbie problems here. You need to learn about functions and how they `return` values when you nest callbacks inside them. Also you need to learn about HTTP queries, how they are made and the meaning of the error codes. Also, following your code and understanding each line of it will help you a lot. – Jorge Fuentes González Sep 13 '19 at 15:05
  • Check this: [https://stackoverflow.com/questions/31326/is-there-a-browser-equivalent-to-ies-clearauthenticationcache](https://stackoverflow.com/questions/31326/is-there-a-browser-equivalent-to-ies-clearauthenticationcache) – Valijon Sep 13 '19 at 15:52

0 Answers0