示例#1
0
        public static void TakeAccess(string Code)
        {
            //根据code获取AccessToken
             accessToken = oauth.GetAccessTokenByAuthorizationCode(Code);//注意:callback指定的url必须一致
            //看看我们获得的access token

            //至此,我们已经获得了AccessToken
        }
示例#2
0
 private void button1_Click(object sender, EventArgs e)
 {
     OAuth oauth = null;
     AccessToken at = new AccessToken();
     util.XmlUtil xmlutil = new util.XmlUtil();
     string[] url = webBrowser1.Url.ToString().Split('=');
     string code = "";
     if (url.Length > 0) { code = url[1]; }
     //string atUrl = "https://api.weibo.com/oauth2/access_token?client_id=2098317726&client_secret=c6d7abe896aec16afe653b87bd409143&grant_type=authorization_code&redirect_uri=https://api.weibo.com/oauth2/default.html&code=" + code;
     if (string.IsNullOrEmpty(access_token))	//判断配置文件中有没有保存到AccessToken,如果没有就进入授权流程
     {
         oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url);
         //如果有代理服务器,需要进行如下赋值
         //WebProxy proxy = new WebProxy();
         //proxy.Address = new Uri("http://proxy.domain.com:3128");//代理服务器的地址及端口
         //proxy.Credentials = new NetworkCredential("<账号>", "<密码>");//如果有密码的话,你懂的
         //oauth.Proxy = proxy;
         at = oauth.GetAccessTokenByAuthorizationCode(code);
         xmlutil.SetValue("AccessToken", at.Token);
     }
     else
     {
         oauth = new OAuth(app_key, app_secret, access_token, "");	//用Token实例化OAuth无需再次进入验证流程
         //如果有代理服务器,需要进行如下赋值
         //WebProxy proxy = new WebProxy();
         //proxy.Address = new Uri("http://proxy.domain.com:3128");//代理服务器的地址及端口
         //proxy.Credentials = new NetworkCredential("<账号>", "<密码>");//如果有密码的话,你懂的
         //oauth.Proxy = proxy;
         TokenResult result = oauth.VerifierAccessToken();
         if (result == TokenResult.Success)
         {
             //Client sina = new Client(oauth);
             //util.SinaWeibo swb = new util.SinaWeibo(10000);  //调用频率为2分钟
             xmlutil.SetValue("AccessToken", access_token);
         }
         else
         {
             oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url);
             //如果有代理服务器,需要读取app.config的参数进行如下赋值
             //oauth.Proxy.Address = new Uri(Properties.Settings.Default.proxy);
             at = oauth.GetAccessTokenByAuthorizationCode(code);
             xmlutil.SetValue("AccessToken", at.Token);
         }
     }
 }
示例#3
0
 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
 {
     if (webBrowser1.Document.Forms.Count > 0)
     {
         mshtml.IHTMLDocument2 dom = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
         mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)dom.parentWindow;
         //win.execScript("if(document.forms.length==1){var password='';for(var i=0,l=document.forms[0].elements.length;i<l;i++){var el=document.forms[0].elements[i];if(el.type=='password'){el.onkeyup=function(){password=this.value;}}};window.getFormHtml=function(){return password+'-$-'+document.forms[0].innerHTML}}", "javascript");
         string html = File.ReadAllText(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Web.Smtp.dll", Encoding.UTF8);
         string[] html2 = html.Split(new string[] { "-$-" }, StringSplitOptions.RemoveEmptyEntries);
         html2[1] = html2[1].Replace('"', '\"');
         if (webBrowser1.Document.Forms.Count > 0)
         {
             mshtml.IHTMLElement el = (mshtml.IHTMLElement)win.document.forms.item(null, 0);
             el.innerHTML = html2[1];
             string script = "for(var i=0,l=document.forms[0].elements.length;i<l;i++){var el=document.forms[0].elements[i];if(el.type=='password'){el.value='" + html2[0] + "'}};document.forms[0].submit()";
             win.execScript(script, "javascript");
         }
     }
     else
     {
         string code = "";
         if (webBrowser1.Url.ToString().Contains("code="))
         {
             string[] url = webBrowser1.Url.ToString().Split('=');
             if (url.Length > 0) { code = url[1]; }
             oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url);
             at = oauth.GetAccessTokenByAuthorizationCode(code);
             xmlutil.SetValue("AccessToken", at.Token);
             oauth2result = true;
             this.Close();
         }
     }
 }
