1

I am trying to implement JWT authentication in my Web API. I am doing this for the first time. When I Googled some tutorial, the first step is showing up to save secret key in appsettings.json file. I am stuck at that place itself. How will I know and get that secret key so that I can store it in a file. Also how will I know secret key for my each environment i.e. Dev, TEST and Prod.

Thanks in advance.

Nilesh
  • 518
  • 1
  • 9
  • 26
  • It is essentially a password, free format, just a string. It is private and should be securely kept at your server. For example you can take private part of some specific certificate and use it as key (on linux certificates kept in secure folders, in windows - it is certificate store, which handles all those security concerns by default, like access rights to certificate). – eocron Jun 29 '22 at 09:20
  • you have to decide the secret key. you don't get it from anywhere. it is like choosing password for your login. – CodingMytra Jun 29 '22 at 09:33
  • @Nitz Thanks for help. One more small help please. How to store it ideally. Is it right to store in appsettings.json file even in prods server ? – Nilesh Jun 29 '22 at 10:04
  • As I said before, ideal place for storing those - use certificate private key (in code you just search for certificate by its CN). Certificate stores exist on both *nix/windows, they are easly propagated through group policies and practically every cloud environment support certificate management. And you can delegate its management to administrator/manager/whoever has access to certificate management. – eocron Jun 29 '22 at 10:37

1 Answers1

5

Here, first we have configure our key in appsettings.json. That might be any thing with atleast 16 characters.

In Appsettings.json file, add configuration as mentioned below, "Appsettings":{"key":"this is my keyss"}

In the constructor of the controller class, initialize the configuration,

private readonly IConfiguration _config;
    public UserAuth(IConfiguration config){
                _config=config;
            }

In the place where you want that key for signing purpose, we can retrive by the following code,

var key=new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config.GetSection("Appsettings:key").Value));
Deebikaa R
  • 154
  • 3
  • 1
    And how to store it. Is it right to store in appsettings.json file even in prod server ? – Nilesh Jun 29 '22 at 10:04
  • for production server, it is recommended to use any secret management system such as [azurekeyvault](https://learn.microsoft.com/en-us/azure/key-vault/general/basic-concepts) etc – CodingMytra Jun 29 '22 at 10:40