Example #1
0
        protected override async Task <AccountModelBase> AddAccountAsync(AccountModelBase account = null)
        {
            var credentials = await GetCredential();

            if (credentials == null)
            {
                return(null);
            }

            Userinfoplus userInfo;

            using (var authService = new Oauth2Service(GetServiceInitializer(credentials)))
            {
                userInfo = await authService.Userinfo.Get().ExecuteAsync();
            }

            var config = GetConfiguration <ConfigModel>();

            var provider = new AccountModel(userInfo.Id, userInfo.Name)
            {
                Email = userInfo.Email
            };

            config.Accounts.Add(provider);
            SetConfiguration(config);

            return(provider);
        }
Example #2
0
        private async Task Run()
        {
            /*
            string CREDENTIAL_FILE_PKCS12 = "c:\\your_pkcs_cert.p12";
            string serviceAccountEmail = "*****@*****.**";
            var certificate = new X509Certificate2(CREDENTIAL_FILE_PKCS12, "notasecret", X509KeyStorageFlags.Exportable);
            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   Scopes = new[] { Oauth2Service.Scope.UserinfoEmail }
               }.FromCertificate(certificate));
            */

            string CREDENTIAL_FILE_JSON = "C:\\your_json_cert.json";
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", CREDENTIAL_FILE_JSON);
            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
            if (credential.IsCreateScopedRequired)
                credential = credential.CreateScoped(new string[] { Oauth2Service.Scope.UserinfoEmail });
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Oauth2 Sample",
            });
            Console.WriteLine(service.Userinfo.Get().Execute().Email);
        }
Example #3
0
        public async Task <bool> Login()
        {
            var clientSecretUri = new Uri("ms-appx:///Resources/client_secret.json", UriKind.Absolute);

            try
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecretUri, Scopes, "user", CancellationToken.None);

                await credential.RefreshTokenAsync(CancellationToken.None);
            }
            catch (TokenResponseException e)
            {
                await credential.GetAccessTokenForRequestAsync();
            }
            catch (Exception e)
            {
                return(false);
            }

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName
            };

            accessToken = credential.Token.AccessToken;

            Oauth2Service = new Oauth2Service(initializer);
            DriveService  = new DriveService(initializer);

            return(true);
        }
        //
        // GET: /oauth2callback

        public ActionResult OAuth2Callback(String code)
        {
            var provider = GetProvider();

            try
            {
                var state       = provider.ProcessUserAuthorization(code, GetAuthorizationState());
                var initializer = new BaseClientService.Initializer()
                {
                    Authenticator = Utils.GetAuthenticatorFromState(state)
                };

                Oauth2Service userService = new Oauth2Service(initializer);
                String        userId      = userService.Userinfo.Get().Fetch().Id;

                Utils.StoreCredentials(userId, state);
                Session["userId"] = userId;

                BootstrapUser(new MirrorService(initializer), userId);
            }
            catch (ProtocolException)
            {
                // TODO(alainv): handle error.
            }
            return(Redirect(Url.Action("Index", "Main")));
        }
Example #5
0
        private static UserCredential Authenticate()
        {
            Console.WriteLine("Requesting Authentication");
            string[]       scopes     = new string[] { Oauth2Service.Scope.UserinfoEmail };
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId     = @"99450014535-bel11jg1ft872p8qvt84nk3qoij5bh5q.apps.googleusercontent.com",
                ClientSecret = @"aTaj6A8kq38r5FkKogPAZb5q"
            }, scopes, "user", CancellationToken.None).Result;

            Oauth2Service oauth2Service = new Oauth2Service(
                new BaseClientService.Initializer {
                HttpClientInitializer = credential
            });
            Userinfoplus userinfo = oauth2Service.Userinfo.Get().ExecuteAsync().Result;

            if (!userinfo.Email.EndsWith(@"@pilani.bits-pilani.ac.in"))
            {
                credential.RevokeTokenAsync(CancellationToken.None).Wait();
                Console.WriteLine("\nInvalid BITS ID : {0}\n\n", userinfo.Email);
                return(Authenticate());
            }

            return(credential);
        }
        //
        // GET: /oauth2callback
        public ActionResult OAuth2Callback(String code)
        {
            var provider = GetProvider();
            try
            {
                var state = provider.ProcessUserAuthorization(code, GetAuthorizationState());
                var initializer = new BaseClientService.Initializer()
                {
                    Authenticator = Utils.GetAuthenticatorFromState(state)
                };

                Oauth2Service userService = new Oauth2Service(initializer);
                String userId = userService.Userinfo.Get().Fetch().Id;

                Utils.StoreCredentials(userId, state);
                Session["userId"] = userId;

                BootstrapUser(new MirrorService(initializer), userId);
            }
            catch (ProtocolException)
            {
                // TODO(alainv): handle error.
            }
            return Redirect(Url.Action("Index", "Main"));
        }
