Create a random token in Javascript based on user details

后端 未结 6 810
醉酒成梦
醉酒成梦 2021-02-01 15:38

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

相关标签:
6条回答
  • 2021-02-01 15:53

    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"
    
    0 讨论(0)
  • 2021-02-01 15:54

    Checkout crypto.js project. Its a collection of cryptographic algorithms. The project has separate js files for each hashing algorithms.

    0 讨论(0)
  • 2021-02-01 15:56

    //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

    0 讨论(0)
  • 2021-02-01 16:02

    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"
    
    0 讨论(0)
  • 2021-02-01 16:10

    I use an approach similar to Kareem's, but with fewer function calls and built-in array operations for a big boost in performance.

    According to a performance test, this method also outperforms the accepted answer by a small margin. Moreover it provides a parameter n to generate any size token length from a white list of acceptable characters. It's flexible and performs well.

    function generateToken(n) {
        var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var token = '';
        for(var i = 0; i < n; i++) {
            token += chars[Math.floor(Math.random() * chars.length)];
        }
        return token;
    }
    
    0 讨论(0)
  • 2021-02-01 16:14

    It is very unlikely, but Math.random() could return 0.0. In that case, the solution of pimvdb would return "" (empty string). So, here is another solution, which returns in every case a random base36 with 10 chars length:

    function generateToken() {
        Math.floor(1000000000000000 + Math.random() * 9000000000000000)
              .toString(36).substr(0, 10)
    }
    
    0 讨论(0)
提交回复
热议问题