OAuth 2.0 authentication in C#

HomeC#

OAuth 2.0 authentication in C#

Open a database connection asynchronously
continue vs break in C#
Building a String Encryption/Decryption Class in C#

Getting an OAuth 2.0 authentication token in C# is easy to do

For this you need only three parameters


grant_type=client_credentials
client_id=[client id]
client_secret=[client secret]

And with the following code you can get the token

RestClient client = new RestClient("https://service.endpoint.com/api/oauth2/token");
RestRequest request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=abc&client_secret=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

From the response body you can obtain your access token, and from there you can add the token to your header on subsequent authenticated requests.

request.AddHeader("authorization", "Bearer [your access token]");

COMMENTS

DISQUS: 0