Example #7
0
        public async Task <ActionResult> LoginByGoogle(CancellationToken cancellationToken, string returnUrl)
        {
            if (Session["UserRandomId"] == null)
            {
                Session["UserRandomId"] = new TextBuilder().GetRandomString(50);
            }

            var result = await new AuthorizationCodeMvcApp(this,
                                                           new AppFlowMetadata(
                                                               repoConfig.Get(ConfigurationKeyStatic.GOOGLE_APP_ID),
                                                               repoConfig.Get(ConfigurationKeyStatic.GOOGLE_APP_SECRET))).AuthorizeAsync(cancellationToken);

            var service = new Oauth2Service(new BaseClientService.Initializer
            {
                HttpClientInitializer = result.Credential,
                ApplicationName       = "ASP.NET MVC Sample"
            });

            if (result.Credential != null)
            {
                var userInfo = await service.Userinfo.Get().ExecuteAsync();

                if (!account.RegisterAndLogByEmail(userInfo.Email, SOURCE_GOOGLE, this))
                {
                    this.SetMessage(InfoMessageType.Danger, Resources.ErrorOcurred);
                }
                Session["UserRandomId"] = null;
                return(Redirect(returnUrl ?? Url.Action("Index", "Home")));
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }
        public async void UpdateLoginDetails()
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId     = "957928808020-pa0lopl3crh565k6jd4djaj36rm1d9i5.apps.googleusercontent.com",
                ClientSecret = "oB9U6yWFndnBqLKIRSA0nYGm"
            }, new[] { Oauth2Service.Scope.UserinfoProfile }, "user", CancellationToken.None);

            // Create the service.
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Youtube Viewer",
            });

            var GetLoginInfo = service.Userinfo.Get();

            try
            {
                var LoginInfo = await GetLoginInfo.ExecuteAsync();

                txtLoginName.Text = LoginInfo.Name;

                var profileImg = new Windows.UI.Xaml.Media.ImageBrush
                {
                    ImageSource = new BitmapImage(new Uri(LoginInfo.Picture))
                };
                imgProfileIcon.Fill = profileImg;
            }
            catch (Exception)
            {
                txtLoginName.Text   = "";
                imgProfileIcon.Fill = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Color.FromArgb(0, 0, 0, 0));
            }
        }
        /// <summary>
        /// Send a request to the UserInfo API to retrieve the user's information.
        /// </summary>
        /// <param name="credentials">OAuth 2.0 credentials to authorize the request.</param>
        /// <returns>User's information.</returns>
        /// <exception cref="NoUserIdException">An error occurred.</exception>
        static Userinfo GetUserInfo(IAuthorizationState credentials)
        {
            // create base client service initializer
            BaseClientService.Initializer baseClientService = new BaseClientService.Initializer()
            {
                Authenticator = GetAuthenticatorFromState(credentials)
            };

            Oauth2Service userInfoService = new Oauth2Service(baseClientService);
            Userinfo      userInfo        = null;

            try
            {
                userInfo = userInfoService.Userinfo.Get().Fetch();
            }
            catch (GoogleApiRequestException e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }
            if (userInfo != null && !String.IsNullOrEmpty(userInfo.Id))
            {
                return(userInfo);
            }
            else
            {
                throw new NoUserIdException();
            }
        }
Example #10
0
        public static async Task <UserInfo> SignInAsync(ClientInfo clientInfo)
        {
            var clientSecrets = new ClientSecrets
            {
                ClientId     = clientInfo.ClientId,
                ClientSecret = clientInfo.ClientSecret
            };

            var credentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                clientSecrets,
                new[] { DriveService.Scope.Drive, Oauth2Service.Scope.UserinfoEmail },
                Guid.NewGuid().ToString(), CancellationToken.None, new FileDataStore(clientInfo.AppName));

            var oauthService = new Oauth2Service(new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                ApplicationName       = clientInfo.AppName
            });

            var userInfo = await oauthService.Userinfo.Get().ExecuteAsync();

            return(new UserInfo
            {
                Email = userInfo.Email,
                Name = userInfo.Name,
                UserId = credentials.UserId
            });
        }
Example #11
0
        /// <summary>
        /// Verifies the token against the client ID.
        /// </summary>
        /// <param name="authState">The credential to verify.</param>
        /// <returns>The user ID that is associated with this token.</returns>
        static public String VerifyToken(IAuthorizationState authState)
        {
            // Use Tokeninfo to validate the user and the client.
            var tokeninfo_request = new Oauth2Service().Tokeninfo();

            tokeninfo_request.Access_token = authState.AccessToken;
            var tokeninfo = tokeninfo_request.Fetch();

            if (tokeninfo == null)
            {
                throw new TokenVerificationException("Error while fetching tokeninfo");
            }

            // Verify the first part of the token for authorization. On mobile clients,
            // the full string might differ, but the first part is consistent.
            Regex matcher = new Regex("(\\d+)(.*).apps.googleusercontent.com$");

            if (matcher.Match(tokeninfo.Issued_to).Groups[1].Value !=
                matcher.Match(CLIENT_ID).Groups[1].Value)
            {
                throw new TokenVerificationException("Issuer other than current client.");
            }

            return(tokeninfo.User_id);
        }
Example #12
0
        public string GetAccountNameFromToken(IAuthorizationState token)
        {
            var client        = GetNativeApplicationClient();
            var oauth2Service = new Oauth2Service(new OAuth2Authenticator <NativeApplicationClient>(client, authProvider => token));

            return(oauth2Service.Userinfo.Get().Fetch().Email);
        }
        public async Task <IActionResult> GoogleAuthentication(string code)
        {
            var request = new AuthorizationCodeTokenRequest
            {
                Code         = code,
                ClientSecret = _googleAuthOptions.ClientSecret,
                ClientId     = _googleAuthOptions.ClientId,
                GrantType    = "authorization_code",
                RedirectUri  = "http://localhost:3000"
            };
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://www.googleapis.com/oauth2/v4/")
            };
            var tokenResponse = await request.ExecuteAsync(httpClient, "token", CancellationToken.None, SystemClock.Default);

            var credentials = GoogleCredential.FromAccessToken(tokenResponse.AccessToken);
            var initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials
            };
            var userInfoService = new Oauth2Service(initializer);
            var userInfo        = await userInfoService.Userinfo.Get().ExecuteAsync();

            await _usersService.CreateUserAsync(new UserCreationDto
            {
                Email    = userInfo.Email,
                Password = "******",  //TODO: Add password generator
                IsFromExternalService = true,
                Name = userInfo.Email
            });

            return(Ok());
        }
Example #14
0
        public async void login()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile, Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail },
                    "user", CancellationToken.None);
            }

            // Create the service.
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Organize-Me",
            });
            var userInfo = await service.Userinfo.Get().ExecuteAsync();

            f.txt_SignUpEmail.Text = userInfo.Email;
            f.FirstName            = userInfo.GivenName;
            f.LastName             = userInfo.FamilyName;
            await credential.RevokeTokenAsync(CancellationToken.None);

            f.bunifuPages1.SetPage(1);
        }
