Search code examples
c#jwtasp.net-core-webapi.net-5api-security

How to know the secret key of JWT and where to store it on windows server


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.


Solution

  • 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));