Unique random token generation in grails
Asked Answered
A

2

7

I am new with grails and on my web application i want to generate a random token with 15 characters length along with username. And tokens must be unique.

All characters from a-z and 0-9 can be use, but no special characters. I have tried to generate random token with

def generator = {String alphabet, int n -> new Random().with { (1..n).collec alphabet[ nextInt( alphabet.length() ) ] }.join() }} generator( (('A'..'Z')+('0'..'9')).join(), 9 )

but how can i append username infront of token like "JayKay586464ASDHH445"

Abiogenetic answered 12/3, 2014 at 9:47 Comment(4)
Could you explain in details? from my side username + token should work :)Cachexia
unique random token is must for my app. so i need to append username along with token genarated. but how can i append username along with generator in this caseAbiogenetic
you can just use operator "+" to concatenate stringsCachexia
Shame you can't just use UUID.randomUUID()Feinberg
C
5

How about this? The username holds the original username without the token, token is the 15 character token and uTok is the username with the token

def generator = { String alphabet, int n ->
  new Random().with {
    (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
  }
}

def token = generator( (('A'..'Z')+('0'..'9')).join(), 15 )

def username = "JayKay"

def uTok = "${username}${token}"

println "==>${uTok}<=="
Conjoined answered 13/3, 2014 at 11:37 Comment(0)
A
9

String confirmCode= UUID.randomUUID().toString() use this codeto generate token, then use "+" to concatenate string

Acroterion answered 12/3, 2014 at 10:55 Comment(0)
C
5

How about this? The username holds the original username without the token, token is the 15 character token and uTok is the username with the token

def generator = { String alphabet, int n ->
  new Random().with {
    (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
  }
}

def token = generator( (('A'..'Z')+('0'..'9')).join(), 15 )

def username = "JayKay"

def uTok = "${username}${token}"

println "==>${uTok}<=="
Conjoined answered 13/3, 2014 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.