locked
MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous' RRS feed

  • Question

  • User-1999935109 posted

    Hi Team,

    I am trying to link to google adwords account using Oauth2 in C# .net . However, I am getting the following error,

    MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'OAuth realm="https://accounts.google.com/OAuthGetRequestToken"'. [Returned while handling POST Request]

    I had a communication regarding this with the google adwords support team. 

    But they told that this is the issue with .Net libraries

    Kindly suggest what can I do to resolve the exception

    Friday, May 31, 2019 6:45 AM

All replies

  • User283571144 posted

    Hi swapygNet,

    Accoridng to your description and error codes, we couldn't directly find out the reason why it show this error.

    Could you please post more details information codes about the owin startup class? 

    Best Regards,

    Brando

    Friday, May 31, 2019 8:53 AM
  • User-1999935109 posted

    Hi Brando,

    As per requirement, here is the adwords linking code used in my App to link to my Adwords Manager account.

    using Google.Api.Ads.AdWords.Lib;
    using Google.Api.Ads.AdWords.Util.Reports;
    using Google.Api.Ads.AdWords.v201809;
    using Google.Api.Ads.Common.Lib;
    using Google.Apis.AndroidPublisher.v2;

    public IEnumerable<adwordlink> adwordslink([FromBody] APIRequest apireq)
    {
    string token = HttpContext.Current.User.Identity.Name;

    Log("Adwords Link start:: " + apireq.servertoken + "::" + apireq.email + "::" + token);

    List<adwordlink> lst = new List<adwordlink>();
    adwordlink obj = new adwordlink();

    string act_status = "", ads_status = "";


    string custid = "******";

    try
    {
    AdWordsUser user = new AdWordsUser();
    AdWordsUser usermanager;


    AdWordsAppConfig config = user.Config as AdWordsAppConfig;
    config.OAuth2RedirectUri = "http://app.meet-emma.com/Link/OnAuthorizeButtonClick";
    OAuth2ProviderForApplications oAuth = new OAuth2ProviderForApplications(config);

    oAuth.State = "callback";
    oAuth.FetchAccessAndRefreshTokens(apireq.servertoken);


    user.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
    user.OAuthProvider = (OAuth2ProviderForApplications)oAuth;

    Customer c = new Customer();

    Selector selector = new Selector()
    {
    fields = new string[] { Convert.ToString(c.customerId), c.descriptiveName }
    };

    CustomerService service =
    (CustomerService)user.GetService(AdWordsService.v201809.CustomerService);

    Customer[] cst = service.getCustomers();
    Log("Adwords Link access token :: " + user.OAuthProvider.AccessToken);
    usermanager = new AdWordsUser();
    System.Net.WebRequest request = System.Net.WebRequest.Create("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + user.OAuthProvider.AccessToken);
    request.Method = "GET";
    Stream dataStream = null;
    System.Net.WebResponse response = request.GetResponse();
    dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
    reader.Close();
    dataStream.Close();
    response.Close();
    Userme objects = JsonConvert.DeserializeObject<Userme>(responseFromServer); // parse as array

    usermanager.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
    OAuth2ProviderForApplications oAuth1 =
    (usermanager.OAuthProvider as OAuth2ProviderForApplications);

    oAuth1.RefreshToken = "******";
    oAuth1.ClientId = "******";
    oAuth1.ClientSecret = "******";

    // Initiates the account link request

    ((AdWordsAppConfig)usermanager.Config).ClientCustomerId = "******";
    LinkOperation linkOp = new LinkOperation();
    ManagedCustomerLink link = new ManagedCustomerLink();
    link.clientCustomerId = cst[0].customerId;
    link.linkStatus = LinkStatus.PENDING;
    link.managerCustomerId = ******;
    linkOp.operand = link;
    linkOp.@operator = Operator.ADD;
    linkOp.operatorSpecified = true;

    ManagedCustomerService mcservice =
    (ManagedCustomerService)usermanager.GetService(AdWordsService.v201809.ManagedCustomerService);

    // Accepts the account link request on behalf of customer

    mcservice.mutateLink(new LinkOperation[] { linkOp });
    ((AdWordsAppConfig)user.Config).ClientCustomerId = cst[0].customerId.ToString();
    LinkOperation linkOp1 = new LinkOperation();
    ManagedCustomerLink link1 = new ManagedCustomerLink();
    link1.clientCustomerId = cst[0].customerId;
    link1.linkStatus = LinkStatus.ACTIVE;
    link1.managerCustomerId = ******;
    linkOp1.operand = link1;
    linkOp1.@operator = Operator.SET;

    ManagedCustomerService mcservice1 =
    (ManagedCustomerService)user.GetService(AdWordsService.v201809.ManagedCustomerService);

    mcservice1.mutateLink(new LinkOperation[] { linkOp1 });

    string rev = "0";

    string type = "standard";

    string cid = "";
    if (cst[0].canManageClients)
    {
    act_status = "act_mcc";

    cid = GetCustomerHierarchy(cst[0].customerId.ToString());

    Log("mcc link :" + cid);

    obj.account_type = "agency";
    }
    else
    {
    rev = revenue(cst[0].customerId.ToString());

    type = checkforexpress(cst[0].customerId.ToString());

    domain(cst[0].customerId.ToString(), token);

    act_status = rev == "0" ? (cst[0].canManageClients ? "act_mcc" : "act_paused") : "active_adwords";

    ads_status = rev == "0" ? (cst[0].canManageClients ? "mcc" : "paused") : "active";

    obj.account_type = rev == "0" ? "paused" : "active";


    }

    Database db = DatabaseFactory.CreateDatabase();
    DbCommand dbc = db.GetStoredProcCommand("SP_Name");
    db.AddInParameter(dbc, "userid", DbType.String, objects.user_id);
    db.AddInParameter(dbc, "email", DbType.String, objects.email);
    db.AddInParameter(dbc, "customerid", DbType.String, (cid == "" ? cst[0].customerId.ToString() : cid));
    db.AddInParameter(dbc, "contactperson", DbType.String, "");
    db.AddInParameter(dbc, "companyName", DbType.String, Convert.ToString(cst[0].customerId) + " - .");
    db.AddInParameter(dbc, "Token", DbType.String, token);
    db.AddInParameter(dbc, "Interface", DbType.String, "App");
    db.AddInParameter(dbc, "CurrencyCode", DbType.String, currency);
    db.AddInParameter(dbc, "Account_Status", DbType.String, act_status);
    dbc.CommandTimeout = 6000000;
    DataSet report = db.ExecuteDataSet(dbc);

    obj.cid = Convert.ToString(cst[0].customerId);
    obj.type = type;

    testmail tst = new testmail();

    if (tst.mailids.Contains<string>(objects.email))
    {
    obj.link_success = false;
    obj.IsError = false;
    }
    else
    {
    obj.link_success = true;
    obj.IsError = false;
    }
    obj.revenue = apireq.email == "******" ? "1" : rev;

    obj.success_msg_title = "Welcome To The . Family!";
    obj.success_msg = "Great, you’ve successfully connected - we’ll start analysing your account and start sending you through recommendations over the next week. You’re first set will be within you in less than an hour!";

    }
    catch (Exception ex)
    {

    Log("Adwords Link Error::1 " + token + "::" + ex.Message);

    obj.IsError = true;
    if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("NOT_ADS_USER"))
    {
    obj.failure_msg = "It doesn't look like there is a Google Ads account associate with that email. Make sure you're using the right email address. It may be different from the one used to log-in to .";
    obj.failure_msg_title = "Oops, No Account found";

    ads_status = "no_account"; obj.account_type = "noaccount";
    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("CUSTOMER_NOT_FOUND"))
    {
    obj.failure_msg = "It doesn't look like there is a Google Ads account associate with that email. Make sure you're using the right email address. It may be different from the one used to log-in to .";
    obj.failure_msg_title = "Oops, No Account found";

    ads_status = "no_account"; obj.account_type = "noaccount";
    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("ALREADY_MANAGED_BY_THIS_MANAGER"))
    {
    obj.failure_msg_title = "Nice to see you again!";
    obj.failure_msg = "It looks like your Google Ads account is already connected, If you're not seeing any data or improvements then get in touch with the team";

    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("ALREADY_INVITED_BY_THIS_MANAGER"))
    {
    obj.failure_msg_title = "Almost there!";
    obj.failure_msg = "Check your email, we’ve sent you an invitation to join and become a .";
    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("ALREADY_MANAGED_FOR_UI_ACCESS"))
    {
    obj.failure_msg_title = "It's a bit crowded in here";
    obj.failure_msg = "It looks like your account is already being managed by another team, you can change permissions by going to your settings in your Google Ads account and editing the “Account Access settings ";
    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("MAX_LINK_DEPTH_EXCEEDED"))
    {
    obj.failure_msg_title = "It's a bit crowded in here";
    obj.failure_msg = "It looks like your account is already being managed by another team, you can change permissions by going to your settings in your Google Ads account and editing the “Account Access settings ";
    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("NOT_AUTHORIZED"))
    {
    obj.failure_msg_title = "Permission Needed";
    obj.failure_msg = "In order to link your Google Ads account to . you’ll need to get admin level permission of your Google Ads account";
    }
    else if (!string.IsNullOrEmpty(Convert.ToString(ex.Message)) && ex.Message.Contains("ALREADY_MANAGED_IN_HIERARCHY"))
    {
    obj.failure_msg_title = "This account is already linked, sort of...";
    obj.failure_msg = "It looks like a manager account (MCC) ,that contains your Google Ads account, has already connected to .. If you would like to link this Google Ads account separately then you can change permissions by going to your settings in your Google Ads account and editing the 'Account Access.'";
    }
    else
    {
    _raygunClient.Send(ex, new List<string>() { "Adwords Link Error ", Convert.ToString(HttpContext.Current.User.Identity.Name) });
    Log("Adwords Link Error::: " + token + ":: " + ex.Message);//throw new WebFaultException<string>(ex.Message, HttpStatusCode.BadRequest);
    trackexceptions("Adwords Link Error:: " + token + "::" + ex.Message);
    obj.failure_msg_title = "Oops! An error has occurred ";
    obj.failure_msg = "Apologies, it looks like something didn’t quite go to plan, please try linking your account again after some time";
    obj.CrashMessage = ex.Message;
    }

    try
    {

    Database db = DatabaseFactory.CreateDatabase();
    DbCommand dbc = db.GetStoredProcCommand("Sp_Name");
    dbc.CommandType = CommandType.StoredProcedure;
    db.AddInParameter(dbc, "Token", DbType.String, HttpContext.Current.User.Identity.Name);
    DataSet ds = db.ExecuteDataSet(dbc);

    if (ds != null && ds.Tables[2].Rows.Count > 0)
    {
    obj.google_subscriptions = ds.Tables[2].Rows[0]["Google"].ToString();
    obj.fb_subscriptions = ds.Tables[2].Rows[0]["Facebook"].ToString();
    obj.analytics_subscriptions = ds.Tables[2].Rows[0]["Analytics"].ToString();
    obj.bing_subscriptions = ds.Tables[2].Rows[0]["Bing"].ToString();

    decimal gspend = Convert.ToDecimal(ds.Tables[2].Rows[0]["GSpend"]);
    decimal fspend = Convert.ToDecimal(ds.Tables[2].Rows[0]["FSpend"]);
    decimal bspend = Convert.ToDecimal(ds.Tables[2].Rows[0]["BSpend"]);

    obj.spend = Convert.ToString(gspend + fspend + bspend);
    }
    else { obj.google_subscriptions = "0"; obj.fb_subscriptions = "0"; obj.analytics_subscriptions = "0"; obj.bing_subscriptions = "0"; obj.spend = "0"; }

    }
    catch (Exception ex1)
    {
    _raygunClient.Send(ex, new List<string>() { "Adwords Link Error(GetClientAccounts) ", Convert.ToString(HttpContext.Current.User.Identity.Name) });
    Log("Adwords Link Error(GetClientAccounts):: " + token + ":: " + ex.Message);
    trackexceptions("Adwords Link Error:: " + token + "::" + ex.Message);
    }


    obj.revenue = "0";
    obj.link_success = false;


    finally
    {

    //writer.Close();
    }

    lst.Add(obj);

    return lst;

    }

    Tuesday, June 11, 2019 2:14 PM
  • User283571144 posted

    Hi swapygNet,

    Could you please tell me your application is a WCF application? If this application is a WCF application, I suggest you could try to refer to below link to solve your issue.

    https://github.com/googleads/google-ads-dotnet/issues/70 

    If this solution doesn't help you, I suggest you could create a issue on below link:

    https://github.com/googleads/google-ads-dotnet/issues 

    Best Regards,

    Brando

    Wednesday, June 12, 2019 8:59 AM