Ejemplo n.º 1
0
        public Authentication getaccesstoken(string code)
        {
            string ClientSecret = "****************";

            var oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new Uri("http://localhost:52713/Default"), null);

            //var oAuthDesktopMobileAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(ClientId);

            oAuthWebAuthCodeGrant.State = "ClientStateGoesHere";
            string refreshToken;

            if (GetRefreshToken(out refreshToken))
            {
                oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(refreshToken).Wait();
            }
            else
            {
                oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(Request.Url).Wait();
            }

            oAuthWebAuthCodeGrant.NewOAuthTokensReceived +=
                (sender, args) => SaveRefreshToken(args.NewRefreshToken);

            return(oAuthWebAuthCodeGrant);
        }
        /// <summary>
        /// Authenticates the current user via OAuth.
        /// </summary>
        /// <returns>The OAuth authentication instance for a user.</returns>
        private Microsoft.BingAds.Authentication AuthenticateWithOAuth(Token token)
        {
            var apiEnvironment =
                ConfigurationManager.AppSettings["BingAdsEnvironment"] == ApiEnvironment.Sandbox.ToString() ?
                ApiEnvironment.Sandbox : ApiEnvironment.Production;

            string clientId     = TempData["ClientId"].ToString();
            string clientSecret = TempData["ClientSecret"].ToString();

            var oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(
                clientId,
                clientSecret,
                new Uri(Url.Action("Redirect", "Home", null, HttpContext.Request.Scheme).ToString()),
                apiEnvironment);

            // It is recommended that you specify a non guessable 'state' request parameter to help prevent
            // cross site request forgery (CSRF).
            oAuthWebAuthCodeGrant.State = _state;

            string refreshToken = token.RefreshToken;

            AuthorizeWithRefreshTokenAsync(oAuthWebAuthCodeGrant, refreshToken).Wait();

            return(oAuthWebAuthCodeGrant);
        }
Ejemplo n.º 3
0
        public void generatecode()
        {
            //var oAuthDesktopMobileAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(ClientId);

            string ClientSecret = "*****************";

            var oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new Uri("http://localhost:52713/Default"), null);


            // It is recommended that you specify a non guessable 'state' request parameter to help prevent
            // cross site request forgery (CSRF).
            oAuthWebAuthCodeGrant.State = "ClientStateGoesHere";

            Response.Redirect(oAuthWebAuthCodeGrant.GetAuthorizationEndpoint().ToString());
        }