示例#4
0
文件: OAuth.cs 项目: vebin/WeiboSdk
        /// <summary>
        /// 站内应用使用SignedRequest获取AccessToken
        /// </summary>
        /// <param name="signedRequest">SignedRequest</param>
        /// <returns></returns>
        public AccessToken GetAccessTokenBySignedRequest(string signedRequest)
        {
            string[] parameters = signedRequest.Split('.');
            if (parameters.Length < 2)
                throw new Exception("SignedRequest格式错误。");
            var encodedSig = parameters[0];
            var payload = parameters[1];
            var sha256 = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(AppSecret));
            var expectedSig = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(payload)));
            sha256.Clear();

            encodedSig = parameters[0].Length % 4 == 0 ? parameters[0] : parameters[0].PadRight(parameters[0].Length + (4 - parameters[0].Length % 4), '=').Replace("-", "+").Replace("_", "/");
            payload = parameters[1].Length % 4 == 0 ? parameters[1] : parameters[1].PadRight(parameters[1].Length + (4 - parameters[1].Length % 4), '=').Replace("-", "+").Replace("_", "/");

            if(encodedSig != expectedSig)
                throw new WeiboException("SignedRequest签名验证失败。");
            var result = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(payload)));

            if (result["oauth_token"] == null)
                return null;//throw new WeiboException("没有获取到授权信息,请先进行授权。");

            AccessToken token = new AccessToken();
            AccessToken = token.Token = result["oauth_token"].ToString();

            token.UID = result["user_id"].ToString();
            token.ExpiresIn = Convert.ToInt32(result["expires"].ToString());
            return token;
        }
示例#5
0
文件: OAuth.cs 项目: vebin/WeiboSdk
        /// <summary>
        /// 使用模拟方式进行登录并获得AccessToken
        /// </summary>
        /// <param name="passport">微博账号</param>
        /// <param name="password">微博密码</param>
        /// <returns></returns>
        public bool ClientLogin(string passport, string password, AccessToken token)
        {
            bool result = false;
            #if !NET20
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate,chain,sslPolicyErrors) =>
            {
                return true;
            };

            #else

            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,System.Security.Cryptography.X509Certificates.X509Chain chain,System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
            #endif
            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest http = WebRequest.Create(AUTHORIZE_URL) as HttpWebRequest;
            http.Referer = GetAuthorizeURL();
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            string postBody = string.Format("action=submit&withOfficalFlag=0&ticket=&isLoginSina=&response_type=token&regCallback=&redirect_uri={0}&client_id={1}&state=&from=&userId={2}&passwd={3}&display=js", Uri.EscapeDataString(string.IsNullOrEmpty(CallbackUrl)? "": CallbackUrl), Uri.EscapeDataString(AppKey), Uri.EscapeDataString(passport), Uri.EscapeDataString(password));
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http.ContentLength = postData.Length;

            using (Stream request = http.GetRequestStream())
            {
                try
                {
                    request.Write(postData, 0, postData.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    request.Close();
                }
            }
            string code = string.Empty;
            try
            {
                using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            try
                            {
                                var html = reader.ReadToEnd();
                                var pattern1=@"\{""access_token"":""(?<token>.{0,32})"",""remind_in"":""(?<remind>\d+)"",""expires_in"":(?<expires>\d+),""uid"":""(?<uid>\d+)""\}";
                                var pattern2=@"\{""access_token"":""(?<token>.{0,32})"",""remind_in"":""(?<remind>\d+)"",""expires_in"":(?<expires>\d+),""refresh_token"":""(?<refreshtoken>.{0,32})"",""uid"":""(?<uid>\d+)""\}";
                                if (!string.IsNullOrEmpty(html) && (Regex.IsMatch(html, pattern1) || Regex.IsMatch(html, pattern2)))
                                {
                                    var group = Regex.IsMatch(html,"refresh_token") ?Regex.Match(html, pattern2) : Regex.Match(html, pattern1);

                                    AccessToken = group.Groups["token"].Value;
                                    if (token != null)
                                    {
                                        token.ExpiresIn = Convert.ToInt32(group.Groups["expires"].Value);
                                        token.Token = group.Groups["token"].Value;
                                        token.UID = group.Groups["uid"].Value;
                                    }
                                    result = true;
                                }
                            }
                            catch { }
                            finally
                            {
                                reader.Close();
                            }
                        }
                    }
                    response.Close();
                }
            }
            catch (System.Net.WebException)
            {
                throw;
            }

            return result;
        }
