Generate a JWT Token for Authentication
To create token, you should follow the below steps in details:
- Navigate to the Web.config file and access the appSettings section.
- 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
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"];
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: