コード例 #1
0
        public static GoogleUserOutputData GetGoogleOauth(string code)
        {
            var data         = $"code={code}&client_id={googleClientId}&client_secret={googleClientSecret}&redirect_uri={googleRedirectUrl}&grant_type=authorization_code";
            var getTokenCode = HttpHelper.CreateHttpGetRequest(getTokenUrl, data);

            GoogleUserOutputData result    = null;
            GoogleAccessToken    tokenInfo = JsonConvert.DeserializeObject <GoogleAccessToken>(getTokenCode);

            if (tokenInfo != null)
            {
                string accessToken = tokenInfo.access_token;
                if (!string.IsNullOrWhiteSpace(accessToken))
                {
                    WebClient client = new WebClient();
                    client.Encoding = Encoding.UTF8;

                    var    url            = urlProfile + accessToken;
                    string downloadString = client.DownloadString(url);

                    result = JsonConvert.DeserializeObject <GoogleUserOutputData>(downloadString);

                    result.token = accessToken;
                }
            }

            return(result);
        }
コード例 #2
0
        private Task <string> GetGoogleAccessToken(string code)
        {
            string         clientsecret    = "uiDtfbXXqMmyugp8h40nPu6t";
            string         clientid        = "388788439444-hlii2thkp1np99cegpteqcethv57f8ud.apps.googleusercontent.com";
            string         redirection_url = Url.Action("index", "Home", null, protocol: Request.Scheme);
            string         poststring      = $"grant_type=authorization_code&code={code}&client_id={clientid}&client_secret={clientsecret}&redirect_uri={redirection_url}";
            string         url             = "http://accounts.google.com/o/oauth2/token";
            HttpWebRequest webRequest      = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method = "POST";
            //Parameters = "code=" + code + "&client_id=" + client_id + "&client_secret=" + client_sceret + "&redirect_uri=" + redirect_url + "&grant_type=authorization_code";
            byte[] byteArray = Encoding.UTF8.GetBytes(poststring);
            webRequest.ContentType   = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            Stream postStream = webRequest.GetRequestStream();

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
            WebResponse response = webRequest.GetResponse();

            postStream = response.GetResponseStream();
            StreamReader      reader             = new StreamReader(postStream);
            string            responseFromServer = reader.ReadToEnd();
            GoogleAccessToken serStatus          = JsonConvert.DeserializeObject <GoogleAccessToken>(responseFromServer);

            if (serStatus != null)
            {
                string accessToken = string.Empty;
                accessToken = serStatus.access_token;
                return(Task.FromResult(accessToken));
            }

            return(null);
        }
コード例 #3
0
    private void GetAuthInfo(string code)
    {
        GoogleAccessToken accessTokenInfo = GetAccessTokenInfo(code);

        GoogleUserProfile userInfo = GetUserInfo(accessTokenInfo.access_token);

        Response.Write(userInfo.given_name + " " + userInfo.family_name);
    }
コード例 #4
0
        private bool IsAccessTokenValid(GoogleAccessToken accessToken)
        {
            if (accessToken == null || string.IsNullOrEmpty(accessToken.access_token))
            {
                return(false);
            }

            return(true);
        }
コード例 #5
0
 public void SaveCredentials(GoogleAccessToken tokens)
 {
     this.context.GoogleCredentials.Add(new GoogleCredentials
     {
         AccessToken    = tokens.AccessToken,
         RefreshToken   = tokens.RefreshToken,
         ExpirationTime = DateTime.Now.AddSeconds(tokens.ExpireIn),
     });
     this.context.SaveChanges();
 }
コード例 #6
0
        public async Task <GoogleCredentials> UpdateCredentials(GoogleAccessToken tokens)
        {
            var credentials = await this.context.GoogleCredentials
                              .FirstOrDefaultAsync();

            credentials.AccessToken    = tokens.AccessToken;
            credentials.ExpirationTime = DateTime.Now.AddSeconds(tokens.ExpireIn);

            await context.SaveChangesAsync();

            return(credentials);
        }
コード例 #7
0
        private GoogleAccessToken GetAccessToken(HttpWebRequest webRequest)
        {
            WebResponse  response           = webRequest.GetResponse();
            Stream       postStream         = response.GetResponseStream();
            StreamReader reader             = new StreamReader(postStream);
            string       responseFromServer = reader.ReadToEnd();

            postStream.Close();

            GoogleAccessToken accessToken = JsonConvert.DeserializeObject <GoogleAccessToken>(responseFromServer);

            return(accessToken);
        }
