linqtotwitter – 获取保存的凭据

我使用linqtotwitter库,在我的win表单应用程序中我可以对twitter进行api调用,但是当我关闭我的应用程序并重新打开时,我需要再次重复输入密码///

在twitter programm tweetdesc中它只需要输入一次针脚吗? 我如何在应用程序本身中做得好?

我读:

授权后,保存与该用户关联的凭据。 下次用户需要使用您的应用执行操作时,请获取已保存的凭据并将所有4个凭据加载到授权程序中。 当授权者拥有全部4个凭据时,它不再需要执行授权过程,您可以在不授权的情况下执行查询

但是这怎么办?

调用CompleteAuthorizeAsync后,您可以读取凭据,如下所示:

await pinAuth.CompleteAuthorizeAsync(PinTextBox.Text); SharedState.Authorizer = pinAuth; // This is how you access credentials after authorization. // The oauthToken and oauthTokenSecret do not expire. // You can use the userID to associate the credentials with the user. // You can save credentials any way you want - database, isolated storage, etc. - it's up to you. // You can retrieve and load all 4 credentials on subsequent queries to avoid the need to re-authorize. // When you've loaded all 4 credentials, LINQ to Twitter will let you make queries without re-authorizing. // var credentials = pinAuth.CredentialStore; string oauthToken = credentials.OAuthToken; string oauthTokenSecret = credentials.OAuthTokenSecret; string screenName = credentials.ScreenName; ulong userID = credentials.UserID; 

因此,您需要做的是有一种方法来存储用户信息。 为简单起见,我假设您正在使用数据库。 您的存储也可以是您选择的任何格式的文件。 假设您正在使用数据库,您应该有一个包含用户信息的表,您应该知道使用您的应用程序的用户是谁。 该用户在您的表中有一个ID,该表应包含oauthToken和oauthTokenSecret的字段。 您还可以为Twitter的UserID和ScreenName添加字段,但OAuth不需要它们。

请注意,上面的代码从授权器pinAuth获取对CredentialStore的引用。 在调用CompleteAuthorizeAsync之后会发生这种情况,因为在OAuth进程完成之前,凭据不可用。 通过引用凭据,请阅读OAuthToken和OAuthToken属性。 然后编写代码以将OAuthToken和OAuthTokenSecret凭据存储到与当前用户关联的数据库中。

现在您已为该用户存储凭据。

在后续查询中,请确保已使用所有四个凭据加载Authorizer:ConsumerKey,ConsumerSecret,OAuthToken和OAuthTokenSecret。 这是一个例子:

  string oauthToken = null; string oauthTokenSecret = null; // read OAuthToken and OAuthTokenSecret from the database table where you previously // stored OAuthToken and OAuthTokenSecret for this user. Put the OAuthToken and // OAuthTokenSecret into the variables named oauthToken and oauthTokenSecret above. pinAuth = new PinAuthorizer { // Get the ConsumerKey and ConsumerSecret for your app and load them here. CredentialStore = new InMemoryCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["consumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"], OAuthToken = oauthToken, OAuthTokenSecret = oauthTokenSecret }, // Note: GetPin isn't used here because we've broken the authorization // process into two parts: begin and complete GoToTwitterAuthorization = pageLink => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute)) }; if (oauthToken == null) await pinAuth.BeginAuthorizeAsync(); 

在实例化PinAuthorizer之前,请检查当前用户是否有OAuthToken和OAuthTokenSecret。 如果您这样做,则使用它们填充Authorizer的CredentialStore。 如果没有,请将OAuthToken和OAuthTokenSecret保留为null,以便LINQ to Twitter将通过OAuth流程获取令牌。 如果您确实拥有OAuthToken和OAuthTokenSecret并将它们分配给CredentialStore属性,那么LINQ to Twitter将不需要执行OAuth流程,您可以使用授权程序立即执行查询。