public String actionGetNewTokenByUsernameAndPassword(String username, String password) { String encrypted_password = new AuthenticationController().getEncryptedString(password); User user = data.Users.Where(o => o.username == username && o.password == encrypted_password).SingleOrDefault(); if (user == null) { return null; } var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); String token = new string(Enumerable.Repeat(chars, 20) .Select(s => s[random.Next(s.Length)]) .ToArray()); OAuth oauth = new OAuth(); oauth.user_obj = user.id; oauth.access_token = token; data.OAuths.AddObject(oauth); if (data.SaveChanges() == 1) { return token; } else { return null; } }
// logs the user in and accesses their userId and userName public static void loginUser(out string userId, out string userName) { OAuth oAuth = new OAuth(); oAuth.getOAuthToken(); string userXML = oAuth.getOAuthDataUrl("http://www.goodreads.com/api/auth_user"); userId = ""; userName = ""; // grab the user name and user id XmlTextReader textReader = new XmlTextReader(userXML); while (textReader.Read()) { textReader.MoveToElement(); if (textReader.LocalName.Equals("user")) { textReader.MoveToAttribute("id"); userId = textReader.Value; } if (textReader.LocalName.Equals("name")) { userName = textReader.ReadElementContentAsString(); } } }
public APIAccess() { authentication = new OAuth(ClientId, ClientSecret, Endpoint); log = Logger.GetLogger(LoggingTarget.Network); thread = new Thread(run) { IsBackground = true }; thread.Start(); }
private AppData() { OAuth = new OAuth(clientId: "1639469262962972", // your OAuth2 client id scope: "public_profile,email,user_friends,user_about_me,user_status", // The scopes for the particular API you're accessing. The format for this will vary by API. authorizeUrl: "https://m.facebook.com/dialog/oauth/", // the auth URL for the service redirectUrl: "http://www.facebook.com/connect/login_success.html"); User = new User(); }
public Photobucket(string apiKey, string apiSecret, bool getLoginToken) { _apiKey = apiKey; _apiSecret = apiSecret; OAuth = new OAuth( _apiUrl, _apiKey, _apiSecret ); if (getLoginToken) { RequestLoginToken(); } }
protected void Page_Load(object sender, EventArgs e) { string verifier = Request.QueryString.Get("oauth_verifier"); if (!string.IsNullOrEmpty(verifier)) { string appKey = Constant.app_key_QQ; string appSecret = Constant.app_secret_QQ; OAuth oauth = new OAuth(appKey, appSecret); string name; oauth.Token = (string)Session["QQ_oauth_token"]; oauth.TokenSecret = (string)Session["QQ_oauth_token_secret"]; if (oauth.GetAccessToken(verifier, out name)) { Session["QQ_oauth_token"] = oauth.Token; Session["QQ_oauth_token_secret"] = oauth.TokenSecret; Session["QQ_user_id"] = name; DictEntity dt = new DictEntity(); dt.App = "QQ"; dt.UserID = name; dt.Key = "Token"; dt.Value = oauth.Token; Dict.Save(dt); dt.Key = "TokenSecret"; dt.Value = oauth.TokenSecret; Dict.Save(dt); ////MaxTimeline //Timeline api = new Timeline(oauth); //var data = api.GetBroadcast_timeline(PageFlag.First, 0, 1); //if (data.Tweets.Length > 0) //{ // OpenTSDK.Tencent.Objects.Tweet tw = data.Tweets[0]; // if (tw.Timestamp > 0) // { // DictEntity dtT = new DictEntity(); // dtT.App = "QQ"; // dtT.Key = "MaxTimeline"; // dtT.UserID = name; // dtT.Value = tw.Timestamp.ToString(); // Dict.Save(dtT); // } //} //T.SaveRelation(); //Response.Write(oauth.TokenSecret); Response.Redirect("SB.aspx"); } } }
protected void ConnectQQBtn_Click(object sender, EventArgs e) { string callback =Constant.AppCallBackDomain+ "/CB_QQ.aspx"; string appKey = Constant.app_key_QQ; string appSecret = Constant.app_secret_QQ; OAuth oauth = new OAuth(appKey, appSecret); if (oauth.GetRequestToken(callback)) { Session["QQ_oauth_token"] = oauth.Token; Session["QQ_oauth_token_secret"] = oauth.TokenSecret; string url = "https://open.t.qq.com/cgi-bin/authorize?oauth_token=" + oauth.Token; Response.Redirect(url); } }
public static Tweet CreateTweet(this Status status, TweetClassification tweetType) { var isMention = false; var isDirectMessage = false; var username = new OAuth().ScreenName; var displayStatus = status.RetweetedStatus ?? status; // Direct messages don't have a User. Instead, dm's use sender and recipient collections. if (displayStatus.User == null) { isDirectMessage = true; displayStatus.User = (status.Recipient.ScreenName == username) ? status.Sender : status.Recipient; } if (status.Entities != null && status.Entities.Mentions != null && status.Entities.Mentions.Any(m => m.ScreenName == username)) { isMention = true; } var createdAt = DateTime.ParseExact(status.CreatedAt, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); var tweet = new Tweet { StatusId = status.Id, Name = displayStatus.User.Name, ScreenName = displayStatus.User.ScreenName, ProfileImageUrl = displayStatus.User.ProfileImageUrl, Text = displayStatus.Text, MarkupNodes = BuildMarkupNodes(displayStatus.Text, displayStatus.Entities), CreatedAt = createdAt, TimeAgo = TimeAgo(createdAt), IsRetweet = status.Retweeted, RetweetedBy = RetweetedBy(status, username), RetweetedByScreenName = RetweetedByScreenName(status, username), RetweetStatusId = (status.RetweetedStatus != null) ? status.RetweetedStatus.Id : String.Empty, MediaLinks = status.Entities.Media != null ? status.Entities.Media.Select(m => m.MediaUrl).ToArray() : new string[0], IsMyTweet = displayStatus.User.ScreenName == username, IsHome = tweetType == TweetClassification.Home, IsMention = tweetType == TweetClassification.Mention | isMention, IsDirectMessage = tweetType == TweetClassification.DirectMessage | isDirectMessage, IsFavorite = tweetType == TweetClassification.Favorite | status.Favorited, IsSearch = tweetType == TweetClassification.Search }; return tweet; }
/// <summary> /// Use the app account settings from developer.att.com for the following values. /// Make sure ADS is enabled for the App Key and the App Secret. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Enter the value from the 'App Key' field obtained at developer.att.com in your // app account. string appKey = ""; // Enter the value from the 'App Secret' field obtained at developer.att.com // in your app account. string appSecret = ""; // Set the fully-qualified domain name to: https://api.att.com string fqdn = "https://api.att.com"; //Set the scope to ADS string scope = "ADS"; // Create the service for requesting an OAuth access token. var oauth = new OAuth(fqdn, appKey, appSecret, scope); // Get the OAuth access token using the Client Credentials. if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials)) { // Get access token OAuthToken at = new OAuthToken(); var accessToken = at.getAccessToken(oauth.accessTokenJson); // Create the service for making the method request. var ads = new Ads(fqdn, accessToken); // Set params: string category = "Auto"; string udid = "123456789012345678901234567890"; string userAgent ="Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"; try { // Make an Make a method call to the Advertising API. // param 1 category // param 2 udid // param 3 user agent AdsObj.RootObject ads_obj = ads.GetAds(category, udid, userAgent); } catch (Exception ex) { string error = ex.StackTrace; } } }
public async Task<ActionResult> OAuth(string code) { // add this code to the auth object var auth = new OAuth(config); // now we have to call back to instagram and include the code they gave us // along with our client secret var oauthResponse = await auth.RequestToken(code); // both the client secret and the token are considered sensitive data, so we won't be // sending them back to the browser. we'll only store them temporarily. If a user's session times // out, they will have to click on the authenticate button again - sorry bout yer luck. Session.Add("InstaSharp.AuthInfo", oauthResponse); // all done, lets redirect to the home controller which will send some intial data to the app return RedirectToAction("Index"); }
// submits a status update for a book to goodreads public static void submitBookStatus(Book book) { OAuth oAuth = new OAuth(); string statusURL = oAuth.getOAuthDataUrl("http://www.goodreads.com/user_status.xml"); HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(statusURL); httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded"; string postData = "user_status[book_id]=" + book.GoodreadsId + "&user_status[page]=" + book.CurrentPage + "&user_status[body]=Added%20By%20Bibliomania"; httpRequest.ContentLength = postData.Length; StreamWriter stOut = new StreamWriter(httpRequest.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(postData); stOut.Close(); StreamReader stIn = new StreamReader(httpRequest.GetResponse().GetResponseStream()); string strResponse = stIn.ReadToEnd(); stIn.Close(); Console.WriteLine(strResponse); }
static void Main(string[] args) { string consumerKey = "na"; string consumerSecret = "j98byb78yg78n"; string local = "http://localhost:1718"; string url, param; var oAuth = new OAuth(); var ts = oAuth.GenerateTimeStamp(); var uri = new Uri(string.Format("{0}/api/categories?limit=3&offset=2&cid={1}&cts={2}", local, consumerKey, ts)); var signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty, "GET", ts, null, OAuth.SignatureTypes.HMACSHA1, out url, out param); url = string.Format("{0}&cs={1}", uri, HttpUtility.UrlEncode(signature)); WebResponse webrespon = (WebResponse)WebRequest.Create(url).GetResponse(); StreamReader stream = new StreamReader(webrespon.GetResponseStream()); Console.WriteLine(stream.ReadToEnd()); Console.Read(); }
// adds a book to the currently reading shelf (statuses cannot be added for books not on this shelf) public static void addBookToShelf(Book book) { OAuth oAuth = new OAuth(); string shelfURL = oAuth.getOAuthDataUrl("http://www.goodreads.com/shelf/add_to_shelf.xml"); HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(shelfURL); httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded"; string postData = "book_id=" + book.GoodreadsId + "&name=currently-reading"; httpRequest.ContentLength = postData.Length; StreamWriter stOut = new StreamWriter(httpRequest.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(postData); stOut.Close(); StreamReader stIn = new StreamReader(httpRequest.GetResponse().GetResponseStream()); string strResponse = stIn.ReadToEnd(); stIn.Close(); Console.WriteLine(strResponse); }
internal static dynamic CheckOAuth( NancyContext ctx) { try { string query = ctx.Request.Url.Query; var qs = HttpUtility.ParseQueryString(query); var auth = new OAuth(); string clientID = qs.Get("cid"); string clientSignature = qs.Get("cs"); string clientTimestamp = qs.Get("cts"); if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSignature) || string.IsNullOrEmpty(clientTimestamp)) throw new Exception("You must supply valid authentication arguments to access method!"); qs.Remove("cs"); var original = ctx.Request.Url.SiteBase + ctx.Request.Url.Path + ConstructQueryString(qs); int ts = int.Parse(clientTimestamp); int now = int.Parse(auth.GenerateTimeStamp()); if ((now - ts) > 60) throw new Exception("Invalid Timestamp"); using (var db = new NorthwindEntities()) { var clientSecret = "j98byb78yg78n"; string normalized; string normalizedParams; var signature = auth.GenerateSignature(new Uri(original), clientID, clientSecret, null, null, ctx.Request.Method, clientTimestamp, null, Api.OAuth.OAuth.SignatureTypes.HMACSHA1, out normalized, out normalizedParams); if (!signature.Equals(clientSignature)) throw new Exception("Authentication failed!"); } return ctx.Response; } catch (Exception ex) { return HttpStatusCode.Unauthorized; } }
public string WebRequest(OAuth.WebMethod method, string url, string postData) { HttpWebRequest webRequest = null; StreamWriter requestWriter = null; string responseData = ""; webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; webRequest.Method = method.ToString(); webRequest.ServicePoint.Expect100Continue = false; //webRequest.UserAgent = "Identify your application please."; //webRequest.Timeout = 20000; if (method == OAuth.WebMethod.POST) { webRequest.ContentType = "application/x-www-form-urlencoded"; //POST the data. requestWriter = new StreamWriter(webRequest.GetRequestStream()); try { requestWriter.Write(postData); } catch { throw; } finally { requestWriter.Close(); requestWriter = null; } } responseData = WebResponseGet(webRequest); webRequest = null; return responseData; }
protected void Page_Load(object sender, EventArgs e) { var client = Session["client"] as Client; if (client == null) { string code = Request["code"]; if (string.IsNullOrEmpty(code)) { OAuth auth = new OAuth(Properties.Settings.Default.AppKey, Properties.Settings.Default.CallBack); HyperLink1.Text = "请授权"; HyperLink1.NavigateUrl = auth.GetAuthorizeURL(); } else { OAuth auth = new OAuth(Properties.Settings.Default.AppKey, Properties.Settings.Default.CallBack); string msg; if (auth.GetAccessTokenByCode(code, out msg)) { client = new Client(auth); Session["client"] = client; HyperLink1.Text = "授权成功"; HyperLink1.NavigateUrl = "#"; } else { HyperLink1.Text = "授权失败"; HyperLink1.NavigateUrl = "#"; } } } if (client != null) { HyperLink1.Text = "任务数量" + client.API.ProjectAPI.GetProjects().Count().ToString(); } }
public override object Authenticate(IServiceBase service, OAuth request, IOAuthSession session, IOAuthTokens tokens, OAuthAuthorizer oAuth) { var code = service.RequestContext.Get<IHttpRequest>().QueryString["code"]; var isPreAuthCallback = !code.IsNullOrEmpty(); if (!isPreAuthCallback) { var preAuthUrl = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), string.Join(",", Permissions)); return service.Redirect(preAuthUrl); } var accessTokenUrl = this.AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}" .Fmt(AppId, this.CallbackUrl.UrlEncode(), AppSecret, code); try { var contents = accessTokenUrl.DownloadUrl(); var authInfo = HttpUtility.ParseQueryString(contents); tokens.AccessTokenSecret = authInfo["access_token"]; service.SaveSession(session); session.OnAuthenticated(service, tokens, authInfo.ToDictionary()); //Haz access! return service.Redirect(session.ReferrerUrl.AddQueryParam("s", "1")); } catch (WebException we) { var statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { return service.Redirect(session.ReferrerUrl.AddQueryParam("f", "AccessTokenFailed")); } } //Shouldn't get here return service.Redirect(session.ReferrerUrl.AddQueryParam("f", "Unknown")); }
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 void imageWindow_Loaded(object sender, RoutedEventArgs e) { mainImage.Width = scrollViewer.ActualWidth; mainImage.Height = scrollViewer.ActualHeight; if (isDM == false || clientDM == null) { return; } if (clientDM.entities.media.Count == 0) { return; } if (clientDM.entities.media[0].type != "photo") { return; } PacketImage parameter = new PacketImage(clientDM.entities.media[0].media_url_https); WebRequest req = (HttpWebRequest)WebRequest.Create(parameter.MethodGetUrl()); req.Headers.Add("Authorization", OAuth.GetInstence().GetHeader(parameter)); req.BeginGetResponse(new AsyncCallback(AsyncLoadBitmap), req); }
internal async Task UpdateAccount() { if (OAuth.IsAuthenticatedForAnything()) { await OAuth.UpdateAccountData(); var token = Account.UploadToken; if (string.IsNullOrEmpty(token) || Account.TokenStatus == TokenStatus.Unknown || (!OAuth.AccountData?.UploadTokens.Contains(token) ?? false)) { await Api.UpdateTokenStatus(); } token = Account.UploadToken; if (Account.TokenStatus == TokenStatus.Unclaimed && !string.IsNullOrEmpty(token)) { await OAuth.ClaimUploadToken(token); } } else { await Api.UpdateTokenStatus(); } }
private void btnLink_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtAppKey.Text.Trim())) { Utility.ShowError("App Key 不能为空!"); return; } if (String.IsNullOrEmpty(txtAppSecret.Text.Trim())) { Utility.ShowError("App Secret 不能为空!"); return; } this.AppKey = txtAppKey.Text.Trim(); this.AppSecret = txtAppSecret.Text.Trim(); String callBackUrl = "urn:ietf:wg:oauth:2.0:oob"; oauth = new OAuth(this.AppKey, this.AppSecret, callBackUrl); oauth.AuthorizeUrl = AppContext.AuthorizeUrl; oauth.AccessTokenUrl = AppContext.AccessTokenUrl; Utility.Run(oauth.GetAuthorizationUrl(), null); Console.WriteLine("打开授权网页!"); }
public void Connect(string key, string secret) { var session = OAuth.Authorize(key, secret); var startInfo = new ProcessStartInfo(session.AuthorizeUri.AbsoluteUri) { UseShellExecute = true }; Process.Start(startInfo); Console.Write("Enter PIN code:"); var pin = Console.ReadLine(); try { var tokens = session.GetTokens(pin); var parameters = new Dictionary <string, object> { { "track", _settings.Keywords }, { "tweet_mode", TweetMode.Extended } }; var stream = tokens.Streaming .FilterAsObservable(parameters); Console.WriteLine("Waiting for tweets..."); _receiver = new TweetReceiver(_settings.ColoredTweets); _receiver.NewTweet += OnNewTweetReceived; _subscription = stream.Subscribe(_receiver); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static void TestAccount() { string[] acc = File.ReadAllLines("1111.txt"); foreach (var st in acc) { string[] tmp = st.Split(','); string username = tmp[0], password = tmp[1]; OAuth o = new OAuth(DefaultSettings.AppKey, DefaultSettings.AppSecret, String.Empty); o.ClientLogin(username, password); Client client = new Client(o); try { var s = client.API.Entity.Friendships.Create("1266321801"); Console.WriteLine(username + " " + s.Name); File.AppendAllText("accountResult.txt", username + " " + password + '\n'); } catch (WeiboException ex) { Console.WriteLine(username + " " + ex.ErrorCode + " " + ex.ErrorMessage); } Thread.Sleep(10000); } }
public void Sign(HttpRequestMessage request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } string payload = null; var httpContent = request.Content; if (httpContent != null) { // Read the body var bodyTask = httpContent.ReadAsStringAsync(); bodyTask.Wait(); payload = bodyTask.Result; } // Generate the header and add it to the request var methodString = request.Method.ToString(); var header = OAuth.GetAuthorizationHeader(request.RequestUri.AbsoluteUri, methodString, payload, Encoding, ConsumerKey, SigningKey); request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", header.Replace("OAuth", string.Empty)); }
private void Submit_Click_1(object sender, EventArgs e) { if (PhotoFile.Length == 0) { MessageBox.Show("Select Photo"); return; } try { var prms = new Dictionary <string, object>(); prms.Add("type", "photo"); prms.Add("caption", caption.Text); prms.Add("data[0]", System.IO.File.ReadAllBytes(PhotoFile)); var postUrl = string.Format("http://api.tumblr.com/v2/blog/{0}.tumblr.com/post", blogName.Text); photoResult.Text = OAuth.OAuthData(postUrl, "POST", LoginDetails.Key, LoginDetails.Value, prms); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static async void MyFeed() { try { if (_user == null) { var authInfo = new OAuth(_config); var response = await authInfo.RequestToken(Code); Access = response.AccessToken; _user = new Users(_config, response); } var media = await _user.RecentSelf(); Images.Clear(); Parallel.ForEach(media.Data, (item) => { Images.Add(item); }); } catch { await _metroWindow.ShowMessageAsync("Instagram", "Nie zalogowano"); } }
private async void OnOpenBrowserAuthAsync(object sender, RoutedEventArgs e) { var progdiag = await this.ShowProgressAsync("読み込み中...", "認証の準備をしています。しばらくお待ちください。"); try { await Task.Run(() => { session = OAuth.Authorize(Tsumugi.APIKey.CONSUMER_KEY, Tsumugi.APIKey.CONSUMER_SECRET); System.Diagnostics.Process.Start(session.AuthorizeUri.AbsoluteUri); }); WindowTab.SelectedIndex = 1; } catch (Exception ex) { await this.ShowMessageAsync("エラー", "何らかのエラーで認証を開始することが出来ませんでした。\n\n" + ex.Message + "\n" + ex.StackTrace); } finally { await progdiag.CloseAsync(); } }
public string AuthProc(HttpContext context) { string returnUrl = context.Request["return_url"]; string code = context.Request["code"]; //string redirectUrl1 =returnUrl+ (returnUrl.Contains("?") ? "&" : "?") + "open_id=12344"; //context.Response.Redirect(redirectUrl1); //return ""; OAuthAccessTokenResult result = OAuth.GetAccessToken(Variables.AppId, Variables.AppSecret, code); if (result.errcode != ReturnCode.请求成功) { return("错误" + result.errmsg); } string redirectUrl = returnUrl + (returnUrl.Contains("?") ? "&" : "?") + "open_id=" + result.openid; context.Response.Redirect(redirectUrl); return(""); }
/// <summary> /// 認証ボタンのクリックイベント /// </summary> private void AuthenticateButton_Click(object sender, EventArgs e) { // 入力チェック if (PINCodeTextBox.Text.Length == 0) { MessageBox.Show("PINコードが未入力です。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 認証 try { this.SecondGroupBox.Enabled = false; Tokens token = OAuth.GetTokens(this.Session, this.PINCodeTextBox.Text); ResultForm f = new ResultForm(token); f.Left = this.Left + (this.Width - f.Width) / 2; f.Top = this.Top + (this.Height - f.Height) / 2; f.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Override application start for implementing the oAuth /// set symmetric key for authentication token should be > 32 chars /// </summary> /// <param name="app"></param> /// <param name="ctx"></param> protected override void ApplicationStarted(UmbracoApplicationBase app, ApplicationContext ctx) { //OAuth implementation for get the authentication token OAuth.ConfigureEndpoint("/oauth/token", new OAuthOptions { UserService = new UmbracoUsersOAuthUserService(), SymmetricKey = "856FECBA3B06519C8DDDBC80BB080553", AccessTokenLifeTime = 20, // Minutes AllowInsecureHttp = true // During development only }); //OAuth.ConfigureEndpoint("realm", "/oauth/token", new OAuthOptions //{ // UserService = new UmbracoMembersOAuthUserService(), // SymmetricKey = "856FECBA3B06519C8DDDBC80BB080553", // AccessTokenLifeTime = 20, // Minutes // ClientStore = new UmbracoDbOAuthClientStore(), // RefreshTokenStore = new UmbracoDbOAuthRefreshTokenStore(), // RefreshTokenLifeTime = 1440, // Minutes (1 day) // AllowedOrigin = "*", // AllowInsecureHttp = true // During development only //}); }
//public FileSystemInfo CreateFolder(string root, string path) //{ // var uri = new Uri(new Uri(DropboxRestApi.BaseUri), // String.Format("fileops/create_folder?root={0}&path={1}", // root, UpperCaseUrlEncode(path))); // var json = GetResponse(uri); // return ParseJson<FileSystemInfo>(json); //} public DropboxFile DownloadFile(string root, string path) { var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer), String.Format("files?root={0}&path={1}", root, UpperCaseUrlEncode(path))); var oauth = new OAuth(); var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken); var request = (HttpWebRequest)WebRequest.Create(requestUri); request.Method = WebRequestMethods.Http.Get; var response = request.GetResponse(); var metadata = response.Headers["x-dropbox-metadata"]; //var file = ParseJson<FileSystemInfo>(metadata); Hashtable o = (Hashtable)Nikse.Json.JSON.JsonDecode(metadata); DropboxFile file = new DropboxFile(); file.Bytes = Convert.ToInt64(o["bytes"]); file.Path = o["path"].ToString().TrimStart('/').Trim(); file.IsDirectory = Convert.ToBoolean(o["is_dir"]); using (Stream responseStream = response.GetResponseStream()) using (MemoryStream memoryStream = new MemoryStream()) { byte[] buffer = new byte[1024]; int bytesRead; do { bytesRead = responseStream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); file.Data = memoryStream.ToArray(); } return(file); }
[Route("api/forge/callback/oauth")] // see Web.Config FORGE_CALLBACK_URL variable public async Task <HttpResponseMessage> OAuthCallback(string code) { ThreeLeggedApi oauth = new ThreeLeggedApi(); dynamic bearer = await oauth.GettokenAsync(ConfigVariables.FORGE_CLIENT_ID, ConfigVariables.FORGE_CLIENT_SECRET, oAuthConstants.AUTHORIZATION_CODE, code, ConfigVariables.FORGE_CALLBACK_URL); OAuth auth = JsonConvert.DeserializeObject <OAuth>(bearer.ToString()); // You can store the oauth Access Token and Refresh Token on your own authentication approach // The Refresh Token can be used later to get a new Access Token // For this basic sample, let's sent a Cooke to the end-user with the Access Token that only give // access to his/her own data, so no security breach (assuming a HTTPS connection), but there is a // accountability concern here (as the end-user will use this token to perform operation on the app behalf) HttpResponseMessage res = Request.CreateResponse(System.Net.HttpStatusCode.Moved /* rorce redirect */); CookieHeaderValue cookie = new CookieHeaderValue(ConfigVariables.FORGE_OAUTH, auth.AccessToken); cookie.Expires = auth.ExpiresAt; cookie.Path = "/"; res.Headers.AddCookies(new CookieHeaderValue[] { cookie }); res.Headers.Location = new Uri("/", UriKind.Relative); // back to / (root, default) return(res); }
public static string GetNavOpenId() { string code = HttpContext.Current.Request["code"]; string from = HttpContext.Current.Request["from"]; if (code != null && from == null) { var accessToken = OAuth.GetAccessToken(Wx.appId, Wx.appSecret, code); return(accessToken.openid); } else { string url = "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.FilePath; url += "?s=" + HttpContext.Current.Request["s"]; if (from != null) { url += "&f=" + from; } url = OAuth.GetAuthorizeUrl(Wx.appId, url, "a", OAuthScope.snsapi_base); HttpContext.Current.Response.Redirect(url, true); return(null); } }
/// <summary> /// Initial set up for the application. We read the config file and create the instance of Oauth and addressbook object. /// If it's post back from getting Auth code then perform operations. /// </summary> protected void Page_Load(object sender, EventArgs e) { ReadConfigFile(); oauth = new OAuth(endPoint, scope, apiKey, secretKey, authorizeRedirectUri, refreshTokenExpiresIn, bypassSSL); this.serializer = new JavaScriptSerializer(); if (Session["cs_rest_AccessToken"] != null && this.addressbook == null) { this.addressbook = new AddressBook(this.endPoint, Session["cs_rest_AccessToken"].ToString()); } if ((string)Session["cs_rest_appState"] == "GetToken" && Request["Code"] != null) { this.oauth.authCode = Request["code"].ToString(); if (oauth.GetAccessToken(OAuth.AccessTokenType.Authorization_Code) == true) { StoreAccessTokenToSession(oauth.access_token_json); this.addressbook = new AddressBook(this.endPoint, this.accessToken); Operation operation = (Operation)Session["cs_rest_ServiceRequest"]; switch (operation) { case Operation.CreateContactOperation: if (!addressbook.createContact(Session["JSONstring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.create_contact = new Success(); this.create_contact.location = this.addressbook.location; } break; case Operation.UpdateContactOperation: if (!addressbook.updateContact(Session["contactid"].ToString(), Session["JSONstring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.success_contact = new Success(); this.success_contact.last_modified = this.addressbook.last_mod; } break; case Operation.DeleteContactOperation: if (!addressbook.deleteContact(Session["contactid"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.success_contact = new Success(); this.success_contact.last_modified = this.addressbook.last_mod; } break; case Operation.GetContactsOperation: if (!addressbook.getContacts(Session["querystring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { try { this.qContactResult = serializer.Deserialize<QuickContactJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.contact_error = ex.Message; } } break; case Operation.UpdateMyInfoOperation: if (!addressbook.updateMyInfo(Session["JSONstring"].ToString())) { this.myinfo_error = this.addressbook.errorResponse; } else { this.update_myinfo = new Success(); this.update_myinfo.last_modified = this.addressbook.last_mod; } break; case Operation.GetMyInfoOperation: if (!addressbook.getMyInfo()) { this.myinfo_error = this.addressbook.errorResponse; } else { try { this.myInfoResult = serializer.Deserialize<ContactJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.myinfo_error = ex.Message; } } break; case Operation.CreateGroupOperation: if (!addressbook.createGroup(Session["JSONstring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.create_group = new Success(); this.create_group.location = this.addressbook.location; } break; case Operation.UpdateGroupOperation: if (!addressbook.updateGroup(Session["groupid"].ToString(), Session["JSONstring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.success_group = new Success(); this.success_group.last_modified = this.addressbook.last_mod; } break; case Operation.DeleteGroupOperation: if (!addressbook.deleteGroup(Session["groupid"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.success_group = new Success(); this.success_group.last_modified = this.addressbook.last_mod; } break; case Operation.GetGroupsOperation: if (!addressbook.getGroups(Session["querystring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { try { this.groupResult = serializer.Deserialize<GroupJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.group_error = ex.Message; } } break; case Operation.GetGroupContactsOperation: if (!addressbook.getGroupContacts(Session["groupid"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { try { this.contactIdResult = serializer.Deserialize<ContactIdJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.manage_groups_error = ex.Message; } } break; case Operation.AddContctsToGroupOperation: if(!addressbook.addContactToGroup(Session["groupid"].ToString(), Session["contactids"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { this.manage_groups = new Success(); this.manage_groups.last_modified = this.addressbook.last_mod; } break; case Operation.RemoveContactsFromGroupOperation: if (!addressbook.removeContactsFromGroup(Session["groupid"].ToString(), Session["contactids"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { this.manage_groups = new Success(); this.manage_groups.last_modified = this.addressbook.last_mod; } break; case Operation.GetContactGroupsOperation: if (addressbook.getContactGroups(Session["contactid"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { try { this.contactGroupResult = serializer.Deserialize<GroupJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.manage_groups_error = ex.Message; } } break; } ResetRequestSessionVariables(operation); } else { if (oauth.getAuthCodeError != null) { this.oauth_error = "GetAuthCodeError: " + oauth.getAuthCodeError; } if (oauth.GetAccessTokenError != null) { this.oauth_error = "GetAccessTokenError: " + oauth.GetAccessTokenError; } this.ResetTokenSessionVariables(); return; } } }
public async void SetupLogin() { session = await OAuth.AuthorizeAsync(API_KEY, API_SECRET); Device.OpenUri(new Uri(session.AuthorizeUri.AbsoluteUri)); }
/// <summary> /// 根据授权对象实例化 /// </summary> /// <param name="oauth"></param> public Trends(OAuth oauth) : base(oauth) { }
/// <summary> /// This region is oauth related helper function /// </summary> #region oauth helper /// <summary> /// This function is for reading session and storing to token variables /// </summary> private bool ReadTokenSessionVariables(OAuth obj) { if (Session["cs_rest_AccessToken"] != null) { obj.accessToken = Session["cs_rest_AccessToken"].ToString(); } else { obj.accessToken = null; } if (Session["cs_rest_AccessTokenExpirtyTime"] != null) { obj.accessTokenExpiryTime = Session["cs_rest_AccessTokenExpirtyTime"].ToString(); } else { obj.accessTokenExpiryTime = null; } if (Session["cs_rest_RefreshToken"] != null) { obj.refreshToken = Session["cs_rest_RefreshToken"].ToString(); } else { obj.refreshToken = null; } if (Session["cs_rest_RefreshTokenExpiryTime"] != null) { obj.refreshTokenExpiryTime = Session["cs_rest_RefreshTokenExpiryTime"].ToString(); } else { obj.refreshTokenExpiryTime = null; } if ((obj.accessToken == null) || (obj.accessTokenExpiryTime == null) || (obj.refreshToken == null) || (obj.refreshTokenExpiryTime == null)) { return false; } return true; }
public SauceNao(String url) { //The url to request the source from String requesturl = "http://saucenao.com/search.php"; //Dicktionary for our parameters Dictionary <string, object> dick = new Dictionary <string, object>(); //Choosing a database? idk, but this is what Image Search Options extension's url dick.Add("db", "999"); //Request image url dick.Add("url", url); //Send the query String response; try { response = OAuth.PostData(requesturl, "GET", "", dick); } catch (Exception sEx) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.NetworkError); } //Parse the response int resultStartIndex; int startIndex; int len; //Look for the top result if ((resultStartIndex = response.IndexOf("<div class=\"result\">")) == -1) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.SauceNotFound); } //Find the info box for the top result if (((resultStartIndex = response.IndexOf("<div class=\"resultcontent\">", resultStartIndex)) == -1)) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.ParseFailed); } //Parse and find the title if ((startIndex = response.IndexOf("<div class=\"resulttitle\">", resultStartIndex)) == -1) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.ParseFailed); } startIndex += 33; //Find the length of the title len = response.IndexOf("</strong>", startIndex) - startIndex; if (len <= 0) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.ParseFailed); } //Extract the title Title = response.Substring(startIndex, len); //Find the link if (((startIndex = response.IndexOf("<a href=\"", resultStartIndex)) == -1)) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.ParseFailed); } startIndex += 9; //Find the length of the link len = response.IndexOf("\"", startIndex) - startIndex; if (len <= 0) { throw new SauceLookupFailedException(SauceLookupFailedException.errCode.ParseFailed); } //Extract the link SauceURL = response.Substring(startIndex, len); }
private async Task <ActionResult> SelectTarget(string courseId) { var returnUrl = Request.Url?.PathAndQuery ?? ""; var oauthAuthorizationUrl = OAuth.GetAuthorizationUrl(stepikClientId, GetStepikOAuthRedirectUri(), OAuth.EncryptState(returnUrl)); var client = await GetAuthenticatedStepikApiClient(); if (client == null) { return(Redirect(oauthAuthorizationUrl)); } var course = courseManager.GetCourse(courseId); var myCourses = await client.GetMyCourses(); return(View("SelectTarget", new SelectTargetModel { UlearnCourse = course, StepikCourses = myCourses.OrderBy(c => c.Id).ToList(), })); }
private Task <OAuthCode> GetAuthenticationCode(string clientId, CancellationToken cancellation) { return(OAuth.GetCode("Google Drive", $"https://accounts.google.com/o/oauth2/v2/auth?scope={Uri.EscapeDataString(Scopes.JoinToString(' '))}&" + $"response_type=code&client_id={Uri.EscapeDataString(clientId)}", RedirectUrl, cancellation: cancellation)); }
public static void User(CancellationToken cancelationToken) { Task.Run(() => { while (cancelationToken.IsCancellationRequested == false) { var delay = Task.Delay(30*1000, cancelationToken); delay.Wait(cancelationToken); if (delay.IsCanceled || delay.IsFaulted) break; Trace.TraceInformation("{ Start Twitter User Stream }"); const string url = "https://userstream.twitter.com/1.1/user.json"; var oauth = new OAuth(); var nonce = OAuth.Nonce(); var timestamp = OAuth.TimeStamp(); var signature = OAuth.Signature("GET", url, nonce, timestamp, oauth.AccessToken, oauth.AccessTokenSecret, null); var authorizeHeader = OAuth.AuthorizationHeader(nonce, timestamp, oauth.AccessToken, signature); var request = WebRequestWrapper.Create(new Uri(url)); request.Headers.Add("Authorization", authorizeHeader); try { using (var response = request.GetResponse()) using (var stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { stream.BaseStream.ReadTimeout = 60*1000; while (true) { var json = stream.ReadLine(); if (json == null) { Trace.TraceInformation("{ null }"); break; } if (cancelationToken.IsCancellationRequested) break; Trace.TraceInformation(string.IsNullOrWhiteSpace(json) ? "{ Blankline }" : json); var serializer = new JavaScriptSerializer(); var reply = serializer.Deserialize<Dictionary<string, object>>(json); if (reply != null && reply.ContainsKey("user")) { Trace.TraceInformation("{ tweet identified }"); var statuses = Status.ParseJson("[" + json + "]"); Application.Current.Dispatcher.InvokeAsync (() => UpdateStatusHomeTimelineCommand.Command.Execute(statuses, Application.Current.MainWindow)); } } } } catch (WebException ex) { Trace.TraceError(ex.ToString()); } catch (ArgumentNullException ex) { Trace.TraceError(ex.ToString()); } catch (ArgumentException ex) { Trace.TraceError(ex.ToString()); } catch (InvalidOperationException ex) { Trace.TraceError(ex.ToString()); } catch (IOException ex) { Trace.TraceError(ex.ToString()); } } Trace.TraceInformation("{ Stream task ends }"); }, cancelationToken); }
public void Session_Start(object sender, EventArgs e) { Session["Token"] = OAuth.Authenticate("apitest", "12345678"); }
public SavedSearches(OAuth oauth) : base(oauth) { }
public Photos(OAuth oauth) : base(oauth) { }
public async Task <ActionResult> UpdateOptions(string courseId, int stepikCourseId) { var course = courseManager.GetCourse(courseId); var slides = course.Slides; var slidesXmls = slides.ToDictionary(s => s.Id, s => stepikRepo.GetSlideXmlIndicatedChanges(s)); /* TODO (andgein): following 5 lines are copy-paste*/ var returnUrl = Request.Url?.PathAndQuery ?? ""; var oauthAuthorizationUrl = OAuth.GetAuthorizationUrl(stepikClientId, GetStepikOAuthRedirectUri(), OAuth.EncryptState(returnUrl)); var client = await GetAuthenticatedStepikApiClient(); if (client == null) { return(Redirect(oauthAuthorizationUrl)); } var stepikCourse = await client.GetCourse(stepikCourseId); var stepikSections = new Dictionary <int, StepikApiSection>(); // TODO (andgein): download multiple sections in one request foreach (var sectionId in stepikCourse.SectionsIds) { stepikSections[sectionId] = await client.GetSection(sectionId); } var stepikUnitsIds = stepikSections.SelectMany(kvp => kvp.Value.UnitsIds); var stepikUnits = new Dictionary <int, StepikApiUnit>(); foreach (var unitId in stepikUnitsIds) { stepikUnits[unitId] = await client.GetUnit(unitId); } var stepikLessonsIds = stepikUnits.Select(kvp => kvp.Value.LessonId); var stepikLessons = new Dictionary <int, StepikApiLesson>(); foreach (var lessonId in stepikLessonsIds) { stepikLessons[lessonId] = await client.GetLesson(lessonId); } var slideStepMaps = stepikRepo.GetStepsExportedFromCourse(courseId, stepikCourseId); return(View(new UpdateOptionsModel { Course = course, DefaultXQueueName = defaultXQueueName, SlidesXmls = slidesXmls, StepikCourse = stepikCourse, StepikSections = stepikSections, StepikUnits = stepikUnits, StepikLessons = stepikLessons, SlideStepMaps = slideStepMaps, })); }
public Search(OAuth oauth) : base(oauth) { }
private void Button_Click(object sender, RoutedEventArgs e) { vm.Session = OAuth.Authorize(Properties.Resources.ConsumerKey, Properties.Resources.ConsumerSecret); System.Diagnostics.Process.Start(vm.Session.AuthorizeUri.AbsoluteUri); }
protected void Page_Load(object sender, EventArgs e) { // Enter the value from the 'App Key' field obtained at developer.att.com in your // app account. string clientId = ""; // Enter the value from the 'App Secret' field obtained at developer.att.com // in your app account. string secretKey = ""; // Set the fully-qualified domain name to: https://api.att.com string fqdn = "https://api.att.com"; //Set the scope to AAB string scope = "Payment"; // Create the service for requesting an OAuth access token. var oauth = new OAuth(fqdn, clientId, secretKey, scope); // Get the OAuth access token using the Client Credentials. if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials)) { // Get access token OAuthToken at = new OAuthToken(); string accessToken = at.getAccessToken(oauth.accessTokenJson); // Create the service for making the method request. var payment = new Payment(fqdn, accessToken); if (string.IsNullOrEmpty((string)Session["NewTransaction"])) { /// <summary> /// Create new transaction /// </summary> /// <param name="apiKey">apiKey</param> /// <param name="secretKey">secretKey</param> /// <param name="description">description</param> /// <param name="amount">amount</param> /// <param name="category">category</param> /// <param name="channel">channel</param> /// <param name="merchantRedirectURI">merchantRedirectURI</param> /// <param name="merchantProductId">merchantProductId</param> /// <param name="merchantTransactionId">merchantTransactionId</param> var redirectUrl = payment.createNewTransactionRedirectUrl( clientId, secretKey, "Sample Product", 0.01, 2, "MOBILE_WEB", "http://localhost/PaymentNewTransaction.aspx", "whateverprod", merchantTransactionId); Session["NewTransaction"] = "created"; Response.Redirect(redirectUrl); } if (Request.QueryString["success"] != null && Request.QueryString["success"].ToString() == "false") { errorCreateNew = new Dictionary<string, string>(); foreach (String key in Request.QueryString.AllKeys) { errorCreateNew.Add(key, Request.QueryString[key]); } throw new Exception(Request.QueryString["faultDescription"]); } if ((Request["TransactionAuthCode"] != null)) { TransactionAuthCode = Request.QueryString["TransactionAuthCode"].ToString(); } /// <summary> /// Call getTransactionStatus operation return getTransactionStatus object /// </summary> /// <param name="idType">idType</param> /// <param name="id">id</param> TransactionStatusResponseObj.RootObject getTransactionStatus = payment.getTransactionStatus("TransactionAuthCode", TransactionAuthCode); //Get Payment notification //Stream inputstream = Request.InputStream; //int streamLength = Convert.ToInt32(inputstream.Length); //byte[] stringArray = new byte[streamLength]; //inputstream.Read(stringArray, 0, streamLength); //string xmlString = System.Text.Encoding.UTF8.GetString(stringArray); string xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ownershipEvent type=\"revoke\" timestamp=\"2014-05-02T06:12:33+00:00\" effective=\"2014-05-02T06:12:18+00:00\"><networkOperatorId>cingular</networkOperatorId><ownerIdentifier>N_NBI_PNW_1369816836000116729061</ownerIdentifier><purchaseDate>2014-05-02T06:12:05+00:00</purchaseDate><productIdentifier>Onetime_Cat1</productIdentifier><purchaseActivityIdentifier>Z89EZXmzjy2yu6s7wFY88cZM9lgztD6PRyo8</purchaseActivityIdentifier><instanceIdentifier>ada820f1-ce48-499b-8b46-eac60ef28a2a-CTASTransactionP1</instanceIdentifier><minIdentifier>4256586023</minIdentifier><sequenceNumber>178</sequenceNumber><reasonCode>1760</reasonCode><reasonMessage>CP Requested Refund</reasonMessage><vendorPurchaseIdentifier>M789819033</vendorPurchaseIdentifier></ownershipEvent>"; XmlSerializer deserializer = new XmlSerializer(typeof(ownershipEvent)); TextReader textReader = new StringReader(xmlString); ownershipEvent notificationObj; notificationObj = (ownershipEvent)deserializer.Deserialize(textReader); textReader.Close(); //create refund transaction object RefundTransactionRequestObj.RootObject refund = new RefundTransactionRequestObj.RootObject() { TransactionOperationStatus = "Refunded", RefundReasonCode = 1, RefundReasonText = "Customer was not happy" }; var serializer = new JavaScriptSerializer(); var refundJSON = serializer.Serialize(refund); RefundTransactionResponseObj.RootObject refundResponse = payment.RefundTransaction(refundJSON, getTransactionStatus.TransactionId); } }
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 DirectMessage(OAuth oauth) : base(oauth) { }
private Task <OAuthCode> GetAuthenticationCode(string clientId, CancellationToken cancellation) { return(OAuth.GetCode("OneDrive", $"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?" + $"scope={Uri.EscapeDataString(Scopes.JoinToString(' '))}&" + $"response_type=code&client_id={Uri.EscapeDataString(clientId)}", RedirectUrl, cancellation: cancellation)); }
/// <summary> /// Saves the OAuth access token. /// </summary> /// <param name="token">The OAuth access token returned from the server.</param> private void SaveAuthToken(TraktOAuthAccessToken token) { OAuth auth = schedulerDb.OAuth.FirstOrDefault(); if (auth == null) { auth = new OAuth(); schedulerDb.OAuth.Add(auth); } auth.AuthToken = token.AccessToken; auth.RefreshToken = token.RefreshToken; auth.Expires = token.AccessTokenExpires; auth.Scope = token.AccessScope; schedulerDb.SaveChanges(); AuthenticationNeeded = !token.IsValid; }
public async Task <ActionResult> UpdateCourse(string courseId, int stepikCourseId, string updateSlidesIds, string xQueueName, string uploadVideo) { var exportSlideAfterKey = "stepik__course-update__export-slide-after__"; var returnUrl = Url.Action("UpdateOptions", "Stepik", new { courseId = courseId, stepikCourseId = stepikCourseId }); /* TODO (andgein): following 4 lines are copy-paste*/ var oauthAuthorizationUrl = OAuth.GetAuthorizationUrl(stepikClientId, GetStepikOAuthRedirectUri(), OAuth.EncryptState(returnUrl)); var client = await GetAuthenticatedStepikApiClient(); if (client == null) { return(Redirect(oauthAuthorizationUrl)); } var exporter = new CourseExporter(client.AccessToken); var course = courseManager.GetCourse(courseId); var updateSlidesGuids = ConvertStringToGuidList(updateSlidesIds).ToList(); var slidesUpdateOptions = new List <SlideUpdateOptions>(); foreach (var slideId in updateSlidesGuids) { var stepsIdsForSlide = stepikRepo.GetStepsExportedFromSlide(courseId, stepikCourseId, slideId) .Select(m => m.StepId) .ToList(); var insertSlideAfterStepId = int.Parse(Request.Form[exportSlideAfterKey + slideId.GetNormalizedGuid()]); slidesUpdateOptions.Add(new SlideUpdateOptions(slideId, insertSlideAfterStepId, stepsIdsForSlide)); } var updateOptions = new CourseUpdateOptions( stepikCourseId, xQueueName, slidesUpdateOptions, new List <Guid>() ) { VideoUploadOptions = (UploadVideoToStepikOption)Enum.Parse(typeof(UploadVideoToStepikOption), uploadVideo) }; var thread = new Thread(async() => await DoUpdateCourse(exporter, course, updateOptions)); thread.Start(); return(View("UpdateStarted", course)); }
protected void Page_Load(object sender, EventArgs e) { // Enter the value from the 'App Key' field obtained at developer.att.com in your // app account. string clientId = ""; // Enter the value from the 'App Secret' field obtained at developer.att.com // in your app account. string secretKey = ""; // Set the fully-qualified domain name to: https://api.att.com string fqdn = "https://api.att.com"; //Set the scope to MMS string scope = "MMS"; //Create the service for requesting an OAuth access token. var oauth = new OAuth(fqdn, clientId, secretKey, scope); //Get the OAuth access token using client Credential method. if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials)) { // Get access token OAuthToken at = new OAuthToken(); string accessToken = at.getAccessToken(oauth.accessTokenJson); // Create the service for making the method request. var mms = new MMS(fqdn, accessToken); // Set params: string mmsAddress = Server.UrlEncode("tel:10000000000") + "&"; //e.g.tel:1234567890 string mmsMessage = Server.UrlEncode("msg txt context"); string mmsFile = Server.MapPath("~/")+"attachments/att.jpg"; //Attachement path string mmsContentType = "image/jpeg"; string messageId = ""; try { // Make an Make a method call to the MMS API. // Method takes: // param 1: string mmsAddress (phone number(s)) // param 2: message text content // param 3: file path // param 4: multipart content type OutboundMessageResponseObj.RootObject SendMMSResponseObj = mms.sendMMS(mmsAddress, mmsMessage, mmsFile, mmsContentType); messageId = SendMMSResponseObj.outboundMessageResponse.messageId; } catch (Exception respex) { string error = respex.StackTrace; } try { // Make an Make a method call to the MMS API. // Method takes: // param 1: string message id DeliveryInfoObj.RootObject getStatusResponseObj = mms.getMMSDeliveryStatus(messageId); } catch (Exception respex) { string error = respex.StackTrace; } } }
public async Task <ActionResult> InitialExport(string courseId, int stepikCourseId, string newLessonsSlidesIds, string xQueueName, string uploadVideo) { var returnUrl = Url.Action("InitialExportOptions", "Stepik", new { courseId = courseId, stepikCourseId = stepikCourseId }); /* TODO (andgein): following 4 lines are copy-paste*/ var oauthAuthorizationUrl = OAuth.GetAuthorizationUrl(stepikClientId, GetStepikOAuthRedirectUri(), OAuth.EncryptState(returnUrl)); var client = await GetAuthenticatedStepikApiClient(); if (client == null) { return(Redirect(oauthAuthorizationUrl)); } var exporter = new CourseExporter(client.AccessToken); var course = courseManager.GetCourse(courseId); var exportOptions = new CourseInitialExportOptions(stepikCourseId, xQueueName, ConvertStringToGuidList(newLessonsSlidesIds).ToList()) { VideoUploadOptions = (UploadVideoToStepikOption)Enum.Parse(typeof(UploadVideoToStepikOption), uploadVideo) }; var thread = new Thread(async() => await DoInitialExport(exporter, course, exportOptions)); thread.Start(); return(View("ExportStarted", course)); }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { if (HttpContext.Current.Session["QQ_user_id"] != null) { if (Session["QQ_script"] == null) { string appKey = Constant.app_key_QQ; string appSecret = Constant.app_secret_QQ; OAuth oauth = new OAuth(appKey, appSecret); //string name; oauth.Token = (string)Session["QQ_oauth_token"]; oauth.TokenSecret = (string)Session["QQ_oauth_token_secret"]; //Access Secret OpenTSDK.Tencent.API.User api = new OpenTSDK.Tencent.API.User(oauth); UserProfileData<UserProfile> data = api.GetProfile(); if (data != null) { string script = @"<script> var QQ_NickName='{0}'; var QQ_Head='{1}'; QQisLogin(); </script>"; if (data.Profile != null) { script = string.Format(script, data.Profile.NickName, data.Profile.Head); Session["QQ_script"] = script; ClientScript.RegisterStartupScript(this.Page.GetType(), "QQ", script); } } } else { ClientScript.RegisterStartupScript(this.Page.GetType(), "QQ", (string)Session["QQ_script"]); } } if (HttpContext.Current.Session["Sina_user_id"] != null) { if (Session["Sina_script"] == null) { var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST); httpRequest.Token = (string)Session["oauth_token"]; httpRequest.TokenSecret = (string)Session["oauth_token_secret"]; var url = "http://api.t.sina.com.cn/users/show.json?"; var r = httpRequest.Request(url, "id=" + (string)HttpContext.Current.Session["Sina_user_id"]); string script = @"<script> var sina={0}; SinaisLogin(); </script>"; script = string.Format(script, r); Session["Sina_script"] = script; ClientScript.RegisterStartupScript(this.Page.GetType(), "Sina", script); } else { ClientScript.RegisterStartupScript(this.Page.GetType(), "Sina", (string)Session["Sina_script"]); } } if (HttpContext.Current.Session["QQ_user_id"] != null && HttpContext.Current.Session["Sina_user_id"] != null) { if (Session["Common_script"] == null) { WebUtility.SaveRelation(); string script = @"<script> finish(); </script>"; Session["Common_script"] = script; ClientScript.RegisterStartupScript(this.Page.GetType(), "Finish", script); } else { ClientScript.RegisterStartupScript(this.Page.GetType(), "Finish", (string)Session["Common_script"]); } } } } catch (Exception ex) { log.Fatal("PageLoad:{0},{1}", ex.Message, ex.StackTrace); Response.Write("杯具,网页好像出错了,请点浏览器的刷新按钮 -_-!"); } }
/// <summary> /// 根据授权对象实例化 /// </summary> /// <param name="oauth"></param> public Timeline(OAuth oauth) : base(oauth) { }
/// <summary> /// 根据请求基本地址实例化对象 /// </summary> /// <param name="oauth">OAuth授权对象</param> protected RequestBase(OAuth oauth) { this.OAuth = oauth; this.ResponseDataFormat = Objects.ResponseDataFormat.XML; }
/// <summary> /// 根据请求基本地址实例化对象 /// </summary> /// <param name="oauth">OAuth授权对象</param> protected RequestBase(OAuth oauth) { this.OAuth = oauth; this.ResponseDataFormat = ResponseDataFormat.JSON; }
public Followers(OAuth oauth) : base(oauth) { }