Tweeting on a user's behalf in asp.net - c#

I have been searching for the most current method for posting a tweet on behalf of a user in Webforms. Most of the information I've come across dates to around 2010 and involves Twitterizer, which is no longer supported by the Twitter API. My question is, is there any updated documentation or examples, tutorials on the subject?
I've created my app, have the consumer key and secret, but most of the code I'm coming across is in php. Any help would be appreciated.

Since you're using WebForms (via your reply in comments), here's an example of tweeting on another user's behalf with LINQ to Twitter. Other examples might show you how to add a signature to an authorization header, but you'll still have to manage the OAuth workflow. This should give you an idea of how that workflow can be managed in WebForms.
LINQ to Twitter uses different authorizers to manage the process of producing OAuth signatures, managing credentials, and supporting OAuth workflow. First, instantiate a WebAuthorizer, like this:
public partial class _Default : System.Web.UI.Page
{
private WebAuthorizer auth;
private TwitterContext twitterCtx;
protected void Page_Load(object sender, EventArgs e)
{
IOAuthCredentials credentials = new SessionStateCredentials();
if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
{
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
}
auth = new WebAuthorizer
{
Credentials = credentials,
PerformRedirect = authUrl => Response.Redirect(authUrl)
};
The WebAuthorizer only needs your ConsumerKey and ConsumerSecret, which can be saved in web.config. The authorization process is divided into two parts because you have to send the user to Twitter to authorize your app and then Twitter redirects the user back to your page to collect the other two tokens, which are oauth_token and access_token. That means you need logic to handle the callback from Twitter, which could look like this:
if (!Page.IsPostBack && Request.QueryString["oauth_token"] != null)
{
auth.CompleteAuthorization(Request.Url);
}
This goes after you instantiate WebAuthorizer and makes sure you're processing a Twitter callback before performing completion. After you call CompleteAuthorize, go into auth.Credentials and grab the new user credentials and save them for the logged in user. On subsequent queries, you can then load all 4 credentials into WebAuthorizer and LINQ to Twitter will work without requiring the user to authorize your application again.
After you have credentials, you can instantiate a TwitterContext, which gives you access to the Twitter API. Here's an example that does that and performs a query:
if (auth.IsAuthorized)
{
twitterCtx = new TwitterContext(auth);
var search =
(from srch in twitterCtx.Search
where srch.Type == SearchType.Search &&
srch.Query == "LINQ to Twitter"
select srch)
.SingleOrDefault();
TwitterListView.DataSource = search.Statuses;
TwitterListView.DataBind();
}
This code follows the call to auth.CompleteAuthorize to make sure all credentials are populated. The auth.IsAuthorized verifies that all 4 credentials are present.
That was the completion and instantiation of the TwitterContext part, but you'll first need to start the oauth process. Here's a button click handler that does that:
protected void authorizeTwitterButton_Click(object sender, EventArgs e)
{
auth.BeginAuthorization(Request.Url);
}
Just call BeginAuthorization, which executes the callback assigned to the PerformRedirect property of WebAuthorizer, sending the user to Twitter to authorize your app. As mentioned earlier, Twitter redirects the user back to your page and CompleteAuthorization executes to finish the authorization process. I typically put the OAuth logic on a separate page to simplify things.
Once the user authorizes your app, you can execute any query you want, such as the method below that tweets some text for the user:
protected void postUpdateButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
twitterCtx.UpdateStatus(updateBox.Text);
updateBox.Text = string.Empty;
}
Tip: the SessionStateCredentials stores credentials in session state. So, you want to make sure you're using state server, SQL server, but definitely not InProc.
There's documentation on the LINQ to Twitter site at CodePlex.com and a working demo in the LinqToTwitterWebFormsDemo in the downloadable source code.

Related

Logout from ADFS using c#

I created an asp.net webform application using ADFS. Sign in and sign out work perfectly using the default method that comes with the template.
Eg of signout button method that is included in the template
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
// Redirect to ~/Account/SignOut after signing out.
string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/Account/SignOut");
HttpContext.Current.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
WsFederationAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
}
I have set up a timer and upon reaching zero I tried using the above code to log the user out but it doesn't work.No error thrown.
Any suggestion how to perform logout here?
What worked for me is to upon timeout to call the click event of a hidden button which in turn causes the below code to run.
// Redirect to ~/Account/SignOut after signing out.
string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/Account/SignOut");
HttpContext.Current.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
WsFederationAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
ADFS is the server that is responsible for authenticating the user and for managing the user session. The website/form is just using this service. It makes sense that a site that uses this service cannot have full control over it. It would make more sense to me to log out the user from the ADFS server and have that server do the heavy lifting for you.
Note the ADFS server keeps a user logged in into ADFS server, and note that when a user requests access to a resource this manifests in an access_token. They are different things. Typically when signing somebody out with a product like identity server, in order to log out you’ll need to do two things:
Revoke the access token
Log out on the authentication server, (if
that is desired, one could argue that isn’t desirable)
Note the explicit difference between session and token. You’ll notice these concepts are also in ADFS. After a quick google search you’ll find the difference between WebSSOLifetime and TokenLifetime. I would suggest configuring those to invalidate the tokens and sessions, and thereby logging the user out after an x amount of minutes.
Hope this helps.
Have you tried the above code that you have posted directly without the timer? and did it work?
Also, Try implementing the below code and see if it works.
public void LogOut()
{
var module = FederatedAuthentication.WSFederationAuthenticationModule;
module.SignOut(false);
var request = new SignOutRequestMessage(new Uri(module.Issuer), module.Realm);
Response.Redirect(request.WriteQueryString());
}

