C# API Authentication

55 views
Skip to first unread message

mcollins

unread,
Jul 25, 2008, 3:41:23 PM7/25/08
to Brightkite API
A couple people have reported problems authenticating with the API
when using C#. Unfortunately I don't have an answer for this yet but
I'd like to start a thread to try and get to the bottom of it so you
guys can finish your apps, and so when we find a solution it will be
easy for others to find later.

Are you attempting to use HTTP Basic Authentication ( login and
password) ? If so have you gotten this to work with other API's or
websites?

Has anyone tried Brightkite's OAuth authentication from C# ? There is
a C# implementation for OAuth here: http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs

Are there any C# guru's out there that have run into something like
this before?

Jason Emerick

unread,
Jul 25, 2008, 4:20:41 PM7/25/08
to brightk...@googlegroups.com
I am by no means an C# expert/guru but the method below is very similar to how I am doing basic authentication on the BlackBerry using JavaME.  I am basically just adding the authorization header to the request before sending out the request.

restRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password")));

The above line was found here: http://geekswithblogs.net/dtotzke/articles/24571.aspx

Maybe this will help.  Let me know.

Jason Emerick

The information transmitted (including attachments) is covered by the Electronic Communications Privacy Act, 18 U.S.C. 2510-2521, is intended only for the person(s) or entity/entities to which it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon, this information by persons or entities other than the intended recipient(s) is prohibited. If you received this in error, please contact the sender and delete the material from any computer.

mcollins

unread,
Jul 25, 2008, 5:22:56 PM7/25/08
to Brightkite API
Ahhh, I think I see what is happening here. Some of the Brightkite
REST URLs may not return a 401 Unauthorized, which means that the
login credentials don't get sent automatically on the subsequent
request. To work around this you will have to force them to be sent
on the first request. I have read though that with .NET if you set
them manually and set PreAuthenticate true, that it will send them on
the first request. Something like:

request.Credentials = new NetworkCredential(login, password);

I believe that adds them to the Authorization header like Jason
suggested, only you won't have to do the manual base64 conversion. I
haven't tried this yet but if someone else wants to give it a try
please respond here whether it works or not.

Mike