Example #15
0
        private async Task Run()
        {
            UserCredential credential;
            string         CLIENTSECRETS_LOCATION = "c:\\client_secrets.json";

            using (var stream = new FileStream(CLIENTSECRETS_LOCATION, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { Oauth2Service.Scope.UserinfoEmail }, Environment.UserName, CancellationToken.None);
            }

            /*
             * string clientId = "YOUR_CLIENT_ID";
             * string clientSecret = "YOUR_CLIENT_SECRET";
             * credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret },
             *  new[] { Oauth2Service.Scope.UserinfoEmail }, Environment.UserName, CancellationToken.None);
             * Console.WriteLine("Credential file saved at: " + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
             */
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Oauth2 Sample",
            });

            Console.WriteLine(service.Userinfo.Get().Execute().Email);
        }
Example #16
0
 public Service(BotUserCredential userCredential, BaseClientService.Initializer initializer, string userAccess)
 {
     UserCredential = userCredential;
     GmailService   = new GmailService(initializer);
     Oauth2Service  = new Oauth2Service(initializer);
     UserAccess     = userAccess;
 }
Example #17
0
        public string OAuth2(string code)
        {
            //generate new developer key to use within Gmail Chrome Extension
            var developerKey = Utility.Strings.Generate.NewId(10);

            //generate new userId for Google Credentials
            var credentialUserId = Utility.Strings.Generate.NewId(10);

            try
            {
                //authenticate Google OAuth 2.0 via server-side
                var oauthService = new Oauth2Service(new BaseClientInitializer(credentialUserId, code));

                var googleUser = oauthService.Userinfo.Get().Execute();

                //check if user is in the database
                var user   = Query.Users.GetByEmail(googleUser.Email);
                var userId = 0;
                if (user != null)
                {
                    //user exists
                    userId = user.userId;
                    if (user.googleUserId == "")
                    {
                        Query.Users.UpdateGoogleUserId(userId, googleUser.Id);
                    }

                    //update Google Credentials userId
                    Query.Users.UpdateCredentialUserId(userId, credentialUserId);
                }
                else
                {
                    //create new user
                    userId = Query.Users.CreateUser(new Query.Models.User()
                    {
                        email            = googleUser.Email,
                        name             = googleUser.Name != null && googleUser.Name != "" ? googleUser.Name : googleUser.Email.Split('@')[0],
                        gender           = googleUser.Gender == "male",
                        locale           = googleUser.Locale,
                        credentialUserId = credentialUserId,
                        googleUserId     = googleUser.Id
                    });
                }

                //update developer key
                Query.DeveloperKeys.Update(userId, developerKey);

                //log API request
                Common.Log.Api(context, Query.Models.LogApi.Names.GoogleOAuth2, userId);

                return(Serializer.WriteObjectToString(new { devkey = developerKey, userId }));
            }
            catch (Exception)
            {
                //log API call
                Common.Log.Api(context, Query.Models.LogApi.Names.GoogleOAuth2, 0, null, null, false);
                return(Error("incorrect Google Sign-In code"));
            }
        }
Example #18
0
        /// <summary>
        /// Token request object initilization to retreive user information
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public object GetTokenInfo(string accessToken)
        {
            Oauth2Service.TokeninfoRequest  tokeninfoRequest = new Oauth2Service().Tokeninfo();
            Google.Apis.Discovery.Parameter accessType       = new Google.Apis.Discovery.Parameter {
                DefaultValue = GoogleReqestParameters.offline.ToString(), Name = GoogleReqestParameters.access_type.ToString()
            };
            tokeninfoRequest.RequestParameters.Add("AccessType", accessType);
            tokeninfoRequest.AccessToken = accessToken;
            Tokeninfo tokeninfo = tokeninfoRequest.Execute();

            return(tokeninfo);
        }
Example #19
0
        public Oauth2Service GetOauth2Service()
        {
            var service = new Oauth2Service(
                new BaseClientService.Initializer()
            {
                HttpClientInitializer = _authorizationCodeApp.Credential,
                ApplicationName       = _applicationName
            }
                );

            return(service);
        }
Example #20
0
 public static void Main(string[] args)
 {
     var accessToken =
         "ya29.GlvTBZnj-NGxW28OIE4jOjEsIQJh2XgxSsuDioj3VapUYeiT_D7TT6zwePEbOhLQ_dO0QlkRh5l_WX7fWm7oTnS75RWEk5OGN45tvheYwWyt0v0jexUSTO0bbETF";
     var credentials = GoogleCredential.FromAccessToken(
         accessToken);
     var service = new Oauth2Service(new BaseClientService.Initializer
     {
         HttpClientInitializer = credentials
     });
     var user = service.Userinfo.V2.Me.Get().Execute();
 }
Example #21
0
 private async Task Run()
 {
     //ComputeCredential credentials = new ComputeCredential(new ComputeCredential.Initializer());
     GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
     if (credential.IsCreateScopedRequired)
         credential = credential.CreateScoped(new string[] { Oauth2Service.Scope.UserinfoEmail });
     var service = new Oauth2Service(new BaseClientService.Initializer()
     {
         HttpClientInitializer = credential,
         ApplicationName = "Oauth2 Sample",
     });
     Console.WriteLine(service.Userinfo.Get().Execute().Email);
 }
Example #22
0
        private Oauth2Service CreateUserInfoService(string userEmail)
        {
            var auth = GetAuthenticator(userEmail);

            // Create the service.
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                Authenticator = auth
            });

            //cache it in session
            return(service);
        }
