Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a random token in Javascript based on user details

I want to create a random string (token) which can be used to identify a user whilst avoiding any potential conflicts with any other users' tokens.

What I was thinking of was an MD5 hash of navigator.userAgent + new Date().getTime() to generate the token but that requires a whole Javascript MD5 library to hash it which I don't really want to do.

It has to be made up of A-Z/0-9 characters and ideally no longer than 32 characters. I am open to all ideas. Thanks!

Just to clarify I'm not looking for any random string generator, the random string has to be generated from the users details available through Javascript and can also use time to avoid potential conflicts!

like image 268
fire Avatar asked Dec 16 '11 09:12

fire


People also ask

How to generate a random token in JavaScript?

To create a random token in JavaScript, we can use the Math. random method with the toString method. For instance, we write: const rand = () => { return Math.

What is a token in JavaScript?

Tokens: These are words or symbols used by code to specify the application's logic. These include +, -, ?, if, else, and var. These are reserved by the JavaScript engine and cannot be misused. They also cannot be used as part of variable names.


3 Answers

You could generate a random number and convert it to base 36 (0-9a-z):

var rand = function() {
    return Math.random().toString(36).substr(2); // remove `0.`
};

var token = function() {
    return rand() + rand(); // to make it longer
};

token(); // "bnh5yzdirjinqaorq0ox1tf383nb3xr"
like image 158
pimvdb Avatar answered Oct 24 '22 03:10

pimvdb


This function allows you to set the token length and allowed characters.

function generate_token(length){
    //edit the token allowed characters
    var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".split("");
    var b = [];  
    for (var i=0; i<length; i++) {
        var j = (Math.random() * (a.length-1)).toFixed(0);
        b[i] = a[j];
    }
    return b.join("");
}

Simply call generate_token

generate_token(32); //returns "qweQj4giRJSdMNzB8g1XIa6t3YtRIHPH"
like image 27
Kareem Avatar answered Oct 24 '22 04:10

Kareem


//length: defines the length of characters to express in the string

const rand=()=>Math.random(0).toString(36).substr(2);
const token=(length)=>(rand()+rand()+rand()+rand()).substr(0,length);

console.log(token(40));
//example1:  token(10) => result: tsywlmdqu6
//example2:  token(40) => result: m4vni14mtln2547gy54ksclhcv0dj6tp9fhs1k10
like image 10
Jasp402 Avatar answered Oct 24 '22 02:10

Jasp402