On Jul 25, 2:20 pm, "Jason Emerick" <jemer...@gmail.com> wrote:
> I am by no means an C# expert/guru but the method below is very similar to
> how I am doing basic authentication on the BlackBerry using JavaME.  I am
> basically just adding the authorization header to the request before sending
> out the request.
>
> restRequest.Headers.Add("Authorization", "Basic " +
> Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password")));
>
> The above line was found here:http://geekswithblogs.net/dtotzke/articles/24571.aspx
>
> Maybe this will help.  Let me know.
>
> Jason Emerick
>
> The information transmitted (including attachments) is covered by the
> Electronic Communications Privacy Act, 18 U.S.C. 2510-2521, is intended only
> for the person(s) or entity/entities to which it is addressed and may
> contain confidential and/or privileged material. Any review, retransmission,
> dissemination or other use of, or taking of any action in reliance upon,
> this information by persons or entities other than the intended recipient(s)
> is prohibited. If you received this in error, please contact the sender and
> delete the material from any computer.
>

d saxman

unread,
Jul 25, 2008, 7:04:47 PM7/25/08
to brightk...@googlegroups.com
That's exactly what I'm doing (have been trying to do) and it still gives me an error that I'm not logged in.  If I try to send a photo, I get a 500 error as well.

d saxman

unread,
Jul 25, 2008, 7:13:26 PM7/25/08
to brightk...@googlegroups.com
Here is the function I'm using - basically a slightly modified version of the KB article at http://support.microsoft.com/kb/908573

private string SendANote(Uri uriLocation, string strUsername, string strPassword, string strBody)
        {
        try
            {

                HttpWebRequest WRequest;
                HttpWebResponse WResponse;
               
                //preAuth the request                               
                WRequest = (HttpWebRequest)HttpWebRequest.Create(uriLocation);
                // Set the username and the password.
                WRequest.Credentials = new NetworkCredential(strUsername, strPassword);
                WRequest.PreAuthenticate = true;
                WRequest.UserAgent = "BrightKiteMobile";
                WRequest.Method = "HEAD";
                WRequest.Timeout = 10000;
                WResponse = (HttpWebResponse)WRequest.GetResponse();
                WResponse.Close();               

                // Make the real request.
                WRequest = (HttpWebRequest)HttpWebRequest.Create(uriLocation);
                // Set the username and the password.
                WRequest.Credentials = new NetworkCredential(strUsername, strPassword);
                //WRequest.PreAuthenticate = true;
                WRequest.UserAgent = "BrightKiteMobile";
                WRequest.Method = "POST";
                WRequest.AllowWriteStreamBuffering = false;
                WRequest.Timeout = -1;

                StringBuilder data = new StringBuilder();
                data.Append(strBody);

                // Create a byte array of the data we want to send 
                byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

                // Set the content length in the request headers 
                WRequest.ContentLength = byteData.Length;

                // Write data 
                using (Stream postStream = WRequest.GetRequestStream())
                {
                    postStream.Write(byteData, 0, byteData.Length);
                }


                // Read your response data here.
                // Get response 
                using (WResponse = WRequest.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream 
                    StreamReader reader = new StreamReader(WResponse.GetResponseStream());

                    // Console application output 
                    string strOutput = reader.ReadToEnd();
                    return strOutput;
                }

                WResponse.Close();
            }
           
            catch (Exception ex)
            {
                string strErrorMessage = "";
                switch (ex.Message)
                {
                    case "The remote server returned an error: (401) Unauthorized.":
                        strErrorMessage = "Unable to contact BrightKite - please make sure your username and password is correct on the Settings page!";
                        MessageBox.Show(strErrorMessage, "Authentication error");
                        return strErrorMessage;
                        break;
                    case "Could not establish connection to network.":
                         strErrorMessage ="Unable to establish a data connection.  Please try again when you have sufficient network signal.";
                        MessageBox.Show(strErrorMessage, "Network error");
                        return strErrorMessage;
                        break;
                    default:
                        strErrorMessage = "An error occurred contacting BrightKite.com.  Please try again later.";
                        MessageBox.Show(strErrorMessage, "Error!");
                        return strErrorMessage;
                        break;

Jason Emerick

unread,
Jul 25, 2008, 9:53:29 PM7/25/08
to brightk...@googlegroups.com
Have you tried the manual way as well?  Just curious...  Also if you can, I would suggest running a packet sniffer (try wireshark) to see what exactly is getting sent to brightkite.  Maybe C# is leaving off the authorization header or something funky like that?


Jason Emerick

The information transmitted (including attachments) is covered by the Electronic Communications Privacy Act, 18 U.S.C. 2510-2521, is intended only for the person(s) or entity/entities to which it is addressed and may contain confidential and/or privileged material.  Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon, this information by persons or entities other than the intended recipient(s) is prohibited.  If you received this in error, please contact the sender and delete the material from any computer.

d saxman

unread,
Jul 25, 2008, 10:10:44 PM7/25/08
to brightk...@googlegroups.com
I can post just fine using cURL.  let me try wireshark and see if I can narrow it down.  I really doubt it's leaving it off given that I'm following the MS code, but I'll give it a shot.

Michael

unread,
Jul 26, 2008, 3:40:37 AM7/26/08
to Brightkite API
For the record, I'm having exactly the same problem. Authenticated GET
works just fine, but POST fails. I did a little looking around and it
appears that it is not all that uncommon for people to have trouble
with authenticated post with the HttpWebRequest object. :-(

Did you have any luck looking at what's on the wire?

On Jul 25, 7:10 pm, "d saxman" <dsax...@gmail.com> wrote:
> I can post just fine using cURL.  let me try wireshark and see if I can
> narrow it down.  I really doubt it's leaving it off given that I'm following
> the MS code, but I'll give it a shot.
>
> On Fri, Jul 25, 2008 at 9:53 PM, Jason Emerick <jemer...@gmail.com> wrote:
> > Have you tried the manual way as well?  Just curious...  Also if you can, I
> > would suggest running a packet sniffer (try wireshark) to see what exactly
> > is getting sent to brightkite.  Maybe C# is leaving off the authorization
> > header or something funky like that?
>
> > Jason Emerick
>
> > The information transmitted (including attachments) is covered by the
> > Electronic Communications Privacy Act, 18 U.S.C. 2510-2521, is intended only
> > for the person(s) or entity/entities to which it is addressed and may
> > contain confidential and/or privileged material.  Any review,
> > retransmission, dissemination or other use of, or taking of any action in
> > reliance upon, this information by persons or entities other than the
> > intended recipient(s) is prohibited.  If you received this in error, please
> > contact the sender and delete the material from any computer.
>
> > On Fri, Jul 25, 2008 at 7:13 PM, d saxman <dsax...@gmail.com> wrote:
>
> >> Here is the function I'm using - basically a slightly modified version of
> >> the KB article athttp://support.microsoft.com/kb/908573
> >>> On Fri, Jul 25, 2008 at 5:22 PM, mcollins <collins.m...@gmail.com>

Eric Moore

unread,
Jul 27, 2008, 12:30:55 PM7/27/08
to brightk...@googlegroups.com
I have been using code which is basically identical to saxman, I have also tried MS recommended authorizing with HEAD before sending the actual webrequest, but got the same result.  Below is an example of my code.

            string url = "http://brightkite.com/me.xml";
            HttpWebRequest WRequest = WebRequest.Create(url) as HttpWebRequest;
            WRequest.Credentials = new NetworkCredential(username, password);
            WRequest.PreAuthenticate = true;

            WRequest.Method = "HEAD";
            WRequest.Timeout = 10000;
            HttpWebResponse WResponse = (HttpWebResponse)WRequest.GetResponse();
            WResponse.Close();

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Credentials = new NetworkCredential(username, password);
            request.PreAuthenticate = true;
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    XmlDocument doc = new XmlDocument();
                    doc.Load(reader);

Martin May

unread,
Jul 29, 2008, 4:20:04 PM7/29/08
to Brightkite API

I think this is happening because certain URL take optional
authentication, and if the site doesn't challenge for authentication,
it's not send by certain client libraries.

Easy fix:

We've added a force_auth=1 parameter that you can append to any
request, and will always challenge for authentication, even when you
could access the URL unauthenticated.

Let me know if this works.

Martin
> ...
>
> read more »

Michael

unread,
Jul 29, 2008, 6:45:51 PM7/29/08
to Brightkite API
Thanks for taking a stab at it, but no... same error: "You must be
logged in to do that."
> ...
>
> read more »

d saxman

unread,
Jul 29, 2008, 7:03:30 PM7/29/08
to brightk...@googlegroups.com
Same results here - You must be logged in to do that.

Any chance you would publish an ASMX file for us to consume as a web service?

Eric Moore

unread,
Jul 30, 2008, 1:34:56 PM7/30/08
to brightk...@googlegroups.com
I've used both amazon REST and facebook REST APIs before from c# so this is doable without resorting to a SOAP webservice.  Unfortunately, I don't know why this isn't working and when I tried to use a packet sniffer I found that everything is transferred compressed so I couldn't see anything.  I haven't had much time to work on this.  I'm certain it is NOT that we're trying to access something that doesn't require authentication.  I'm assume me.xml requires authentication since it won't know who "me" is until you authenticate.

dsaxman

unread,
Aug 3, 2008, 12:23:51 AM8/3/08
to Brightkite API
I know it's doable without SOAP, however, if the brightkite guys can't
get it working the way it stands at the moment, it may be easier to
write a SOAP API or let one of us help them out with it to get it up
and going.

On Jul 30, 1:34 pm, "Eric Moore" <aliasmrjo...@gmail.com> wrote:
> I've used both amazon REST and facebook REST APIs before from c# so this is
> doable without resorting to a SOAP webservice.  Unfortunately, I don't know
> why this isn't working and when I tried to use a packet sniffer I found that
> everything is transferred compressed so I couldn't see anything.  I haven't
> had much time to work on this.  I'm certain it is NOT that we're trying to
> access something that doesn't require authentication.  I'm assume me.xml
> requires authentication since it won't know who "me" is until you
> authenticate.
>
>
>
> On Tue, Jul 29, 2008 at 5:03 PM, d saxman <dsax...@gmail.com> wrote:
> > Same results here - You must be logged in to do that.
>
> > Any chance you would publish an ASMX file for us to consume as a web
> > service?
>
> ...
>
> read more »- Hide quoted text -
>
> - Show quoted text -

dsaxman

unread,
Sep 4, 2008, 1:50:58 AM9/4/08
to Brightkite API
I still can't get Basic Auth or OAuth to work. My offer still stands
to help setup a SOAP based API for us C# guys. I'd *really* like to
get one of these three methods working in the next week to use for
part of my presentation at the Richmond Code Camp on Oct. 4th on
mobile social networking app development.
> ...
>
> read more »

Chris Messina

unread,
Sep 4, 2008, 2:21:42 AM9/4/08
to brightk...@googlegroups.com
I'm surprised that it's not working... if this is a problem with the
OAuth library, we should definitely get this fixed. Do you have an
idea where the problem is actually occurring?
--
Chris Messina
Citizen-Participant &
Open Source Advocate-at-Large
factoryjoe.com # diso-project.org
citizenagency.com # vidoop.com
This email is: [ ] bloggable [X] ask first [ ] private
Message has been deleted

d saxman

unread,
Sep 12, 2008, 3:04:43 PM9/12/08
to brightk...@googlegroups.com
What code did you use to get it to work, it's still not working for me using OAuth or BasicAuth via C# for me.

BTW, on the OAuth side, should have some time to debug this weekend and see exact where it is breaking down.  A lot of the posts I've read on trying to troubleshoot the issue center around URL encoding in the proper order, so that may be part of the problem.

On Fri, Sep 12, 2008 at 8:13 AM, Wratty <ian.ra...@gmail.com> wrote:

I've had little experience with the API so far, but I've just done
exactly the same as posted above for placemarks and it works for me.


On Sep 4, 7:21 am, "Chris Messina" <chris.mess...@gmail.com> wrote:
> I'm surprised that it's not working... if this is a problem with the
> OAuth library, we should definitely get this fixed. Do you have an
> idea where the problem is actually occurring?
>
> ...
>
> read more »


Michael Nemtsev

unread,
Sep 13, 2008, 9:19:53 AM9/13/08
to Brightkite API
Any progress since then how to logon via C#?
Tried samples from here, but get "The remote server returned an error:
(404) Not Found." all time

Alex Wright

unread,
Nov 7, 2008, 10:47:05 AM11/7/08
to Brightkite API
I've created a quick client. At this point it's mainly a Brightkite
client, but it has a Twitter tab and I intend to add more networks.

It's c# .Net 3.5 CF, but I expect it would compile on 2.0.

Still very rough BTW. I've spent about a total of 15 hours in VS.Net
in my life time, so forgive any noob mistakes please.

Authentication works, you can:
* load placemarks
* search places
* check in from either
* read feeds
* post notes

Exe to run on CF 3.5 Windows Mobiles: http://alex-fu.com/work/CSharp/SocializeWM.exe
Source: http://alex-fu.com/work/CSharp/SocializeWM.zip

Please email me any feedback, or message me on Brightkite (Alex_w).
Thanks
Reply all
Reply to author
Forward
0 new messages