Search code examples
c#restapioauthnewsletter2go

Receving access token from api with oauth in c#


I want to use Newsletter2Go API. I've downloaded a c# example, added the compiled library and tried to getting started with receiving a access token. I'm new to programming with a REST-API but as far as I've understand I need to connect with my api-key and credentials to receive the access token. With the token I can do further operations.

This is the code for receving the token.

        //////// Configure HTTP basic authorization: Basic
        Configuration.Default.Username = "";
        Configuration.Default.Password = "";
       
        var apiInstance = new AuthorizationApi();
        var grantType = "";  // string | grant_type (default to https://nl2go.com/jwt)
        var username = "";  // string | username. Required for grant_type https://nl2go.com/jwt (optional) 
        var password = "";  // string | password. Required for grant_type https://nl2go.com/jwt (optional) 
        var refreshToken = "";  // string | refresh_token. Required for grant_type https://nl2go.com/jwt_refresh (optional) 

        try
        {
            // Endpoint for retrieving a token
            Token result = apiInstance.GetToken(grantType, username, password, refreshToken);
            Debug.WriteLine(result);
        }
        catch (Exception ex)
        {
            Debug.Print("Exception when calling AuthorizationApi.GetToken: " + ex.Message);
        }

I get the error.

Exception when calling AuthorizationApi.GetToken:

Error calling GetToken: {"error":"invalid_client","error_description":"The client credentials are invalid"}

I don't understand how I can pass the api-key to the api. In the docs they write this but there is no examplel in c# in the docs.

...and add an Authorization header with your auth key:
xhr.setRequestHeader("Authorization", "Basic " + btoa("xhr5n6xf_Rtguwv_jzr1d3_LTshikn4_0dtesdahNvp1:Kqf2Hs#Wwazl");
send the request:
xhr.send(JSON.stringify(params));

So any ideas what's missing here? Thanks in advance.


Solution

  • You need to pass the api_key in the request header. You can do the following using RestSharp:

    var client = new RestClient("https://api.newsletter2go.com/oauth/v2/token");
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Basic xhr5n6xf_Rtguwv_jzr1d3_LTshikn4_0dtesdahNvp1:Kqf2Hs#Wwazl");
    request.AddHeader("content-type", "application/x-www-form-urlencoded");
    request.AddParameter("application/x-www-form-urlencoded", "grant_type=https://nl2go.com/jwt&username={username}&password={password}", ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
    

    From the response body you can then obtain your access token.