Search code examples
c#oauth-2.0restsharp

How do I get an OAuth 2.0 authentication token in C#


I have these settings:

I then need to make a get call using a bearer token in the header.

I can get this to work in Postman, but have hit a wall trying to work out how to implement it in C#. I've been using RestSharp (but open to others). It all seems so opaque, when I thought it'd be pretty straight forward: it's a console app, so I don't need bells and whistles.

Ultimately, I want my app to (programatically) get a token, then use that for my subsequent calls. I'd appreciate anyone pointing me to documentation or examples, that explains what I'm after clearly. Everything I've come across is partial or for services operating on a different flow.

Thanks.


Solution

  • In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).

    Also, you should only need the access token URL. The form parameters are then:

    grant_type=client_credentials
    client_id=abc    
    client_secret=123
    

    Code Snippet:

    /* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */
    
    var client = new RestClient("https://service.endpoint.com/api/oauth2/token");
    var 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 then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:

    request.AddHeader("authorization", "Bearer <access_token>");