简体   繁体   中英

How to create a secure token for an app?

Im working on a simple app, that allow the user to login. Im using an ajax function pass the values to a PHP file(on a different domain). If the user and the password are correct the page display echo"success" and im using that word to validate and create a random key to allow the user access to a private page.

I was reading that you can also add a header token, it is possible to add that to my current code.. Iam new in developing "app", hope some one can point in the right direction on what is the best way to do this.

var username = $("#username").val();
    var password = $("#pass").val();


    var dataString = "username="+username+"&pass="+password+"&insert="; 
    $.ajax({
        type: "POST",
        url: "url",
        data: dataString,
        crossDomain: true,
        cache: false,
        beforeSend: function() {$('#loginButton').val('Connecting...');},
        success: function(data)
        { 
            if(data == " success")
            {
                alert("Success");
                returnHash(); 
            }

            if(data == " Login failed")
            {
                alert("There's a problem with username/password!");
                $('#loginButton').val('Submit');  
            }
        }
    });

function returnHash()
{
    letters = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
    window.token=""; 
    for(i=0;i<64;i++){
         window.token += letters[Math.floor(Math.random()*letters.length)];
    }
    success();
}

To create a real unique hash, use the current time with an random generated number like in the code below:

var dateForHash = (new Date()).valueOf().toString();
var createRandomNum = Math.random().toString();
crypto.createHash('sha1').update(dateForHash + createRandomNum).digest('hex');

You can also use crypto.randomBytes() - this hash is practical unique but not theoretical.

var hash = crypto.randomBytes(20).toString('hex');

I would recommend the second way for this type of use.

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