Esempio n. 1
0
        /// <summary>
        /// Generates a login token for authenticating DFA API calls.
        /// </summary>
        /// <param name="user">The user for which token is generated.</param>
        /// <param name="serviceVersion">The service version.</param>
        /// <returns>A token which may be used for future API calls.</returns>
        private static UserToken GenerateAuthenticationToken(AdsUser user, string serviceVersion)
        {
            DfaAppConfig config = (DfaAppConfig)user.Config;

            if (!String.IsNullOrEmpty(config.DfaAuthToken))
            {
                return(new UserToken(config.DfaUserName, config.DfaAuthToken));
            }
            if (config.AuthorizationMethod == DfaAuthorizationMethod.LoginService)
            {
                if (string.IsNullOrEmpty(config.DfaUserName))
                {
                    throw new ArgumentNullException(DfaErrorMessages.UserNameCannotBeEmpty);
                }
                if (string.IsNullOrEmpty(config.DfaPassword))
                {
                    throw new ArgumentNullException(DfaErrorMessages.PasswordCannotBeEmpty);
                }
            }
            try {
                DfaServiceSignature loginServiceSignature = new DfaServiceSignature(serviceVersion,
                                                                                    "LoginRemoteService");
                AdsClient loginService = user.GetService(loginServiceSignature, config.DfaApiServer);
                object    userProfile  = loginService.GetType().GetMethod("authenticate").Invoke(
                    loginService, new object[] { config.DfaUserName, config.DfaPassword });
                return(new UserToken(
                           userProfile.GetType().GetProperty("name").GetValue(userProfile, null).ToString(),
                           userProfile.GetType().GetProperty("token").GetValue(userProfile, null).ToString()));
            } catch (Exception ex) {
                throw new DfaException("Failed to authenticate user. See inner exception for details.", ex);
            }
        }
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create an DfaAppConfig object with the default settings in
            // App.config.
            DfaAppConfig config = new DfaAppConfig();

            if (config.AuthorizationMethod == DfaAuthorizationMethod.OAuth2)
            {
                if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    DoAuth2Configuration(config);
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Configures the DFA user for OAuth.
        /// </summary>
        private void ConfigureUserForOAuth()
        {
            DfaAppConfig config = (user.Config as DfaAppConfig);

            if (config.AuthorizationMethod == DfaAuthorizationMethod.OAuth2)
            {
                if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    user.OAuthProvider = (OAuth2ProviderForApplications)Session["OAuthProvider"];
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }
        }
        /// <summary>
        /// The main method.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        static void Main(string[] args)
        {
            DfaUser      user   = new DfaUser();
            DfaAppConfig config = (user.Config as DfaAppConfig);

            if (config.AuthorizationMethod == DfaAuthorizationMethod.OAuth2)
            {
                if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    DoAuth2Authorization(user);
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }

            // Set the username. This is required for the LoginService to work
            // correctly when authenticating using OAuth2.
            Console.Write("Enter the user name: ");
            string userName = Console.ReadLine();

            (user.Config as DfaAppConfig).DfaUserName = userName;

            // Create AdRemoteService instance.
            AdRemoteService service = (AdRemoteService)user.GetService(
                DfaService.v1_20.AdRemoteService);

            try {
                // Get ad types.
                AdType[] adTypes = service.getAdTypes();

                // Display ad type and its id.
                foreach (AdType result in adTypes)
                {
                    Console.WriteLine("Ad type with name \"{0}\" and id \"{1}\" was found.", result.name,
                                      result.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to retrieve ad types. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Handles the Click event of the btnAuthorize control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnAuthorizeButtonClick(object sender, EventArgs e)
        {
            // This code example shows how to run an DFA API web application
            // while incorporating the OAuth2 web application flow into your
            // application. If your application uses a single Google login to make calls
            // to all your accounts, you shouldn't use this code example. Instead, you
            // should run Common\Util\OAuth2TokenGenerator.cs to generate a refresh
            // token and set that in user.Config.OAuth2RefreshToken field, or set
            // OAuth2RefreshToken key in your App.config / Web.config.
            DfaAppConfig config = user.Config as DfaAppConfig;

            if (config.AuthorizationMethod == DfaAuthorizationMethod.OAuth2)
            {
                if (user.Config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    Response.Redirect("OAuthLogin.aspx");
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Gets a login token for authenticating DFA API calls.
        /// </summary>
        /// <param name="user">The user for which token is generated.</param>
        /// <param name="serviceVersion">The service version.</param>
        /// <returns>A token which may be used for future API calls.</returns>
        public static UserToken GetAuthenticationToken(AdsUser user, string serviceVersion)
        {
            DfaAppConfig config = (DfaAppConfig)user.Config;

            if (string.IsNullOrEmpty(config.DfaUserName))
            {
                throw new ArgumentNullException(DfaErrorMessages.UserNameCannotBeEmpty);
            }

            UserToken userToken = tokenCache.GetToken(config.DfaUserName);

            if (userToken == null)
            {
                lock (typeof(LoginUtil)) {
                    userToken = tokenCache.GetToken(config.DfaUserName);
                    if (userToken == null)
                    {
                        userToken = GenerateAuthenticationToken(user, serviceVersion);
                        tokenCache.AddToken(config.DfaUserName, userToken);
                    }
                }
            }
            return(userToken);
        }
        private void DoAuth2Configuration(DfaAppConfig config)
        {
            // Since we use this page for OAuth callback also, we set the callback
            // url as the current page. For a non-web application, this will be null.
            config.OAuth2RedirectUri = Request.Url.GetLeftPart(UriPartial.Path);

            // Create an OAuth2 object for handling OAuth2 flow.
            OAuth2ProviderForApplications oAuth = new OAuth2ProviderForApplications(config);

            if (Request.Params["state"] == null)
            {
                // This is the first time this page is being loaded.
                // Set the state variable to any value that helps you recognize
                // when this url will be called by the OAuth2 server.
                oAuth.State = "callback";

                // Create an authorization url and redirect the user to that page.
                Response.Redirect(oAuth.GetAuthorizationUrl());
            }
            else if (Request.Params["state"] == "callback")
            {
                // This page was loaded because OAuth server did a callback.
                // Retrieve the authorization code from the url and use it to fetch
                // the access token. This call will also fetch the refresh token if
                // your mode is offline.
                oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);

                // Save the OAuth2 provider for future use. If you wish to save only
                // the values and restore the object later, then save
                // oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
                // oAuth.ExpiresIn.
                //
                // You can later restore the values as
                // DfaUser user = new AdWordsUser();
                // user.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
                // OAuth2ProviderForApplications oAuth =
                //     (user.OAuthProvider as OAuth2ProviderForApplications);
                // oAuth.RefreshToken = xxx;
                // oAuth.AccessToken = xxx;
                // oAuth.UpdatedOn = xxx;
                // oAuth.ExpiresIn = xxx;
                //
                // Note that only oAuth.RefreshToken is mandatory. If you leave
                // oAuth.AccessToken as empty, or if oAuth.UpdatedOn + oAuth.ExpiresIn
                // is in the past, the access token will be refreshed by the library.
                // You can listen to this event as
                //
                // oAuth.OnOAuthTokensObtained += delegate(AdsOAuthProvider provider) {
                //    OAuth2ProviderForApplications oAuth =
                //        (provider as OAuth2ProviderForApplications);
                //    // Save oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
                //    // oAuth.ExpiresIn.
                //};
                Session["OAuthProvider"] = oAuth;
                // Redirect the user to the main page.
                Response.Redirect("Default.aspx");
            }
            else
            {
                throw new Exception("Unknown state for OAuth callback.");
            }
        }