private static Authentication GetOAuthDesktopMobileAuthCodeGrantUsingToken()
        {
            string accessToken = "", refreshToken = "";
            DateTime generationTime = DateTime.MinValue;
            int accessTokenExpiresInSeconds = 0;
            //Hardcode file name
            string iniFile = "MyCredential.ini";
            ParseOAuthFile(iniFile, out generationTime, out accessToken, out accessTokenExpiresInSeconds, out refreshToken);
            CommonHelper.OutputSuccessMessage("Read MyCredential.ini");
            CommonHelper.OutputMessage(string.Format("OAuthTokens.GenerationTime = {0}", CommonHelper.GetDateTimeInMillisecond(generationTime)));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.AccessToken = {0}", accessToken));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.AccessTokenExpiresInSeconds = {0}", accessTokenExpiresInSeconds));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.RefreshToken = {0}", refreshToken));

            var authentication = new OAuthDesktopMobileAuthCodeGrant(GlobalConfig.ClientId);
            if (NeedRequestAccessToken(generationTime, accessTokenExpiresInSeconds))
            {
                authentication.RequestAccessAndRefreshTokensAsync(refreshToken).Wait();
                WriteToFile(authentication.OAuthTokens);
            }
            else
            {
                //How to generate OAuthTokens
            }

            CommonHelper.OutputMessage(string.Format("OAuthTokens.AccessToken = {0}", authentication.OAuthTokens.AccessToken));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.AccessTokenExpiresInSeconds = {0}", authentication.OAuthTokens.AccessTokenExpiresInSeconds));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.RefreshToken = {0}", authentication.OAuthTokens.RefreshToken));

            return authentication;
        }
Пример #2
0
        /// <summary>
        /// Ensures that your application has authorization to manage a Bing Ads account. 
        /// If authorization has previously been granted, authentication is attempted with the refresh token.
        /// If a refresh token is not available, authorization is requested in a browser window. 
        /// </summary>
        /// <returns>Returns an instance of OAuthDesktopMobileAuthCodeGrant when the authorization 
        /// request task completes. </returns>
        public static async Task<OAuthDesktopMobileAuthCodeGrant> AuthorizeDesktopMobileAuthCodeGrant()
        {
            var oAuthDesktopMobileAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(Settings.Default["ClientId"].ToString());

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

            // 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. 
            oAuthDesktopMobileAuthCodeGrant.NewOAuthTokensReceived +=
                    (sender, tokens) => SaveRefreshToken(tokens.NewRefreshToken);

            string refreshToken;

            if (GetRefreshToken(out refreshToken))
            {
                await AuthorizeWithRefreshTokenAsync(oAuthDesktopMobileAuthCodeGrant, refreshToken);
            }
            else
            {
                await AuthorizeInBrowser(oAuthDesktopMobileAuthCodeGrant);
            }
                        
            return oAuthDesktopMobileAuthCodeGrant;
        }
Пример #3
0
        private static async Task AuthorizeInBrowser(OAuthDesktopMobileAuthCodeGrant auth)
        {
            var browserWindow = new BrowserWindow(auth.GetAuthorizationEndpoint(), auth.RedirectionUri.AbsolutePath);

            browserWindow.Show();

            var redirectUri = await browserWindow.GetRedirectUri();

            await auth.RequestAccessAndRefreshTokensAsync(redirectUri);
        }
        //authorization endpoint
        //https://login.live.com/oauth20_authorize.srf?client_id=000000004C181609&scope=bingads.manage&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf
        private static Authentication GetOAuthDesktopMobileAuthCodeGrantUsingCode()
        {
            var authentication = new OAuthDesktopMobileAuthCodeGrant(GlobalConfig.ClientId);

            Uri urlContainsCode = new Uri("https://login.live.com/oauth20_desktop.srf?code=M660f6d05-b20f-88b6-106f-deb7707b0072&lc=1033");
            CommonHelper.OutputMessage(string.Format("urlContainsCode = {0}", urlContainsCode));
            authentication.RequestAccessAndRefreshTokensAsync(urlContainsCode).Wait();
            WriteToFile(authentication.OAuthTokens);
            CommonHelper.OutputMessage(string.Format("OAuthTokens.AccessToken = {0}", authentication.OAuthTokens.AccessToken));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.AccessTokenExpiresInSeconds = {0}", authentication.OAuthTokens.AccessTokenExpiresInSeconds));
            CommonHelper.OutputMessage(string.Format("OAuthTokens.RefreshToken = {0}", authentication.OAuthTokens.RefreshToken));

            return authentication;
        }
Пример #5
0
        /// <summary>
        /// Ensures that your application has authorization to manage a Bing Ads account. 
        /// If authorization has previously been granted, authentication is attempted with the refresh token.
        /// If a refresh token is not available, authorization is requested in a browser window. 
        /// </summary>
        /// <returns>Returns an instance of OAuthDesktopMobileAuthCodeGrant when the authorization 
        /// request task completes. </returns>
        public static async Task<OAuthDesktopMobileAuthCodeGrant> AuthorizeDesktopMobileAuthCodeGrant()
        {
            var auth = new OAuthDesktopMobileAuthCodeGrant(Settings.Default["ClientId"].ToString());
            
            string refreshToken;

            if (GetRefreshToken(out refreshToken))
            {
                await AuthorizeWithRefreshTokenAsync(auth, refreshToken);
            }
            else
            {
                await AuthorizeInBrowser(auth);

                SaveRefreshToken(auth);
            }

            return auth;
        }
Пример #6
0
        private static async Task AuthorizeInBrowser(OAuthDesktopMobileAuthCodeGrant authentication)
        {
            var browserWindow = new BrowserWindow(authentication.GetAuthorizationEndpoint(), authentication.RedirectionUri.AbsolutePath);

            browserWindow.Show();

            var redirectUri = await browserWindow.GetRedirectUri();
            
            if (authentication.State != ClientState)
                throw new HttpRequestException("The OAuth response state does not match the client request state.");

            await authentication.RequestAccessAndRefreshTokensAsync(redirectUri);

        }
Пример #7
0
 private static Task<OAuthTokens> AuthorizeWithRefreshTokenAsync(OAuthDesktopMobileAuthCodeGrant auth, string refreshToken)
 {
     return auth.RequestAccessAndRefreshTokensAsync(refreshToken);
 }
Пример #8
0
        private static Authentication AuthenticateWithOAuth()
        {
            var oAuthDesktopMobileAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(Settings.Default["ClientId"].ToString());

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

            string refreshToken;

            // If you have previously securely stored a refresh token, try to use it.
            if (GetRefreshToken(out refreshToken))
            {
                AuthorizeWithRefreshTokenAsync(oAuthDesktopMobileAuthCodeGrant, 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", oAuthDesktopMobileAuthCodeGrant.GetAuthorizationEndpoint()));

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

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

                oAuthDesktopMobileAuthCodeGrant.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. 
            oAuthDesktopMobileAuthCodeGrant.NewOAuthTokensReceived +=
                    (sender, tokens) => SaveRefreshToken(tokens.NewRefreshToken);

            return oAuthDesktopMobileAuthCodeGrant;
        }
Пример #9
0
 private static void SaveRefreshToken(OAuthDesktopMobileAuthCodeGrant auth)
 {
     Settings.Default["RefreshToken"] = auth.OAuthTokens.RefreshToken.Protect();
     Settings.Default.Save();
 }