Example #23
0
 /// <summary>
 /// Pulls the authenticated user's information from Google and uses that to update OAuth2Base.currentAuthInfo.
 /// </summary>
 /// <remarks>Requires that Authentication has taken place and filled out asyncUserCredential first.</remarks>
 public static void SetAuthenticatedUserInfo()
 {
     using (Oauth2Service oService = new Oauth2Service(new BaseClientService.Initializer()
     {
         HttpClientInitializer = asyncUserCredential,
         ApplicationName = _appName,
     }))
     {
         Userinfoplus userInfoPlus = oService.Userinfo.Get().Execute();
         _currentAuthInfo.userName = Utils.GetUserFromEmail(userInfoPlus.Email);
         _currentAuthInfo.domain   = userInfoPlus.Hd;
     }
 }
Example #24
0
        public Tokeninfo GetTokenDetails(TokenResponse token)
        {
            var oauthService = new Oauth2Service(new Google.Apis.Services.BaseClientService.Initializer());

            var tokenInfoRequest = oauthService.Tokeninfo();

            tokenInfoRequest.AccessToken = token.AccessToken;

            var tokenInfo = tokenInfoRequest.Execute();

            Console.WriteLine("Email: {0}", tokenInfo.Email);
            Console.WriteLine("Refresh Token: {0}", tokenInfo.UserId);

            return(tokenInfo);
        }
Example #25
0
        /// <summary>
        /// Send a request to the UserInfo API to retrieve the user's information.
        /// </summary>
        /// <param name="credentials">OAuth 2.0 credentials to authorize the request.</param>
        /// <returns>User's information.</returns>
        /// <exception cref="NoUserIdException">An error occurred.</exception>
        public static Userinfo GetUserInfo(IAuthenticator credentials) 
        {
            Oauth2Service userInfoService = new Oauth2Service(credentials);
            Userinfo userInfo = null;
            try {
                userInfo = userInfoService.Userinfo.Get().Fetch();
            } catch (GoogleApiRequestException e) {
                Console.WriteLine("An error occurred: " + e.Message);
            }

            if (userInfo != null && !String.IsNullOrEmpty(userInfo.Id)) {
                return userInfo;
            } else {
                throw new NoUserIdException();
            }
        }
Example #26
0
        public async static Task Run()
        {
            string CRED_PATH = new Factory.FileFactory().GetFolder() + @"\api_key\My First Project-ca909aeb1219.json";


            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", CRED_PATH);

            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();

            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Oauth2 Sample",
            }
                                            );
        }
Example #27
0
        public ActionResult SignInWithGoogle(string code)
        {
            // Use the code exchange flow to get an access and refresh token.
            IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = GetClientConfiguration().Secrets,
                Scopes        = new[] { Oauth2Service.Scope.PlusLogin, Oauth2Service.Scope.UserinfoProfile, Oauth2Service.Scope.UserinfoEmail }
            });

            var response = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // response.accessToken now should be populated

            var credential = new UserCredential(flow, "me", response);

            var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Grid Intranet"
            });

            var userInfo = oauthSerivce.Userinfo.Get().Execute();

            var user = _userRepository.GetBy(u => u.Username == userInfo.Email, "AccessRule,Person");

            if (user == null)
            {
                return(Json(false));
            }

            if (user.AccessRule == null)
            {
                return(Json(false));
            }

            if (!user.AccessRule.IsApproved)
            {
                return(Json(false));
            }

            // Everything is fine.
            RecordLoginSucceeded(user);

            return(Json(true));
        }
Example #28
0
        /// <summary>
        /// Is token expired or not
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public bool IsTokenExpired(string accessToken)
        {
            Tokeninfo tokeninfo = null;

            Oauth2Service.TokeninfoRequest  tokeninfoRequest = new Oauth2Service().Tokeninfo();
            Google.Apis.Discovery.Parameter accessType       = new Google.Apis.Discovery.Parameter {
                DefaultValue = GoogleReqestParameters.offline.ToString(), Name = GoogleReqestParameters.access_type.ToString()
            };
            tokeninfoRequest.RequestParameters.Add("AccessType", accessType);
            tokeninfoRequest.AccessToken = accessToken;
            try
            {
                tokeninfo = tokeninfoRequest.Execute();
            }
            catch (Exception)
            {
                // ignored
            }
            return(tokeninfo == null);
        }
        private async Task AuthenticateAsync()
        {
            if (_service != null)
                return;

            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { Oauth2Service.Scope.UserinfoEmail },
                "user",
                CancellationToken.None);

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName = "GoogleLogin",
            };

            _service = new Oauth2Service(initializer);

        }
Example #30
0
        private async Task Run()
        {
            /*
             * string CREDENTIAL_FILE_PKCS12 = "c:\\your_pkcs_cert.p12";
             * string serviceAccountEmail = "*****@*****.**";
             * var certificate = new X509Certificate2(CREDENTIAL_FILE_PKCS12, "notasecret", X509KeyStorageFlags.Exportable);
             * ServiceAccountCredential credential = new ServiceAccountCredential(
             * new ServiceAccountCredential.Initializer(serviceAccountEmail)
             * {
             *     Scopes = new[] { Oauth2Service.Scope.UserinfoEmail }
             * }.FromCertificate(certificate));
             */

            // a) for google apis:

            //string CREDENTIAL_FILE_JSON = "C:\\your_json_cert.json";
            //Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", CREDENTIAL_FILE_JSON);

            //GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new string[] { Oauth2Service.Scope.UserinfoEmail });
            }
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Oauth2 Sample",
            });

            Console.WriteLine(service.Userinfo.Get().Execute().Email);

            // b) For Google Cloud APIs:

            var client = StorageClient.Create();

            foreach (var obj in client.ListObjects("your_project", ""))
            {
                Console.WriteLine(obj.Name);
            }
        }
        public async Task <ActionResult> ConnectCallBack(AuthorizationCodeResponseUrl authorizationCode,
                                                         CancellationToken taskCancellationToken)
        {
            try
            {
                var userId    = CurrentUser.StringId;
                var returnUrl = Request.Url.ToString();
                returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?"));
                var token =
                    await
                    AppFlow.Flow.ExchangeCodeForTokenAsync(userId, authorizationCode.Code, returnUrl,
                                                           taskCancellationToken);

                var api = new Oauth2Service(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = new UserCredential(AppFlow.Flow, userId, token)
                });
                var userInfo = api.Userinfo.Get().Execute();
                CurrentUser.GoogleDriveAccount = new GoogleDriveAccount
                {
                    ConnectingDate   = DateTime.UtcNow,
                    Enabled          = true,
                    AccessToken      = token.AccessToken,
                    RefreshToken     = token.RefreshToken,
                    Issued           = token.Issued,
                    Scope            = token.Scope,
                    TokenType        = token.TokenType,
                    ExpiresInSeconds = token.ExpiresInSeconds,
                    AccountName      = userInfo.Name
                };
                UnitOfWork.Commit();
            }
            catch
            {
                ModelState.AddModelError("", "Can't connect to Google Drive.");
            }
            return(RedirectToAction <UserController>(c => c.Index()));
        }