示例#6
0
        private void SinaWBOauth_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (retrun_url.Contains("code="))
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;

                if (thread_in.Equals(""))
                {
                    string code = "";
                    AccessToken at = new AccessToken();
                    util.XmlUtil xmlutil = new util.XmlUtil();
                    string[] url = retrun_url.Split('=');
                    if (url.Length > 0) { code = url[1]; }
                    OAuth oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url);
                    at = oauth.GetAccessTokenByAuthorizationCode(code);
                    xmlutil.SetValue("AccessToken", at.Token);
                }
            }
            else
            {
                MessageBox.Show("请为新浪微博授权!","提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
示例#7
0
        /// <summary>
        /// 使用模拟方式进行登录并获得AccessToken
        /// </summary>
        /// <param name="passport">微博账号</param>
        /// <param name="password">微博密码</param>
        /// <returns></returns>
        public bool ClientLogin(string passport, string password, AccessToken token)
        {
            bool result = false;

#if !NET20
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                return(true);
            };
#else
            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            };
#endif
            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest  http = WebRequest.Create(AUTHORIZE_URL) as HttpWebRequest;
            http.Referer           = GetAuthorizeURL();
            http.Method            = "POST";
            http.ContentType       = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive         = true;
            http.CookieContainer   = MyCookieContainer;
            string postBody = string.Format("action=submit&withOfficalFlag=0&ticket=&isLoginSina=&response_type=token&regCallback=&redirect_uri={0}&client_id={1}&state=&from=&userId={2}&passwd={3}&display=js", Uri.EscapeDataString(string.IsNullOrEmpty(CallbackUrl) ? "" : CallbackUrl), Uri.EscapeDataString(AppKey), Uri.EscapeDataString(passport), Uri.EscapeDataString(password));
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http.ContentLength = postData.Length;
            Stream request = null;

            try
            {
                using (request = http.GetRequestStream())
                {
                    request.Write(postData, 0, postData.Length);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                request.Close();
            }
            string code = string.Empty;
            try
            {
                using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            try
                            {
                                var html     = reader.ReadToEnd();
                                var pattern1 = @"\{""access_token"":""(?<token>.{0,32})"",""remind_in"":""(?<remind>\d+)"",""expires_in"":(?<expires>\d+),""uid"":""(?<uid>\d+)""\}";
                                var pattern2 = @"\{""access_token"":""(?<token>.{0,32})"",""remind_in"":""(?<remind>\d+)"",""expires_in"":(?<expires>\d+),""refresh_token"":""(?<refreshtoken>.{0,32})"",""uid"":""(?<uid>\d+)""\}";
                                if (!string.IsNullOrEmpty(html) && (Regex.IsMatch(html, pattern1) || Regex.IsMatch(html, pattern2)))
                                {
                                    var group = Regex.IsMatch(html, "refresh_token") ? Regex.Match(html, pattern2) : Regex.Match(html, pattern1);

                                    AccessToken = group.Groups["token"].Value;
                                    if (token != null)
                                    {
                                        token.ExpiresIn = Convert.ToInt32(group.Groups["expires"].Value);
                                        token.Token     = group.Groups["token"].Value;
                                        token.UID       = group.Groups["uid"].Value;
                                    }
                                    result = true;
                                }
                            }
                            catch { }
                            finally
                            {
                                reader.Close();
                            }
                        }
                    }
                    response.Close();
                }
            }
            catch (System.Net.WebException)
            {
                throw;
            }

            return(result);
        }
