Search code examples
c#bing-ads-api

Use existing Bing Ads API access token in new Authentication


I'm entering a method, and want to create a new Bing Ads API CampaignManagementService object.

var _campaignManagementService = new BingAds.ServiceClient<BingCampaignManagement.ICampaignManagementService>(authorizationData, BingAds.ApiEnvironment.Production);

This requires an AuthorizationData object.

var authorizationData = new AuthorizationData
{
    Authentication = authentication,
    DeveloperToken = developerToken,
    AccountId = accountID,
    CustomerId = customerId
};

And the authentication object for this is generally something like this:

var authentication = new OAuthDesktopMobileAuthCodeGrant(
    oAuthScope: OAuthScope.MSADS_MANAGE,
    clientId: clientId,
    environment: ApiEnvironment.Production
);

So far, so good, for the usual case.

However, generally, code samples and docs then say to do something like:

authentication.RequestAccessAndRefreshTokensAsync(refreshToken);

to populate the Authentication object with the access and refresh token data.

In my case, I know both the access and refresh tokens, and I'd like to create my service with them without having to pull them down and save them again. (I know the access token can expire, but in this case it has been generated/saved not long prior to this call. In this case we're coming in with knowledge of the tokens...but need to create a new service.)

Is there a way to create the service with the existing tokens?


Solution

  • Okay, so it turns out that the best approach to do this is to skip using the existing Authorizations like OAuthDesktopMobileAuthCodeGrant, and create a new class that inherits from Authorization.

    So, adding a class like:

    public class PrePulledTokenAuth : Authentication
    {
        private string AccessToken { get; set; }
    
        public StoredAuth(string accessToken)
        {
            AccessToken = accessToken;
        }
    
        protected override void SetAuthenticationFieldsOnApiRequestObject(dynamic apiRequest)
        {
            if (AccessToken == null)
            {
                throw new InvalidOperationException("OAuth access token is missing or invalid.");
            }
    
            apiRequest.AuthenticationToken = AccessToken;
        }
    
        protected override void AddAuthenticationHeaders(HttpRequestHeaders requestHeaders)
        {
            requestHeaders.Add("AuthenticationToken", AccessToken);
        }
    }
    

    Can then be easily leveraged later with:

    var authorization = new PrePulledTokenAuth(myAccessToken);