コード例 #8
0
        /// <summary>
        /// 取得Google 使用者profile
        /// </summary>
        /// <param name="googleAccessToken">AccessToken</param>
        /// <returns></returns>
        public async Task <GoogleUserProfile> GetProfile(GoogleAccessToken googleAccessToken)
        {
            try {
                var req = await Client.GetAsync($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={googleAccessToken.access_token}");

                var data = await req.Content.ReadAsStringAsync();

                var resData = JsonSerializer.Deserialize <GoogleUserProfile> (data);
                return(resData);
            } catch (Exception e) {
                throw e;
            }
        }
コード例 #9
0
ファイル: AuthController.cs プロジェクト: timchow/JournalApp
        public async Task <IActionResult> LoginFacebookWithAccessToken([FromBody] GoogleAccessToken body)
        {
            FacebookUserInfo userInfo = null;

            if (MockOn && body.AccessToken == MockToken)             // get value from config file
            {
                userInfo = new FacebookUserInfo(isMockuser: true);
            }
            else
            {
                HttpClient client = new HttpClient();

                // 1.generate an app access token
                (string, string)[] appAccessTokenRequestParameters =
コード例 #10
0
        private async void OnGoogleSignInAPIClick(object sender, RoutedEventArgs e)
        {
            // 請求取得 access token
            var json = await GoogleSignInAPI.InvokeGoogleSignIn();

            // 轉換成 json 物件
            var accessToken = new GoogleAccessToken(json);
            // 取得 user profile
            var userProfile = await GoogleSignInAPI.GetUserInfo(accessToken.access_token);

            txtGoogleSignInResult.Text = userProfile.name + "\n" + userProfile.email;
            var bitmapImage = new BitmapImage();

            bitmapImage.UriSource            = new Uri(userProfile.picture);
            imgPicture.Source                = bitmapImage;
            txtGoogleSignInResult.Visibility = imgPicture.Visibility = Visibility.Visible;
        }
コード例 #11
0
    public IEnumerator GetNewAccessToken(UnityWebRequest getAccessTokenHTTPRequest, IRefreshedTokenRequester requester)
    {
        UnityWebRequest NewAccessTokenRequest = getAccessTokenHTTPRequest;

        NewAccessTokenRequest.chunkedTransfer = false;
        NewAccessTokenRequest.timeout         = 100000;
        yield return(NewAccessTokenRequest.SendWebRequest());

        if (NewAccessTokenRequest.isNetworkError || NewAccessTokenRequest.isHttpError)
        {
            Debug.Log(NewAccessTokenRequest.downloadHandler.text);
        }
        else
        {
            string refresh_token = gat.refresh_token;
            gat = JsonUtility.FromJson <GoogleAccessToken>(NewAccessTokenRequest.downloadHandler.text);
            gat.refresh_token = refresh_token;
            requester.AfterRefreshedToken();
        }
    }
コード例 #12
0
        public async Task <ActionResult> GoogleCallback(string code, string callBackAction, string errorReturnToAction, object returnUrl)
        {
            try
            {
                HttpWebRequest    webRequest  = GetHttpWebRequest(Request, code, callBackAction);
                GoogleAccessToken accessToken = GetAccessToken(webRequest);

                if (!IsAccessTokenValid(accessToken))
                {
                    throw new Exception("Invalid access token");
                }

                UserSignupVM model = await GetGoogleUserData(accessToken.access_token);

                return(base.SignUpWithSocialAccount(model, returnUrl));
            }
            catch (Exception)
            {
                TempData[SocialAccount.SOCIALSIGNUPERROR.ToDescription()] = ErrorCode.SOCIALSIGNUPERROR.ToDescription();
                return(RedirectToAction(errorReturnToAction, "Account", new { returnUrl = returnUrl }));
            }
        }
コード例 #13
0
ファイル: FrmConnect.cs プロジェクト: wenhelinlu/imapx
        private void Authenticate(object arg)
        {
            try
            {
                if (_authMode == AuthMode.Google)
                {
                    GoogleAccessToken token   = GoogleOAuth2Provider.GetAccessToken(_oAuth2Code);
                    GoogleProfile     profile = GoogleOAuth2Provider.GetUserProfile(token);

                    Program.ImapClient.Credentials = new OAuth2Credentials(profile.email, token.access_token);
                }
                else if (_authMode == AuthMode.Outlook)
                {
                    var token   = OutlookOAuth2Provider.GetAccessToken(_oAuth2Code);
                    var profile = OutlookOAuth2Provider.GetUserProfile(token.access_token);
                    Program.ImapClient.Credentials = new OAuth2Credentials(profile.emails.account, token.access_token);
                }
                else if (_authMode == AuthMode.Yahoo)
                {
                    var token = YahooOAuth2Provider.GetAccessToken(_oAuth2Code);
                    Program.ImapClient.Credentials = new OAuth2Credentials(token.xoauth_yahoo_guid, token.access_token, "ImapX");
                }

                if (Program.ImapClient.Login())
                {
                    Invoke(new SuccessDelegate(OnAuthenticateSuccessful));
                }
                else
                {
                    Invoke(new FailedDelegate(OnAuthenticateFailed));
                }
            }
            catch (Exception ex)
            {
                Invoke(new FailedDelegate(OnAuthenticateFailed), new[] { ex });
            }
        }
コード例 #14
0
    GoogleAccessToken GetAccessTokenInfo(string code)
    {
        string redirectGoogleUrl = Request.Url.Scheme + "://" + Request.Url.Host + @"/Auth/Google/GoogleMakeAuth.aspx";

        string getAccessCodeUrl =
            string.Format("https://accounts.google.com/o/oauth2/token");

        string data = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
                                    code,
                                    "946891151573.apps.googleusercontent.com", //Resources.OAuth.Google_App_ID,
                                    "YLjmACkeCD2LmrJDrYa7EuGT",                //Resources.OAuth.Google_App_SecretKey,
                                    redirectGoogleUrl
                                    );

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getAccessCodeUrl);

        request.Method      = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        byte[] dataArray = Encoding.UTF8.GetBytes(data);
        request.ContentLength = dataArray.Length;
        Stream dataStream = request.GetRequestStream();

        dataStream.Write(dataArray, 0, dataArray.Length);
        dataStream.Close();

        HttpWebResponse response        = (HttpWebResponse)request.GetResponse();
        Encoding        enc             = Encoding.GetEncoding("utf-8");
        StreamReader    configStream    = new StreamReader(response.GetResponseStream(), enc);
        string          accessTokenJson = configStream.ReadToEnd();

        JavaScriptSerializer serializer  = new JavaScriptSerializer();
        GoogleAccessToken    accessToken = serializer.Deserialize <GoogleAccessToken>(accessTokenJson);

        return(accessToken);
    }
コード例 #15
0
    void ReadGoogleCalendarAccessToken()
    {
        TextAsset txtAsset = (TextAsset)Resources.Load("Credentials/access_token", typeof(TextAsset));

        gat = JsonUtility.FromJson <GoogleAccessToken>(txtAsset.text);
    }
コード例 #16
0
ファイル: GoogleDriveClient.cs プロジェクト: kelvincwk/RAD
        /// <summary>
        /// Authorise the app from the cloud API via the implemented connector
        /// </summary>
        protected override bool Authorise()
        {
            try
            {
                bool runLocally = (System.Configuration.ConfigurationManager.AppSettings["RunLocally"].ToString() == "true");
                ///Toggle between the debug mode and potentially the firewall access issues
                if (!runLocally)
                {
                    ///Running over the azure
                    string authRedirectURL = String.Empty;
                    authRedirectURL = "https://googledrivewatcher.azurewebsites.net/Home/SubscribeStorageChanges";
                    //authRedirectURL = "http://*****:*****@gmail.com";
                                string accessToken = string.Empty;
                                accessToken = serStatus.access_token;

                                if (!string.IsNullOrEmpty(accessToken))
                                {
                                    // This is where you want to add the code if login is successful.
                                    // getgoogleplususerdataSer(accessToken);

                                    var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                                    {
                                        ClientSecrets = new ClientSecrets
                                        {
                                            ClientId     = secrets.ClientId,
                                            ClientSecret = secrets.ClientSecret
                                        },
                                        Scopes    = _scopes,
                                        DataStore = new AppDataFileStore(".credentials")
                                    });

                                    var token = new TokenResponse
                                    {
                                        AccessToken  = accessToken,
                                        RefreshToken = serStatus.refresh_token
                                    };

                                    _credential = new UserCredential(flow, serStatus.id_token, token);
                                    return(_credential != null);
                                }
                            }
                        }
                    }
                }
                else
                {
                    //Below code does not work in Azure it is not allowed to mimic the browser
                    using (var stream =
                               new FileStream(HttpContext.Current.Request.MapPath("~/client_secret.json"), FileMode.Open, FileAccess.Read))
                    {
                        //string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                        string credPath = HttpContext.Current.Request.MapPath("~/App_Data/.credentials/drive.googleapis.com-dotnet-quickstart.json");
                        //credPath = Path.Combine(credPath, ".credentials\\drive.googleapis.com-dotnet-quickstart.json");

                        _credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                            GoogleClientSecrets.Load(stream).Secrets,
                            _scopes,
                            "user",
                            CancellationToken.None,
                            new FileDataStore(credPath, true)).Result;
                        Console.WriteLine("Credential file saved to: " + credPath);
                    }
                    return(_credential != null);

                    //Use the code exchange flow to get an access and refresh token.
                    //IAuthorizationCodeFlow flow =
                    //    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    //    {
                    //        ClientSecrets = secrets,
                    //        Scopes = _scopes
                    //    });
                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message, ex);
                ETL.Logging.Logger.Write(new ETL.Logging.LogEntry {
                    Message = ex.Message
                });
                return(false);
            }
            return(false);
        }