Example #32
0
        private async Task <ActionResult> UpdateDatabase(CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                         AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var serviceInitializer = new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = "AssistMe"
                };

                userConfig.GoogleAccessToken = result.Credential.Token.AccessToken;
                Session["UserConfig"]        = userConfig;

                var service      = new DriveService(serviceInitializer);
                var oauthService = new Oauth2Service(serviceInitializer);
                HttpContext.Session["DriveService"]  = service;
                HttpContext.Session["Oauth2Service"] = oauthService;

                var gDriveHelper = new GDriveHelper();
                gDriveHelper.InitBaseSystem();

                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Base init completed for user: {0}", userConfig.User_Id);
                }

                //var data = await result.Credential.RefreshTokenAsync(cancellationToken);
                //ViewBag.Message =  // "FILE COUNT IS: " + list.Items.Count();
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }
Example #33
0
        private void getUserInfo()
        {
            bool result = true;

            if (credential == null)
            {
                result = GoogleConnect();
            }

            if (result == false || credential == null)
            {
                return;
            }

            Oauth2Service service = new Oauth2Service(
                new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = AppDomain.CurrentDomain.FriendlyName,
            });

            userInfo = service.Userinfo.Get().Execute();
        }
Example #34
0
        public async Task<ActionResult> Login(CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var service = new Oauth2Service(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName = this.ApplicationName
                });

                var response = await service.Userinfo.Get().ExecuteAsync();

                this.Session["UserInfo"] = response;

                return RedirectToAction("Index", "Home");
            }
            else
            {
                return new RedirectResult(result.RedirectUri);
            }
        }
Example #35
0
        /// <summary>
        /// Verifies the token against the client ID.
        /// </summary>
        /// <param name="authState">The credential to verify.</param>
        /// <returns>The user ID that is associated with this token.</returns>
        public static String VerifyToken(IAuthorizationState authState)
        {
            // Use Tokeninfo to validate the user and the client.
            var tokeninfo_request = new Oauth2Service().Tokeninfo();
            tokeninfo_request.Access_token = authState.AccessToken;
            var tokeninfo = tokeninfo_request.Fetch();

            if (tokeninfo == null)
            {
                throw new TokenVerificationException("Error while fetching tokeninfo");
            }

            // Verify the first part of the token for authorization. On mobile clients,
            // the full string might differ, but the first part is consistent.
            Regex matcher = new Regex("(\\d+)(.*).apps.googleusercontent.com$");
            if (matcher.Match(tokeninfo.Issued_to).Groups[1].Value !=
                matcher.Match(CLIENT_ID).Groups[1].Value)
            {
                throw new TokenVerificationException("Issuer other than current client.");
            }

            return tokeninfo.User_id;
        }
Example #36
0
 private async Task Run()
 {
     UserCredential credential;
     string CLIENTSECRETS_LOCATION = "c:\\client_secrets.json";
     using (var stream = new FileStream(CLIENTSECRETS_LOCATION, FileMode.Open, FileAccess.Read))
     {
         credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
             GoogleClientSecrets.Load(stream).Secrets,
             new[] { Oauth2Service.Scope.UserinfoEmail }, Environment.UserName, CancellationToken.None);
     }
     /*
     string clientId = "YOUR_CLIENT_ID";
     string clientSecret = "YOUR_CLIENT_SECRET";
     credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret },
         new[] { Oauth2Service.Scope.UserinfoEmail }, Environment.UserName, CancellationToken.None);
     Console.WriteLine("Credential file saved at: " + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
     */
     var service = new Oauth2Service(new BaseClientService.Initializer()
     {
         HttpClientInitializer = credential,
         ApplicationName = "Oauth2 Sample",
     });
     Console.WriteLine(service.Userinfo.Get().Execute().Email);
 }
Example #37
0
        private async Task Run()
        {
            //ComputeCredential credentials = new ComputeCredential(new ComputeCredential.Initializer());
            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new string[] { Oauth2Service.Scope.UserinfoEmail });
            }
            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Oauth2 Sample",
            });

            Console.WriteLine(service.Userinfo.Get().Execute().Email);

            var client = StorageClient.Create();

            foreach (var obj in client.ListObjects("your_project", ""))
            {
                Console.WriteLine(obj.Name);
            }
        }
