xaisoft
xaisoft

Reputation: 3451

Generate a secret key for JWT?

Currently I have a hard-coded secret key I use for my JWT Token Generation. What is the best way to generate this randomly when generating the token? Also, what I don't understand is if the secret is randomly generated, how can it be that the secret would be randomly generated again for authentication purposes. Am I missing something here or am I way off on how this works? It appears that the secret key is not even random. Is it something I would store in web.config for example

Upvotes: 6

Views: 17758

Answers (2)

sbeskur
sbeskur

Reputation: 2290

Just expanding on @nodd13's post to I have used the following (in LinqPad) to randomly generate a key:

var key = new byte[32];
RNGCryptoServiceProvider.Create().GetBytes(key);
var base64Secret = Convert.ToBase64String(key);
// make safe for url
var urlEncoded = base64Secret.TrimEnd('=').Replace('+', '-').Replace('/', '_');

urlEncoded.Dump();

This is indeed random and as I understand it you only need to do this once and you can then store this in your web.config to be referenced later.

Upvotes: 5

nodd13
nodd13

Reputation: 178

I used the following code from this blog post

var key = new byte[32];
RNGCryptoServiceProvider.Create().GetBytes(key);
var base64Secret = TextEncodings.Base64Url.Encode(key);

Upvotes: 3

Related Questions