Implement clientside token-based authentication using plain Javascript/AJAX

偶尔善良 提交于 2019-12-23 04:39:45

问题


Can anyone point me to an article that explains clientside token auth implementation using Javascript?

I found many articles on Angular but that is not what I'm looking for. That brings me to the question if it is possible to be done with Javascript.

Also how to handle scenarios when the auth server throws a 401. Is there a built in exception to detect that response? Or is a custom exception required to be implemented?


回答1:


I have personally used JSON web tokens in one of my projects. http://blog.slatepeak.com/creating-a-simple-node-express-api-authentication-system-with-passport-and-jwt is a tutorial on how to set up JSON web tokens on the server side.

Once you get the token as a response to the client side, you can store the token on window.localStorage.

var credentials = {
    username : document.getElementById("username").value,
    password : document.getElementById("password").value
};
var url = window.localStorage.getItem('appUrl');
$.ajax({
  url: url + '/register',
  type: 'POST', 
  data: { username: credentials.username, password: credentials.password },
  success: function(Data) {
           window.localStorage.setItem('token', Data.token);
          },
  beforeSend: function(xhr){xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));},
  error: function() {
          alert('Error occured');
          }
});

});

Then you can attach it in an AJAX call as a header while navigating to other pages.

$.ajax
 ({
  type: "GET",
  url: "index1.php",
  data: '{}',
  beforeSend: function (xhr){ 
     xhr.setRequestHeader('Authorization',window.localStorage.getItem('token')); 
  },
 success: function (){
  alert('Thanks for your comment!'); 
 }
});



回答2:


This worked for me..

var token = gettoken();
function getDatatypes() {
    if (isEmpty(token)) {
        token = gettoken();

    }

    var request = getDatatypesFromApi();
        request.success(function (data) {
            alert('success!');

        });
        request.error(function (httpObj, textStatus) {
            if (httpObj.status == 401)
                gettoken();
        });    
}
function getDatatypesFromApi() {
    var request = $.ajax
 ({
     type: "GET",
     url: "http://yoururl.com/",
     data: '',
     headers:{
         'Authorization': 'Basic ' + token
     },
     dataType: "json",
     timeout: 5000,
 });
    return request;
}
function gettoken() {
    var credentials = {
        username: "userid",
        password: "PASS",
        domain: "",
        extensionsAppId:"{extAppId}"

    };
    var url = "http://thelinktoresource/"
    $.ajax({
        url: url,
        type: 'GET',
        data: { userId: credentials.username, password: credentials.password, domain: credentials.domain, extensionsAppId: credentials.extensionsAppId },
        dataType: "json",
        contentType: 'application/json; charset=UTF-8',
        success: function (Data) {
            console.log(Data);
            token = Data.replace(/"/ig, ''); 
            return token;
        },

        error: function () {
            alert('Error occured');
            return "undefined";
        }
    });

}

function isEmpty(strIn) {
    if (strIn === undefined) {
        return true;
    }
    else if (strIn == null) {
        return true;
    }
    else if (strIn == "") {
        return true;
    }
    else {
        return false;
    }
}


来源:https://stackoverflow.com/questions/41863401/implement-clientside-token-based-authentication-using-plain-javascript-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!