Example #38
0
 /// <summary>
 /// Send a request to the UserInfo API to retrieve the user's information.
 /// </summary>
 /// <param name="credentials">OAuth 2.0 credentials to authorize the request.</param>
 /// <returns>User's information.</returns>
 /// <exception cref="NoUserIdException">An error occurred.</exception>
 static Userinfo GetUserInfo(IAuthorizationState credentials)
 {
     Oauth2Service userInfoService = new Oauth2Service(GetAuthenticatorFromState(credentials));
     Userinfo userInfo = null;
     try
     {
         userInfo = userInfoService.Userinfo.Get().Fetch();
     }
     catch (GoogleApiRequestException e)
     {
         Console.WriteLine("An error occurred: " + e.Message);
     }
     if (userInfo != null && !String.IsNullOrEmpty(userInfo.Id))
     {
         return userInfo;
     }
     else
     {
         throw new NoUserIdException();
     }
 }
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Get the code from the request POST body.
            string accessToken = context.Request.Params["access_token"];
            string idToken = context.Request.Params["id_token"];

            // Validate the ID token
            if (idToken != null)
            {
                JWTSecurityToken token = new JWTSecurityToken(idToken);
                JWTSecurityTokenHandler jwt = new JWTSecurityTokenHandler();

                // Configure validation
                Byte[][] certBytes = getCertBytes();
                for (int i = 0; i < certBytes.Length; i++)
                {
                    X509Certificate2 certificate = new X509Certificate2(certBytes[i]);
                    X509SecurityToken certToken = new X509SecurityToken(certificate);

                    // Set up token validation
                    TokenValidationParameters tvp = new TokenValidationParameters();
                    tvp.AllowedAudience = CLIENT_ID;
                    tvp.SigningToken = certToken;
                    tvp.ValidIssuer = "accounts.google.com";

                    // Enable / disable tests
                    tvp.ValidateNotBefore = false;
                    tvp.ValidateExpiration = true;
                    tvp.ValidateSignature = true;
                    tvp.ValidateIssuer = true;

                    // Account for clock skew. Look at current time when getting the message
                    // "The token is expired" in try/catch block.
                    // This is relative to GMT, for example, GMT-8 is:
                    tvp.ClockSkewInSeconds = 3600 * 13;

                    try
                    {
                        // Validate using the provider
                        ClaimsPrincipal cp = jwt.ValidateToken(token, tvp);
                        if (cp != null)
                        {
                            its.valid = true;
                            its.message = "Valid ID Token.";
                        }
                    }
                    catch (Exception e)
                    {
                        // Multiple certificates are tested.
                        if (its.valid != true)
                        {
                            its.message = "Invalid ID Token.";
                        }
                        if (e.Message.IndexOf("The token is expired") > 0)
                        {
                            // TODO: Check current time in the exception for clock skew.
                        }
                    }
                }

                // Get the Google+ id for this user from the "sub" claim.
                Claim[] claims = token.Claims.ToArray<Claim>();
                for (int i = 0; i < claims.Length; i++)
                {
                    if (claims[i].Type.Equals("sub"))
                    {
                        its.gplus_id = claims[i].Value;
                    }
                }
            }

            // Use Tokeninfo to validate the user and the client.
            var tokeninfo_request = new Oauth2Service().Tokeninfo();
            tokeninfo_request.Access_token = accessToken;

            // Use Google as a trusted provider to validate the token.
            // Invalid values, including expired tokens, return 400
            Tokeninfo tokeninfo = null;
            try
            {
                tokeninfo = tokeninfo_request.Fetch();
                if (tokeninfo.Issued_to != CLIENT_ID){
                    ats.message = "Access Token not meant for this app.";
                }else{
                    ats.valid = true;
                    ats.message = "Valid Access Token.";
                    ats.gplus_id = tokeninfo.User_id;
                }
            }
            catch (Exception stve)
            {
                ats.message = "Invalid Access Token.";
            }

            // Use the wrapper to return JSON
            token_status_wrapper tsr = new token_status_wrapper();
            tsr.id_token_status = its;
            tsr.access_token_status = ats;

            context.Response.StatusCode = 200;
            context.Response.ContentType = "text/json";
            context.Response.Write(JsonConvert.SerializeObject(tsr));
        }
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Redirect base path to signin.
            if (context.Request.Path.Equals("/"))
            {
                context.Response.RedirectPermanent("signin.ashx");
            }

            // This is reached when the root document is passed. Return HTML
            // using index.html as a template.
            if (context.Request.Path.Equals("/signin.ashx"))
            {
                String state = (String)context.Session["state"];

                // Store a random string in the session for verifying
                // the responses in our OAuth2 flow.
                if (state == null)
                {
                    Random random = new Random((int)DateTime.Now.Ticks);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < 13; i++)
                    {
                        builder.Append(Convert.ToChar(
                                Convert.ToInt32(Math.Floor(
                                        26 * random.NextDouble() + 65))));
                    }
                    state = builder.ToString();
                    context.Session["state"] = state;
                }

                // Render the templated HTML.
                String templatedHTML = File.ReadAllText(
                     context.Server.MapPath("index.html"));
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME);
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID);
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*STATE\\s*[}]{2}", state);

                context.Response.ContentType = "text/html";
                context.Response.Write(templatedHTML);
                return;
            }

            if (context.Session["authState"] == null)
            {
                // The connect action exchanges a code from the sign-in button,
                // verifies it, and creates OAuth2 credentials.
                if (context.Request.Path.Contains("/connect"))
                {
                    // Get the code from the request POST body.
                    StreamReader sr = new StreamReader(
                        context.Request.InputStream);
                    string code = sr.ReadToEnd();

                    string state = context.Request["state"];
                    string userid = context.Request["gplus_id"];

                    // Test that the request state matches the session state.
                    if (!state.Equals(context.Session["state"]))
                    {
                        context.Response.StatusCode = 401;
                        return;
                    }

                    // Manually perform the OAuth2 flow for now.
                    var authObject = ManualCodeExchanger.ExchangeCode(code);

                    // Create an authorization state from the returned token.
                    _authState = CreateState(
                        authObject.access_token, authObject.refresh_token,
                        DateTime.UtcNow,
                        DateTime.UtcNow.AddSeconds(authObject.expires_in));

                    // Use Tokeninfo to validate the user and the client.
                    var tokeninfo_request = new Oauth2Service().Tokeninfo();
                    tokeninfo_request.Access_token = _authState.AccessToken;
                    var tokeninfo = tokeninfo_request.Fetch();
                    if (userid == tokeninfo.User_id
                        && tokeninfo.Issued_to == CLIENT_ID)
                    {
                        context.Session["authState"] = _authState;
                    }
                    else
                    {
                        // The credentials did not match.
                        context.Response.StatusCode = 401;
                        return;
                    }
                }
                else
                {
                    // No cached state and we are not connecting.
                    context.Response.StatusCode = 400;
                    return;
                }
            }
            else
            {
                // Register the authenticator and construct the Plus service
                // for performing API calls on behalf of the user.
                _authState =
                    (IAuthorizationState)context.Session["authState"];
                AuthorizationServerDescription description =
                    GoogleAuthenticationServer.Description;
                var provider = new WebServerClient(description);
                provider.ClientIdentifier = CLIENT_ID;
                provider.ClientSecret = CLIENT_SECRET;
                var authenticator =
                    new OAuth2Authenticator<WebServerClient>(
                        provider,
                        GetAuthorization)
                    {
                        NoCaching = true
                    };
                ps = new PlusService(authenticator);
            }

            // Perform an authenticated API request to retrieve the list of
            // people that the user has made visible to the app.
            if (context.Request.Path.Contains("/people"))
            {
                // Get the PeopleFeed for the currently authenticated user.
                PeopleFeed pf = ps.People.List("me", PeopleResource.CollectionEnum.Visible).Fetch();

                // This JSON, representing the people feed, will later be
                // parsed by the JavaScript client.
                string jsonContent =
                    Newtonsoft.Json.JsonConvert.SerializeObject(pf);
                context.Response.ContentType = "application/json";
                context.Response.Write(jsonContent);
                return;
            }

            // Disconnect the user from the application by revoking the tokens
            // and removing all locally stored data associated with the user.
            if (context.Request.Path.Contains("/disconnect"))
            {
                // Perform a get request to the token endpoint to revoke the
                // refresh token.
                _authState =
                    (IAuthorizationState)context.Session["authState"];
                string token = (_authState.RefreshToken != null) ?
                    _authState.RefreshToken : _authState.AccessToken;

                WebRequest request = WebRequest.Create(
                    "https://accounts.google.com/o/oauth2/revoke?token=" +
                    token);

                WebResponse response = request.GetResponse();

                // Remove the cached credentials.
                context.Session["authState"] = null;

                // You could reset the state in the session but you must also
                // reset the state on the client.
                // context.Session["state"] = null;
                context.Response.Write(
                    response.GetResponseStream().ToString().ToCharArray());
                return;
            }
        }
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Get the code from the request POST body.
            string accessToken = context.Request.Params["access_token"];
            string idToken = context.Request.Params["id_token"];

            // Validate the ID token
            if (idToken != null)
            {
                JwtSecurityToken token = new JwtSecurityToken(idToken);
                JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler();

                // Configure validation
                Byte[][] certBytes = getCertBytes();
                Dictionary<String, X509Certificate2> certificates = new Dictionary<String, X509Certificate2>();

                for (int i = 0; i < certBytes.Length; i++)
                {
                    X509Certificate2 certificate = new X509Certificate2(certBytes[i]);
                    certificates.Add(certificate.Thumbprint, certificate);
                }
                {
                    // Set up token validation
                    TokenValidationParameters tvp = new TokenValidationParameters()
                    {
                        ValidateActor = false, // check the profile ID

                        ValidateAudience = (CLIENT_ID != "YOUR_VALID_CLIENT_ID"), // check the client ID
                        ValidAudience = CLIENT_ID,

                        ValidateIssuer = true, // check token came from Google
                        ValidIssuer = "accounts.google.com",

                        ValidateIssuerSigningKey = true,
                        RequireSignedTokens = true,
                        CertificateValidator = X509CertificateValidator.None,
                        IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
                        {
                            return identifier.Select(x =>
                            {
                                // TODO: Consider returning null here if you have case sensitive JWTs.
                                /*if (!certificates.ContainsKey(x.Id))
                                {
                                    return new X509SecurityKey(certificates[x.Id]);
                                }*/
                                if (certificates.ContainsKey(x.Id.ToUpper()))
                                {
                                    return new X509SecurityKey(certificates[x.Id.ToUpper()]);
                                }
                                return null;
                            }).First(x => x != null);
                        },
                        ValidateLifetime = true,
                        RequireExpirationTime = true,
                        ClockSkew = TimeSpan.FromHours(13)
                    };

                    try
                    {
                        // Validate using the provider
                        SecurityToken validatedToken;
                        ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken);
                        if (cp != null)
                        {
                            its.valid = true;
                            its.message = "Valid ID Token.";
                        }
                    }
                    catch (Exception e)
                    {
                        // Multiple certificates are tested.
                        if (its.valid != true)
                        {
                            its.message = "Invalid ID Token.";
                        }
                        if (e.Message.IndexOf("The token is expired") > 0)
                        {
                            // TODO: Check current time in the exception for clock skew.
                        }
                    }
                }

                // Get the Google+ id for this user from the "sub" claim.
                Claim[] claims = token.Claims.ToArray<Claim>();
                for (int i = 0; i < claims.Length; i++)
                {
                    if (claims[i].Type.Equals("sub"))
                    {
                        its.gplus_id = claims[i].Value;
                    }
                }
            }

            // Use Tokeninfo to validate the user and the client.
            var tokeninfo_request = new Oauth2Service().Tokeninfo();
            tokeninfo_request.AccessToken = accessToken;

            // Use Google as a trusted provider to validate the token.
            // Invalid values, including expired tokens, return 400
            Tokeninfo tokeninfo = null;
            try
            {
                tokeninfo = tokeninfo_request.Execute();
                if (tokeninfo.IssuedTo != CLIENT_ID)
                {
                    ats.message = "Access Token not meant for this app.";
                }
                else
                {
                    ats.valid = true;
                    ats.message = "Valid Access Token.";
                    ats.gplus_id = tokeninfo.UserId;
                }
            }
            catch (Exception stve)
            {
                ats.message = "Invalid Access Token: " + stve.Message;
            }

            // Use the wrapper to return JSON
            token_status_wrapper tsr = new token_status_wrapper();
            tsr.id_token_status = its;
            tsr.access_token_status = ats;

            context.Response.StatusCode = 200;
            context.Response.ContentType = "text/json";
            context.Response.Write(JsonConvert.SerializeObject(tsr));
        }
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Redirect base path to signin.
            if (context.Request.Path.EndsWith("/"))
            {
                context.Response.RedirectPermanent("signin.ashx");
            }

            // This is reached when the root document is passed. Return HTML
            // using index.html as a template.
            if (context.Request.Path.EndsWith("/signin.ashx"))
            {
                String state = (String)context.Session["state"];

                // Store a random string in the session for verifying
                // the responses in our OAuth2 flow.
                if (state == null)
                {
                    Random random = new Random((int)DateTime.Now.Ticks);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < 13; i++)
                    {
                        builder.Append(Convert.ToChar(
                                Convert.ToInt32(Math.Floor(
                                        26 * random.NextDouble() + 65))));
                    }
                    state = builder.ToString();
                    context.Session["state"] = state;
                }

                // Render the templated HTML.
                String templatedHTML = File.ReadAllText(
                     context.Server.MapPath("index.html"));
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME);
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId);
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*STATE\\s*[}]{2}", state);

                context.Response.ContentType = "text/html";
                context.Response.Write(templatedHTML);
                return;
            }

            if (context.Session["authState"] == null)
            {
                // The connect action exchanges a code from the sign-in button,
                // verifies it, and creates OAuth2 credentials.
                if (context.Request.Path.Contains("/connect"))
                {
                    // Get the code from the request POST body.
                    StreamReader sr = new StreamReader(
                        context.Request.InputStream);
                    string code = sr.ReadToEnd();

                    string state = context.Request["state"];

                    // Test that the request state matches the session state.
                    if (!state.Equals(context.Session["state"]))
                    {
                        context.Response.StatusCode = 401;
                        return;
                    }

                    // Use the code exchange flow to get an access and refresh token.
                    IAuthorizationCodeFlow flow =
                        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                        {
                            ClientSecrets = secrets,
                            Scopes = SCOPES
                        });

                    token = flow.ExchangeCodeForTokenAsync("", code, "postmessage",
                            CancellationToken.None).Result;

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = token;

                    // Get tokeninfo for the access token if you want to verify.
                    Oauth2Service service = new Oauth2Service(
                        new Google.Apis.Services.BaseClientService.Initializer());
                    Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
                    request.AccessToken = token.AccessToken;

                    Tokeninfo info = request.Execute();

                    string gplus_id = info.UserId;
                }
                else
                {
                    // No cached state and we are not connecting.
                    context.Response.StatusCode = 400;
                    return;
                }
            }
            else if (context.Request.Path.Contains("/connect"))
            {
                // The user is already connected and credentials are cached.
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = 200;
                context.Response.Write(JsonConvert.SerializeObject("Current user is already connected."));
                return;
            }
            else
            {
                // Register the authenticator and construct the Plus service
                // for performing API calls on behalf of the user.
                token = (TokenResponse)context.Session["authState"];
                IAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = secrets,
                        Scopes = SCOPES
                    });

                UserCredential credential = new UserCredential(flow, "me", token);
                bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;

                token = credential.Token;
                ps = new PlusService(
                    new Google.Apis.Services.BaseClientService.Initializer()
                    {
                        ApplicationName = ".NET Quickstart",
                        HttpClientInitializer = credential
                    });
            }

            // Perform an authenticated API request to retrieve the list of
            // people that the user has made visible to the app.
            if (context.Request.Path.Contains("/people"))
            {
                // Get the PeopleFeed for the currently authenticated user.
                PeopleFeed pf = ps.People.List("me",
                        PeopleResource.ListRequest.CollectionEnum.Visible).Execute();

                // This JSON, representing the people feed, will later be
                // parsed by the JavaScript client.
                string jsonContent =
                    Newtonsoft.Json.JsonConvert.SerializeObject(pf);
                context.Response.ContentType = "application/json";
                context.Response.Write(jsonContent);
                return;
            }

            // Disconnect the user from the application by revoking the tokens
            // and removing all locally stored data associated with the user.
            if (context.Request.Path.Contains("/disconnect"))
            {
                // Perform a get request to the token endpoint to revoke the
                // refresh token.
                token = (TokenResponse)context.Session["authState"];
                string tokenToRevoke = (token.RefreshToken != null) ?
                    token.RefreshToken : token.AccessToken;

                WebRequest request = WebRequest.Create(
                    "https://accounts.google.com/o/oauth2/revoke?token=" +
                    tokenToRevoke);

                WebResponse response = request.GetResponse();

                // Remove the cached credentials.
                context.Session["authState"] = null;

                // You could reset the state in the session but you must also
                // reset the state on the client.
                // context.Session["state"] = null;
                context.Response.Write(
                    response.GetResponseStream().ToString().ToCharArray());
                return;
            }
        }
Example #43
0
 public string GetAccountNameFromToken(IAuthorizationState token)
 {
     var client = GetNativeApplicationClient();
     var oauth2Service = new Oauth2Service(new OAuth2Authenticator<NativeApplicationClient>(client, authProvider => token));
     return oauth2Service.Userinfo.Get().Fetch().Email;
 }
Example #44
0
        public static Userinfo GetUserInfo(IAuthenticator credentials)
        {
            Oauth2Service userInfoService = new Oauth2Service(new BaseClientService.Initializer() { Authenticator = credentials });
            Userinfo userInfo = null;
            string err = "";
            try
            {
            userInfo = userInfoService.Userinfo.Get().Fetch();

            }
            catch (GoogleApiRequestException e)
            {
            err = "An error occurred: " + e.Message;
            Console.WriteLine(err);
            }

            if (userInfo != null && !String.IsNullOrEmpty(userInfo.Id))
            {
            return userInfo;
            }
            else
            {
            throw new Exception(err);
            }
        }