Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
643 views
in .Net Framework by 31 42 54
I am working on an API solutions and I want to create token that allow me to consume api for my solution, How can I do that in soluation?

1 Answer

1 like 0 dislike
by 31 42 54
edited by
 
Best answer

Generate a JWT Token for Authentication

To create token, you should follow the below steps in details:

  1. Navigate to the Web.config file and access the appSettings section.
  2. Add in appSettings 5 key and it's value
    • Key ClientId and value is APPLICATION_Client
    • Key ClientSecret and value is APPLICATION_Secret/
    • Key GrantType and value is client_credentials
    • Key Scope and value is APPLICATION_SCOPE
    • Key TokenURL and value is TOKEN_URL
  3. Retrieve values from previous keys in the Web.Config file of the MVC application

     static string ClientId = ConfigurationManager.AppSettings["ClientId"];
     static string ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
     static string GrantType = ConfigurationManager.AppSettings["GrantType"];
     static string Scope = ConfigurationManager.AppSettings["Scope"];
     static string TokenURL = ConfigurationManager.AppSettings["TokenURL"];
    
  4. Develop a method that generates a token for authorizing the application to invoke the API

      public static async Task<Test> CreateToken()
      {
           var session = System.Web.HttpContext.Current.Session["TokenSession"];
           if (session != null && ((Test)session).ExpireIn > DateTime.Now)
           {
                   return (Test)session;
           }
    
             using (HttpClient client = new HttpClient())
             {
                 var paramss = new Dictionary<string, string>();
                 paramss.Add("client_id", ClientId.ToString());
                 paramss.Add("client_secret", ClientSecret.ToString());
                 paramss.Add("grant_type", GrantType.ToString());
                 paramss.Add("scope", Scope.ToString());
    
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
    
                  try
                  {
                       var response = client.PostAsync(TokenURL, new FormUrlEncodedContent(paramss)).Result;
    
                       var token = response.Content.ReadAsStringAsync().Result;
    
                      if (response.IsSuccessStatusCode)
                      {
                            var cu = await response.Content.ReadAsStringAsync();
                            var SelectedObject = JsonConvert.DeserializeObject<Test>(cu);
                            SelectedObject.ExpireIn = DateTime.Now.AddSeconds(int.Parse(SelectedObject.expires_in));
                            System.Web.HttpContext.Current.Session["TokenSession"] = SelectedObject;
                            return SelectedObject;
                      }
                      else
                      {
                            throw new Exception("يوجد مشكلة في الاتصال الخارجي بالنظام");
                      }
                  }
                  catch (Exception ex)
                  {
                            throw new Exception("يوجد مشكلة في الاتصال الخارجي بالنظام");
                   }
               }
      }
    

P.S: Test Class : The return type of the CreateToken method should include essential variables, notably access_token.

public class Test
{
    public string access_token { get; set; }
    public string expires_in { get; set; }
    public string token_type { get; set; }
    public string scope { get; set; }
    public DateTime ExpireIn { get; set; }

}

Result:

CreateToken

If you don’t ask, the answer is always NO!
...