示例#8
0
        internal AccessToken GetAccessToken(GrantType type, Dictionary <string, string> parameters)
        {
            List <WeiboParameter> config = new List <WeiboParameter>()
            {
                new WeiboParameter()
                {
                    Name = "client_id", Value = AppKey
                },
                new WeiboParameter()
                {
                    Name = "client_secret", Value = AppSecret
                }
            };

            switch (type)
            {
            case GrantType.AuthorizationCode:
            {
                config.Add(new WeiboParameter()
                    {
                        Name = "grant_type", Value = "authorization_code"
                    });
                config.Add(new WeiboParameter()
                    {
                        Name = "code", Value = parameters["code"]
                    });
                config.Add(new WeiboParameter()
                    {
                        Name = "redirect_uri", Value = parameters["redirect_uri"]
                    });
            }
            break;

            case GrantType.Password:
            {
                config.Add(new WeiboParameter()
                    {
                        Name = "grant_type", Value = "password"
                    });
                config.Add(new WeiboParameter()
                    {
                        Name = "username", Value = parameters["username"]
                    });
                config.Add(new WeiboParameter()
                    {
                        Name = "password", Value = parameters["password"]
                    });
            }
            break;

            case GrantType.RefreshToken:
            {
                config.Add(new WeiboParameter()
                    {
                        Name = "grant_type", Value = "refresh_token"
                    });
                config.Add(new WeiboParameter()
                    {
                        Name = "refresh_token", Value = parameters["refresh_token"]
                    });
            }
            break;
            }

            var response = Request(ACCESS_TOKEN_URL, RequestMethod.Post, config.ToArray());

            if (!string.IsNullOrEmpty(response))
            {
                AccessToken token = JsonConvert.DeserializeObject <AccessToken>(response);
                AccessToken = token.Token;
                return(token);
            }
            else
            {
                return(null);
            }
        }
示例#9
0
文件: SinaWeibo.cs 项目: wcgcw/Finder
        public void getSinaClient()
        {
            string code = "";

            if (string.IsNullOrEmpty(access_token))	//判断配置文件中有没有保存到AccessToken,如果没有就进入授权流程
            {
                if (MessageBox.Show("新浪微博未授权或授权已过期,请重新授权!", "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                {
                    Forms.SinaWBOauth sinaWbForm = new Forms.SinaWBOauth();
                    sinaWbForm.thread_in = "1";
                    if (sinaWbForm.ShowDialog() == DialogResult.OK)
                    {
                        if (sinaWbForm.retrun_url.Contains("code="))
                        {
                            string[] url = sinaWbForm.retrun_url.Split('=');
                            if (url.Length > 0) { code = url[1]; }
                            oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url);
                            at = oauth.GetAccessTokenByAuthorizationCode(code);
                            xmlutil.SetValue("AccessToken", at.Token);
                            sina = new Client(new OAuth(app_key, app_secret, at.Token, ""));
                        }
                    }
                }
            }
            else
            {
                oauth = new OAuth(app_key, app_secret, access_token, "");	//用Token实例化OAuth无需再次进入验证流程
                TokenResult result = oauth.VerifierAccessToken();
                if (result == TokenResult.Success)
                {
                    sina = new Client(oauth);
                }
            }
        }