NetSuite Service Login with SessionID (can not retrieve sessionID from current service) in C#

For the life of me I can no figure out where to get the SessionID out of the service so that I can use it in a future call to recreate the same session.
I am currently using the 2013_1_0 version of the wsdl in C#
When referencing the older documents SuiteTalkWebServicesPlatformGuide_2011.1.pdf on page 78 (Reusing Session IDs During Login) they talk about this.
Any Suggestions?
Here is my sample code for logging into NetSuite without using a previous SessionID...
// invoke the login operation
Passport passport = new Passport();
passport.account = _sNetSuiteAccount;
passport.email = _sNetSuiteUserName;
RecordRef role = new RecordRef();
role.externalId = _sNetSuiteRole;
passport.role = role;
passport.password = _sNetSuitePassword;
status = service.login(passport).status;
// Confirm login was a success
// Process response
if (status.isSuccess == true)
{
_bIsNetSuiteAuthenticated = true;
}
Additionally I have yet to find sample code for using the SessionID to re-create the service. So any suggestion there would also be welcomed.
Thank you!
In talking with NetSuite what I desire to do is impossible and the SessionID is stored as a private variable and handled by the .NET code.
I am currently seeking an alternative to a persistent session so when code base is called multiple times that the user will not need to be prompted for each iteration to enter their NetSuite cridentials. I will update this answer as more details come available on this.

LinqToTwitter Error - The remote certificate is invalid according to the validation procedure

