/* * 正常的流程或Web流程: * 1. 获取授权地址 * 2. 访问授权地址 * 3. 授权成功后自动跳转至callback指定的网站,并获得code * 4. 通过code换取access token */ public static void StartAuth(string Appkey,string Appsecert,string callbackURL) { oauth = new NetDimension.Weibo.OAuth(Appkey ,Appsecert , callbackURL ); string url = oauth.GetAuthorizeURL( ResponseType.Code);//根据授权方法,获得授权地址。 System.Diagnostics.Process.Start(url);//模拟弹窗,Console方式直接打开了浏览器,Web项目可以根据需求来使用iframe、新窗口等打开此页面。 //打开浏览器,进行授权流程,之后会跳转到callback指定的网址,并获得code }
protected void LinkButton1_Click(object sender, EventArgs e) { //Response.Write( GetBytesByImagePath("/img/bg1.jpg")); if (Session["Token"] == null) { //string cusCallbackUrl = CallbackUrl + "?point=1"; OAuth myoauth = new NetDimension.Weibo.OAuth(AppKey, AppSecret, CallbackUrl); String authUrl = myoauth.GetAuthorizeURL(ResponseType.Code, null, DisplayType.Default); Response.Redirect(authUrl); } else { Sina = new Client(new OAuth(AppKey, AppSecret, Session["Token"].ToString(), null)); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 UserID = Sina.API.Account.GetUID(); string weiboContent = "想让韩国国宝级彩妆大师朴泰轮教你如何打造少女肌肤吗?现在观看#人人都爱少女肌肤#教学视频就能从#innisfree#这里学到少女肌肤的底妆秘籍,还有机会赢取#悦诗风吟矿物质纯安动人粉底膏#哦!立刻猛击"; string jpgPath = Server.MapPath("") + "\\img\\bg1.jpg"; Sina.API.Statuses.Upload(weiboContent, GetBytesByImagePath(jpgPath)); //Sina.API.Statuses.Update(weiboContent); } }
public WeiboShare() { if (null == oAuth && !IsNullOrEmpty()) { oAuth = new OAuth(Properties.Settings.Default.AppKey, Properties.Settings.Default.AppSecrect, Properties.Settings.Default.CallbackUrl); } }
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); } }
/// <summary> /// 实例化微博操作类 /// </summary> /// <param name="oauth">OAuth实例</param> public Client(OAuth oauth) { this.OAuth = oauth; #if NET40 API = new Interface.InterfaceSelector(this); #else API = new Interface.EntityInterfaces(this); #endif }
/// <summary> /// 微博用户登录 /// </summary> private void login() { string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"]; string appSecret = System.Configuration.ConfigurationManager.AppSettings["appSecret"]; string userName = System.Configuration.ConfigurationManager.AppSettings["userName"]; string password = System.Configuration.ConfigurationManager.AppSettings["userPassword"]; OAuth oauth = new OAuth(appKey, appSecret); oauth.ClientLogin(userName, password); client = new Client(oauth); }
public Form1() { InitializeComponent(); appKey = Properties.Settings.Default.AppKey; appSecret = Properties.Settings.Default.AppSecret; accessToken = Properties.Settings.Default.AcessToken; serialReadFlag = false; OAuth oauth = null; sina = null; if (string.IsNullOrEmpty(accessToken))//如果本地未保存accessToken,这里没有做过期判断2012-10-5 { oauth = Authorize(); if (!string.IsNullOrEmpty(oauth.AccessToken)) { Properties.Settings.Default.AcessToken = oauth.AccessToken; Properties.Settings.Default.Save(); statTxt.Text = "授权成功,保存accesstoken"; sina = new Client(oauth); } else { statTxt.Text = "授权失败,未获取accesstoken"; } } else { oauth = new OAuth(appKey, appSecret, accessToken, "");//最后一个参数是refreshtoken这个是面向高级用户对的 TokenResult tokenResult = oauth.VerifierAccessToken(); if (tokenResult == TokenResult.Success) { statTxt.Text = "验证本地accesstoken有效"; sina = new Client(oauth); } else { Properties.Settings.Default.AcessToken = string.Empty; Properties.Settings.Default.Save(); statTxt.Text = "验证本地accesstoken无效,尝试重新授权"; oauth = Authorize(); if (!string.IsNullOrEmpty(oauth.AccessToken)) { Properties.Settings.Default.AcessToken = oauth.AccessToken; Properties.Settings.Default.Save(); statTxt.Text = "授权成功,重新保存accesstoken"; sina = new Client(oauth); } else { statTxt.Text = "授权失败,未获取accesstoken"; } } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string cusCallbackUrl = CallbackUrl + "?point=1"; OAuth oauth = new NetDimension.Weibo.OAuth(AppKey, AppSecret, cusCallbackUrl); if (Session["Token"] != null) { string token = (string)Session["Token"]; OAuth newoauth = new OAuth(AppKey, AppSecret, token, ""); NetDimension.Weibo.Client Sina = new NetDimension.Weibo.Client(newoauth); String uid = Sina.API.Account.GetUID(); NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Users.Show(uid, null); //NetDimension.Weibo.Entities.user.Collection userFriends = new NetDimension.Weibo.Entities.user.Collection(); Session["wid"] = uid; Response.Redirect(CallbackUrl); } else { String mycode = Request.QueryString["code"]; if (mycode == String.Empty || mycode == null) { String authUrl = oauth.GetAuthorizeURL(ResponseType.Code, null, DisplayType.Default); Response.Redirect(authUrl); } else { AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(mycode); NetDimension.Weibo.Client Sina = new NetDimension.Weibo.Client(oauth); String uid = Sina.API.Account.GetUID(); //Response.Write(uid); Session["wid"] = Sina.API.Account.GetUID(); Response.Redirect(CallbackUrl); Session["Token"] = accessToken.Token; } } } }
static void Main() { OAuth oauth = new OAuth(Properties.Settings.Default.AppKey, Properties.Settings.Default.AppSecret, Properties.Settings.Default.CallbackUrl); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); frmLogin LoginForm = new frmLogin(oauth); if (LoginForm.ShowDialog() == DialogResult.OK) { Application.Run(new frmChat(oauth)); } }
public override void Post() { if (!String.IsNullOrEmpty(this.accessToken = Config.WeiboAccessToken)) { oauth = new OAuth(AppKey, AppSecret, accessToken, null); sinaClient = new Client(oauth); PostWeibo(); } else { AuthAndPost(); } }
private void btnSendToWeibo_Click(object sender, EventArgs e) { OAuth oauth = new OAuth(appKey, appSecrect, callbackUrl); string passport = this.txtName.Text.Trim(); string password = this.txtPwd.Text.Trim(); //string accessToken = string.Empty; bool result = oauth.ClientLogin(passport, password); if (!result) { MessageBoxHelper.Show("微博登陆失败!"); return; } //好吧,授权至此应该成功了。下一步调用接口吧。 Client Sina = new Client(oauth); try { //.Net其他版本 string uid = Sina.API.Account.GetUID(); //获取UID //这里用VS2010的var关键字和可选参数最惬意了。 //如果用VS2005什么的你得这样写: //NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Users.Show(uid,null); //如果用VS2008什么的也不方便,你得把参数写全: //var userInfo = Sina.API.Users.Show(uid,null); var userInfo = Sina.API.Users.Show(uid, null); Console.WriteLine("昵称:{0}", userInfo.ScreenName); Console.WriteLine("来自:{0}", userInfo.Location); //发条微博啥的 Image img = this.imageProcessPanel1.GetFinalImage(); //var statusInfo = Sina.API.Statuses.Update(string.Format("我是{0},我来自{1},我在{2}用《新浪微博开放平台API for .Net SDK》开发了一个小程序并发了这条微博,欢迎关注http://weibosdk.codeplex.com/", userInfo.ScreenName, userInfo.Location, DateTime.Now.ToShortTimeString()),0,0,""); var statusInfo = Sina.API.Statuses.Upload("测试内容"+System.DateTime.Now.ToLocalTime().ToString(), ImageHelper.GetBytesByImage(img), 0, 0, ""); //加个当前时间防止重复提交报错。 Console.WriteLine("微博已发送,发送时间:{0}", statusInfo.CreatedAt); MessageBoxHelper.Show("微博已发送"); } catch (WeiboException ex) { Console.WriteLine("出错啦!" + ex.Message); MessageBoxHelper.Show("出错啦!" + ex.Message); } Console.WriteLine("演示结束,按任意键继续..."); }
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); } } }
public static OAuth Authorize(string CallbackUrl) { string AppKey = ConfigurationManager.AppSettings["app_key"].ToString(); string AppSecrect = ConfigurationManager.AppSettings["app_secret"].ToString(); OAuth o = new OAuth(AppKey, AppSecrect,CallbackUrl); //string authorizeUrl = o.GetAuthorizeURL(); while (!ClientLogin(o)) //使用模拟方法 { //Console.WriteLine("授权登录失败,请重试。"); HttpContext.Current.Response.Write("授权登录失败,请重试。"); } return o; }
private static bool ClientLogin(OAuth o) { //Console.Write("微博账号:"); string passport = "*****@*****.**"; //Console.Write("登录密码:"); //ConsoleColor originColor = Console.ForegroundColor; //Console.ForegroundColor = Console.BackgroundColor; //知道这里是在干啥不?其实是为了不让你们看到我的密码^_^ string password = "******"; //Console.ForegroundColor = originColor; //恢复前景颜色。 return o.ClientLogin(passport, password); }
void AuthAndPost() { fRefreshed = true; oauth = new OAuth(AppKey, AppSecret, "https://api.weibo.com/oauth2/default.html"); WeiboLoginDialog loginDialog = new WeiboLoginDialog(oauth); System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(loginDialog); if (loginDialog.ShowDialog() == true) { SaveAndPost(); } else { App.Instance.AddError(Config.AUTHORIZATION_ERROR_CN, Config.WEIBO_TITLE); } }
protected void ImageButton2_Click(object sender, ImageClickEventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data/ThirdLogin.xml"))); XmlNode node = xmlDoc.SelectSingleNode("//ThirdLogin//WeiBo//AppID"); XmlNode node1 = xmlDoc.SelectSingleNode("//ThirdLogin//WeiBo//Key"); string returnurl = AppConfig.HomeUrl() + "Passport/ThirdLogin.aspx"; if (url != "") { returnurl += "?url=" + url; } var oauth = new NetDimension.Weibo.OAuth(node.InnerText, node1.InnerText, returnurl); //第一步获取新浪授权页面的地址 var authUrl = oauth.GetAuthorizeURL(); //VS2008需要指定全部4个参数,这里是VS2010等支持“可选参数”的开发环境的写法 // 第二步访问这个地址。 Response.Redirect(authUrl); }
/// <summary> /// 初始化Weibo /// </summary> /// <returns></returns> private string InitWeiboOAuth() { if (Session["AccessToken"] == null) { OAUTH = new OAuth(APPKEY, APPSECRET, RETURNURL); if (!OAUTH.ClientLogin(WEIBO_NAME, PASSWORD)) { return "授权登录失败,请重试。"; } else { Session["AccessToken"] = OAUTH.AccessToken; Sina = new Client(OAUTH); UserID = Sina.API.Entity.Account.GetUID(); return OAUTH.AccessToken; } } else { return (string)Session["AccessToken"]; } }
static OAuth Authorize() { OAuth o = new OAuth(appKey, appSecrect, callbackUrl); //让使用者自行选择一个授权方式 /* * Console.WriteLine("请选择授权模式"); Console.WriteLine("1. 标准授权方式"); Console.WriteLine("2. 模拟授权方式");//一键授权登录 ConsoleKeyInfo key = Console.ReadKey(true); Console.WriteLine(); if (key.Key == ConsoleKey.D2) { * */ while (!ClientLogin(o)) //使用模拟方法 { Console.WriteLine("授权登录失败,请重试。"); } /* } else { string authorizeUrl = o.GetAuthorizeURL(ResponseType.Token,"",DisplayType.JS); System.Diagnostics.Process.Start(authorizeUrl); Console.WriteLine("复制浏览器中的Code:"+authorizeUrl); string code = Console.ReadLine(); try { AccessToken accessToken = o.GetAccessTokenByAuthorizationCode(code); //请注意这里返回的是AccessToken对象,不是string } catch (WeiboException ex) { Console.WriteLine(ex.Message); } //}*/ return o; }
public bool Login(string passport, string password) { accessToken = Properties.Settings.Default.AccessToken; if (string.IsNullOrEmpty(accessToken)) { try { oauth = Authorize(passport, password); online = true; sina = new Client(oauth); return true; } catch (Exception e) { return false; } } else { /* oauth = new OAuth(AppKey, AppSecret, accessToken, ""); TokenResult result = oauth.VerifierAccessToken(); if (result == TokenResult.Success) { //empty } else { return false; } */ return true; } return true; }
public OAuthUserInfo GetUserInfo(NameValueCollection queryString) { OAuthWeiboConfig config = WeiboCore.GetConfig(); NetDimension.Weibo.OAuth oAuth = new NetDimension.Weibo.OAuth(config.AppKey, config.AppSecret, Service.ReturnUrl); Client client = new Client(oAuth); oAuth.GetAccessTokenByAuthorizationCode(queryString["code"]); OAuthUserInfo oAuthUserInfo = null; if (oAuth != null) { oAuthUserInfo = new OAuthUserInfo(); oAuthUserInfo.OpenId = client.API.Entity.Account.GetUID(); Entity entity = client.API.Entity.Users.Show(oAuthUserInfo.OpenId, ""); string name = entity.Name; string str = name; oAuthUserInfo.RealName = name; oAuthUserInfo.NickName = str; oAuthUserInfo.IsMale = new bool?(entity.Gender == "m"); } return(oAuthUserInfo); }
protected void Page_Load(object sender, EventArgs e) { //string cusCallbackUrl = CallbackUrl + "?point=1"; //Response.Write(Server.MapPath("") + "\\images\\bg1.jpg"); OAuth oauth = new NetDimension.Weibo.OAuth(AppKey, AppSecret, CallbackUrl); if (Session["Token"] != null) { string token = (string)Session["Token"]; OAuth newoauth = new OAuth(AppKey, AppSecret, token, ""); Sina = new Client(newoauth); UserID = Sina.API.Account.GetUID(); NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Users.Show(UserID, null); UserName = userInfo.ScreenName; Session["wid"] = UserID; } else { String mycode = Request.QueryString["code"]; if (mycode == String.Empty || mycode == null) { } else { AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(mycode); Sina = new NetDimension.Weibo.Client(oauth); String UserID = Sina.API.Account.GetUID(); Session["wid"] = UserID; Session["Token"] = accessToken.Token; } } }
private Client InitializeSinaClient() { if (!string.IsNullOrEmpty(sessionKey))//检查是否存在SessionKey,后续可能还要从数据库去取 { OAuth2Base sinaAuth2 = new SinaWeiboOAuth2(); OAuth auth = new OAuth(sinaAuth2.AppKey, sinaAuth2.AppSecret, sessionKey, null); Client sinaClient = new Client(auth); return sinaClient; } else { throw new CustomException.NullWeiboSessionKeyException(); } }
private static bool ClientLogin(OAuth o) { string passport = Properties.WeiboOAuth.Default.WeiboUser; string password = Properties.WeiboOAuth.Default.WeiboPassword; Console.WriteLine("username:"******"password:"******"******"); return o.ClientLogin(passport, password); }
public App() { oAuth = new OAuth(AppKey, AppSecret, CallbackUrl); BLogin = false; }
public JsonResult OAuthInit() { JsonResult jr = new JsonResult(); jr.ContentType = "text/json"; jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; try { Client Sina = null; OAuth oauth = new OAuth(CnfgConst.Sina_AppKey, CnfgConst.Sina_AppSecret, CnfgConst.Sina_CallbackUrl); Sina = new Client(oauth); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 //if (!string.IsNullOrEmpty(code))//暂时无法获取到传回的URL //{ // var token = oauth.GetAccessTokenByAuthorizationCode(code); // string accessToken = token.Token; // Response.Cookies["AccessToken"].Value = accessToken; // jr.Data = new { isSuccess = true }; // //Response.Redirect("Default.aspx"); //} //else { string url = oauth.GetAuthorizeURL(); jr.Data = new { isSuccess = false, url = url }; } return jr; } catch (Exception) { throw; } }
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(); } } }
private static bool ClientLogin(OAuth o) { string username="******"; string password="******"; return o.ClientLogin(username, password); }
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); } }
/// <summary> /// 初始化Weibo /// </summary> /// <returns></returns> private static void InitWeiboOAuth(string APPKEY, string APPSECRET, string ACCESSTOKEN) { OAUTH = new OAuth(APPKEY, APPSECRET, accessToken: ACCESSTOKEN); if (OAUTH.VerifierAccessToken() == TokenResult.Success)//验证AccessToken是否有效 { SINA = new NetDimension.Weibo.Client(OAUTH); Console.WriteLine(OAUTH.AccessToken); //还是来打印下AccessToken看看与前面方式获取的是不是一样的 //streamWriter.WriteLine(OAUTH.AccessToken); } }
static OAuth Authorize() { OAuth o = new OAuth( Properties.WeiboOAuth.Default.AppKey, Properties.WeiboOAuth.Default.AppSecrect, Properties.WeiboOAuth.Default.CallbackUrl ); //让使用者自行选择一个授权方式 Console.WriteLine("Please choose OAuth mode:"); Console.WriteLine("1.Standard process"); Console.WriteLine("2.Second process");//一键授权登录 //ConsoleKeyInfo key = Console.ReadKey(true); Console.WriteLine("Auto use second one ...."); /* if (key.Key == ConsoleKey.D2) //使用模拟方法 */ //这里使用第二种方法抓取 { while (!ClientLogin(o)) { Console.WriteLine("OAuth fail, please try again."); Console.WriteLine(""); } Console.WriteLine("OAuth success!"); } /* else { string authorizeUrl = o.GetAuthorizeURL(); System.Diagnostics.Process.Start(authorizeUrl); Console.Write("复制浏览器中的Code:"); string code = Console.ReadLine(); try { AccessToken accessToken = o.GetAccessTokenByAuthorizationCode(code); //请注意这里返回的是AccessToken对象,不是string } catch (WeiboException ex) { Console.WriteLine(ex.Message); } } */ return o; }
public JsonResult OAuthLogin(string code) { JsonResult jr = new JsonResult(); jr.ContentType = "text/json"; jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; try { Client Sina = null; OAuth oauth = new OAuth(CnfgConst.Sina_AppKey, CnfgConst.Sina_AppSecret, CnfgConst.Sina_CallbackUrl); Sina = new Client(oauth); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 if (!string.IsNullOrEmpty(code))//暂时无法获取到传回的URL { var token = oauth.GetAccessTokenByAuthorizationCode(code); string accessToken = token.Token; Response.Cookies["AccessToken"].Value = accessToken; var userinfo = Sina.API.Dynamic.Users.Show(token.UID.ToString(), ""); jr.Data = new { isSuccess = true, Data = userinfo.ToString() }; //Response.Redirect("Default.aspx"); } else { jr.Data = new { isSuccess = false }; } return jr; } catch (Exception) { throw; } }
public static Client getOAuth() { OAuth oauth = null; Properties.WeiboOAuth.Default.AccessToken = string.Empty; Properties.WeiboOAuth.Default.Save(); string accessToken = Properties.WeiboOAuth.Default.AccessToken; if (string.IsNullOrEmpty(accessToken)) //判断配置文件中有没有保存到AccessToken,如果没有就进入授权流程 { oauth = Authorize(); if (!string.IsNullOrEmpty(oauth.AccessToken)) { Console.WriteLine("Get AccessToken{{{0}}} success!", oauth.AccessToken); Console.Write("Save Token to local in order to launch automaticaly next time? [Y/N]: Y"); /* if (Console.ReadKey(true).Key == ConsoleKey.Y) * */ { Properties.WeiboOAuth.Default.AccessToken = oauth.AccessToken; Properties.WeiboOAuth.Default.Save(); //配置文件已保存。如果要撤销AccessToken请删除ConsoleApp.exe.config中AcceessToken节点中的Token值。 Console.WriteLine(); Console.WriteLine("Token Saved."); } /* else { Console.WriteLine(); Console.WriteLine("AccessToken unsaved."); } */ } } else //如果配置文件中保存了AccesssToken { Console.WriteLine("Get saved AccessToken{{{0}}}!", accessToken); oauth = new OAuth(AppKey, AppSecret, accessToken, ""); //用Token实例化OAuth无需再次进入验证流程 Console.Write("Checking the saved Token ... "); TokenResult result = oauth.VerifierAccessToken(); //测试保存的AccessToken的有效性 if (result == TokenResult.Success) { Console.WriteLine("Done!"); /* Console.Write("Delete the saved token in order to OAuth next time?[Y/N]:"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { //如果想演示下登录授权,那就得把配置文件中的Token删除,所以做那么一个判断。 Properties.WeiboOAuth.Default.AccessToken = string.Empty; Properties.WeiboOAuth.Default.Save(); //已从配置文件移除AccessToken值,重新运行程序来演示授权过程。 Console.WriteLine(); Console.WriteLine("Access Token Removed"); } // */ } else { Console.WriteLine("Error! Message:{0}", result); Properties.WeiboOAuth.Default.AccessToken = string.Empty; Properties.WeiboOAuth.Default.Save(); //已从配置文件移除AccessToken值,重新运行程序获取有效的AccessToken Console.WriteLine("Access Token Deleted, Please run again."); Console.ReadKey(); return null; //AccessToken无效,继续执行没有任何意义,反正也无法调用API } } //好吧,授权至此应该成功了。下一步调用接口吧。 return new Client(oauth); }
public frmChat(NetDimension.Weibo.OAuth oauth) { InitializeComponent(); this.oauth = oauth; Sina = new NetDimension.Weibo.Client(oauth); }
static OAuth Authorize() { OAuth oauth = null; oauth = new OAuth(Properties.Settings.Default.AppKey, Properties.Settings.Default.AppSecret, Properties.Settings.Default.CallBackUrl); while (!ClientLogin(oauth)) { //尝试登陆直到登上为止 } return oauth; }