Ejemplo n.º 4
0
        private static Authentication AuthenticateWithOAuth()
        {
            var webCodeGrant = new OAuthWebAuthCodeGrant(Settings.Default["ClientId"].ToString(),
                                                         Settings.Default["ClientSecret"].ToString(), new Uri(Settings.Default["OAuthRedirectUri"].ToString()));

            // It is recommended that you specify a non guessable 'state' request parameter to help prevent
            // cross site request forgery (CSRF).
            webCodeGrant.State = ClientState;

            string refreshToken;

            // If you have previously securely stored a refresh token, try to use it.
            if (GetRefreshToken(out refreshToken))
            {
                AuthorizeWithRefreshTokenAsync(webCodeGrant, refreshToken).Wait();
            }
            else
            {
                // You must request user consent at least once through a web browser control.
                // Call the GetAuthorizationEndpoint method of the OAuthDesktopMobileAuthCodeGrant instance that you created above.
                Console.WriteLine(string.Format(
                                      "The Bing Ads user must provide consent for your application to access their Bing Ads accounts.\n" +
                                      "Open a new web browser and navigate to {0}.\n\n" +
                                      "After the user has granted consent in the web browser for the application to access their Bing Ads accounts, " +
                                      "please enter the response URI that includes the authorization 'code' parameter: \n", webCodeGrant.GetAuthorizationEndpoint()));

                // Request access and refresh tokens using the URI that you provided manually during program execution.
                var responseUri = new Uri(Console.ReadLine());

                if (webCodeGrant.State != ClientState)
                {
                    throw new HttpRequestException("The OAuth response state does not match the client request state.");
                }

                webCodeGrant.RequestAccessAndRefreshTokensAsync(responseUri).Wait();
            }

            // It is important to save the most recent refresh token whenever new OAuth tokens are received.
            // You will want to subscribe to the NewOAuthTokensReceived event handler.
            // When calling Bing Ads services with ServiceClient<TService>, BulkServiceManager, or ReportingServiceManager,
            // each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code.
            webCodeGrant.NewOAuthTokensReceived +=
                (sender, tokens) => SaveRefreshToken(tokens.NewRefreshToken);

            return(webCodeGrant);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Controls the contents displayed at Index.cshtml.
        /// </summary>
        public async Task <ActionResult> bing()
        {
            try
            {
                // If there is already an authenticated Microsoft account during this HTTP session,
                // go ahead and call Bing Ads service operations.

                if (Session["auth"] != null)
                {
                    return(await CallBingAdsServices((OAuthWebAuthCodeGrant)Session["auth"]));
                }

                // Prepare the OAuth object for use with the authorization code grant flow.

                var oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new Uri(RedirectionUri));

                // It is recommended that you specify a non guessable 'state' request parameter to help prevent
                // cross site request forgery (CSRF).
                oAuthWebAuthCodeGrant.State = ClientState;

                // When calling Bing Ads services with ServiceClient or BulkServiceManager, each will refresh your access token
                // automatically if they detect the AuthenticationTokenExpired (109) error code.
                // As a best practice you should always use the most recent provided refresh token.
                // Save the refresh token whenever new OAuth tokens are received by subscribing to the NewOAuthTokensReceived event handler.

                oAuthWebAuthCodeGrant.NewOAuthTokensReceived +=
                    (sender, args) => SaveRefreshToken(args.NewRefreshToken);

                // If a refresh token is already present, use it to request new access and refresh tokens.

                if (RefreshTokenExists())
                {
                    // To force the authorization prompt, you can clear a previous refresh token.
                    DeleteRefreshToken();

                    await oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(GetRefreshToken());

                    // Save the authentication object in a session for future requests.
                    Session["auth"] = oAuthWebAuthCodeGrant;

                    return(await CallBingAdsServices((OAuthWebAuthCodeGrant)Session["auth"]));
                }

                // If the current HTTP request is a callback from the Microsoft Account authorization server,
                // use the current request url containing authorization code to request new access and refresh tokens
                if (Request["code"] != null)
                {
                    if (oAuthWebAuthCodeGrant.State != ClientState)
                    {
                        throw new HttpRequestException("The OAuth response state does not match the client request state.");
                    }

                    await oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(Request.Url);

                    // Save the authentication object in a session for future requests.
                    Session["auth"] = oAuthWebAuthCodeGrant;

                    return(await CallBingAdsServices((OAuthWebAuthCodeGrant)Session["auth"]));
                }

                // If there is no refresh token saved and no callback from the authorization server,
                // then connect to the authorization server and request user consent.
                return(Redirect(oAuthWebAuthCodeGrant.GetAuthorizationEndpoint().ToString()));
            }
            // OAuth classes can throw OAuthTokenRequestException
            catch (OAuthTokenRequestException ex)
            {
                ViewBag.Errors = string.Format("Couldn't get OAuth tokens. \nError: {0}. Description: {1}",
                                               ex.Details.Error, ex.Details.Description);

                return(View());
            }
            // Bulk service operations can throw AdApiFaultDetail.
            catch (FaultException <Microsoft.BingAds.V11.Bulk.AdApiFaultDetail> ex)
            {
                ViewBag.Errors  = string.Format("Error when calling the Bulk service: ");
                ViewBag.Errors += string.Join("; ",
                                              ex.Detail.Errors.Select(e => string.Format("{0}: {1}", e.Code, ex.Message)));

                return(View());
            }
            // Customer Management service operations can throw AdApiFaultDetail.
            catch (FaultException <Microsoft.BingAds.V11.CustomerManagement.AdApiFaultDetail> ex)
            {
                ViewBag.Errors  = string.Format("Error when calling the Customer Management service: ");
                ViewBag.Errors += string.Join("; ",
                                              ex.Detail.Errors.Select(e => string.Format("{0}: {1}", e.Code, ex.Message)));

                return(View());
            }
            catch (Exception ex)
            {
                ViewBag.Errors = ex.Message;

                return(View());
            }
        }
Ejemplo n.º 6
0
 private static Task <OAuthTokens> AuthorizeWithRefreshTokenAsync(OAuthWebAuthCodeGrant authentication, string refreshToken)
 {
     return(authentication.RequestAccessAndRefreshTokensAsync(refreshToken));
 }