mardi 18 février 2020

How can get the 0Auth 2.0 Bearer token in C# having password crenditals

My goal is to generate the token at run time. And write it in a method where I can use this when ever a request needs authentication.

So I have the following

Access Token URL "http://example.com/connect/token"
Authentication type: Basic
Grant Type: password Username "abc@gmail.com"
password "123" ClientId "abc"
Clientsecret "123"
scope: "test"

public void AuthenticationMechanism()
        {
            var client = new RestClient("http://example.com/connect/token");

            var request = new RestRequest(Method.POST);

   request.RequestFormat = DataFormat.Json;
request.AddBody(new {grant_type = "password" , username = "abc@gmail.com" , password = "123" , ClientId "abc", Clientsecret "123"  ,  scope = "test"});
            var response = client.ExecutePostTaskAsync(request).GetAwaiter().GetResult();
            var access_token = response.DeserializeResponse()["access_token"];
        }


//this is my deserialization method
public static class Libraries
    {
        public static Dictionary<string, string> DeserializeResponse(this IRestResponse restResponse)
        {
            var JSONObj = new JsonDeserializer().Deserialize<Dictionary<string, string>>(restResponse);

            return JSONObj;
        }

    }


Aucun commentaire:

Enregistrer un commentaire