I've found several different questions about this error, but none of them seem to outline my scenario.
I am creating a website that pulls in tweets from our company's Twitter account, and displaying them on a social wall. I am using C# asp.NET webforms. The C# code uses a Linqtotwitter library to handle the authentication and the "tweet pulling." It grabs the tweets and dumps them onto an aspx file as a big long string of json. We then have a jquery script that reads through the json and displays the tweets on the page nice and pretty like.
The code currently works perfect on my dev box. But when I push the code up to production I get this .NET error:
The remote certificate is invalid according to the validation procedure
I'll provide my code in a bit here, but first let me give you a little background. I have no idea if this information would be relevant or not, but who knows. This website is actually part of a larger project to fit several tiny one page microsites that we get from marketing onto one server to reduce the overhead they cause. These microsites can all have a different host name, but they point to the same IP address. An httpmodule lives on that server, and intercepts all requests coming in, and redirects them to an appropriate sub folder depending on the host name.
From the research that I've done, it seems that SSL is tied into this error quite a bit. I'm still pretty new to the IT world, and I'm learning more about SSL as this troubleshooting goes on. The server these microsites live on does have a few SSL certificates on it, and one of the microsites uses SSL, but not the website I'm currently working on. But since they both share the same IP address in that sense they kind of ARE the same website.
This is the C# LinqtoTwitter code:
private SingleUserAuthorizer auth;
private TwitterContext twitterCtx;
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
auth = new SingleUserAuthorizer
{
Credentials = new SingleUserInMemoryCredentials
{
ConsumerKey =
ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret =
ConfigurationManager.AppSettings["twitterConsumerSecret"],
TwitterAccessToken =
ConfigurationManager.AppSettings["twitterAccessToken"],
TwitterAccessTokenSecret =
ConfigurationManager.AppSettings["twitterAccessTokenSecret"]
}
};
if (auth.IsAuthorized)
{
twitterCtx = new TwitterContext(auth);
var tweetResponse =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.User &&
tweet.ScreenName == "OurProfile" &&
tweet.IncludeRetweets == true
select tweet)
.ToList();
Results.Text = twitterCtx.RawResult;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (twitterCtx != null)
{
twitterCtx.Dispose();
twitterCtx = null;
}
}
Does anyone have any ideas of what could be the problem here? Like I said, I'm still pretty new, and I'm at a loss here even how to troubleshoot this issue beyond Google. Could it be something where our server can't verify that Twitter's SSL certificate is from a trusted source? Let me know if I can provide any more information or any more code. Thanks for your time and for reading through my post!

(OAuthException) (#200) User must have accepted TOS on C# - Facebook

Well, I am trying make a app to write comments to facebook in C#.
Searching in google I know that I need an Application (I did it) and I need select the permissions. I did it..
Now I wrote my code in C#:
private string MyAppId = "XXX";
private string MyAppSecret = "XXX";
private void button1_Click(object sender, EventArgs e)
{
FacebookClient FB = new FacebookClient(MyAppId, MyAppSecret);
Dictionary<string,string> data = new Dictionary<string,string>();
data.Add("message","test");
FB.Post("OBJECT_ID/comments", data);
}
But when I click the button I get this error:
(OAuthException) (#200) User must have accepted TOS
I am getting crazy! Please help me =(
It doesn't look like you're actually using the users access token.
You need to go through the OAuth workflow, where the user is redirected to facebook.com and grants your application permission. Once that happens, you'll get an Access Token that you use to make requests on behalf of the user.
There's an overload for the FacebookClient class that will take an access token.
Since you didn't really expand on the type of app you're writing, the Facebook C# Github page has a collection of samples, for WinForms, ASP.NET, and Windows 8 Metro. This example should show you how to do client-side authentication.
You're also trying to post to OBJECT_ID, which isn't a valid user/post/page.

Windows identity foundation - sign out or update claims

I am using Windows Identity foundation to manage login to our site.
When a user logs in i am using some information in his request to put into the claims.
It is all working fine, but now I need to manage this scenario:
user is already logged in, athenticated and has a valid token.
But user decides to browses in again (via a redirect from another site)
So his information in his request is different.
I want to either
Sign him out - so that he naturally creates a new token with his new information
OR update his existing token.
So my question is:
How do i Sign out of Windows Identity foundation?
Or How do I update the existing claims?
I have tried this code:
public void ExpireClaims(HttpContextBase httpContextBase)
{
var module =
httpContextBase.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as
WSFederationAuthenticationModule;
if (module == null)
{
return;
}
module.SignOut(true);
}
But module is alway null.
and i tried this:
public void FederatedSignOut(string replyUrl)
{
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri(replyUrl));
}
But i get a null reference execption when i do this.
Thanks very much.
Essentially sign-out is just deleting the cookie so:
FormsAuthentication.SignOut
or
FederatedAuthentication.SessionAuthenticationModule.SignOut
or
FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie
will work.
Or use the FederatedPassiveSignInStatus (should be in your Toolbox). Set the property SignOutAction to FederatedSignOut and the control will clear out your STS session as well.

Categories

Resources