cancel
Showing results for 
Search instead for 
Did you mean: 

C# ASP.NET OAuth Example

Moderator

C# ASP.NET OAuth Example

With our new support for OAuth, we released a PHP sample of how to use our API features with OAuth.  Since then, we've received quite a few request on how to do the same with ASP.NET.  I decided to write up a quick demo of how to do a simple ASP.NET OAuth API access.  We'll be looking to add this to our .NET library in the next version of the library, feel free to reuse this code with the library in the meantime. 

 

Disclamer: This sample is basically a one time use demo, it will not keep the data stored for future use.  How you do that depends on how you store customer data in your application.  You should follow all comments in the code for when and what to store in your database.  All code is provided as is.  The OAuth library is courtesy of Bittercoder and his DevDefined.OAuth library.  Amazing resource and a great developer, big thanks!

 

Any OAuth implementation involves basically only two pages.  One that initiates the OAuth process, generally a button or a link to a server script (my example uses an ASP.NET Button) and a callback URL, a page that handles the return request from the authorizing server and stores the Authorization Token for future use.  My sample is the most simple way that this can possibly happen, though there are far more user friendly options using AJAX that are beyond the scope of this post. 

 

The first page of my demo is the default.aspx page.  There isn't really much going on here that is interesting except for the setting up of the OAuth process.  Here are the details on what is set up and what it all means.

 

First, we need to set up an OAuthConsumerContext for the flow. This contains three pieces of information, ConsumerKey (your Constant Contact API Key), SignatureMethod (always will be SignatureMethod.HmacSha1) and your ConsumerSecret (your Constant Contact Consumer Secret token).

 

private OAuthConsumerContext ConstantContactContext = new OAuthConsumerContext
{
    ConsumerKey = "", // Replace with your API Key
    SignatureMethod = SignatureMethod.HmacSha1,
    ConsumerSecret = "" // Replace with your Consumer Secret Key
};

 

Now we have to set up the callback URL used for OAuth.   This must be done in an environment where Constant Contact can see your script, in my case I just published it to a test IIS server.  You'll want to replace this string with  the path to the test files if they aren't in the root folder.

 

String CallbackUrl = Server.MachineName + "/OAuthCallbackPage.aspx";

 

The last piece of setup we need to do is configure the OAuthSession for getting the Authorized Token.  Two pieces need to be set, one for processing actual requests.

 

ConstantContactContext.UseHeaderForOAuthParameters = true;

ConstantContactSession = new OAuthSession(ConstantContactContext,
    "https://oauth.constantcontact.com/ws/oauth/request_token",
    "https://oauth.constantcontact.com/ws/oauth/confirm_access",
    "https://oauth.constantcontact.com/ws/oauth/access_token",
    CallbackUrl);

 

Now that we're all configured on everything, we need to get the Request Token from Constant Contact and then send the user over to Constant Contact OAuth Application to Authorize us.  It's actually only two lines of code to generate this with this library and the end product is a URI that we can use any way we want, from a simple redirect to complicated AJAX requests.

 

IToken requestToken = ConstantContactSession.GetRequestToken();

String requestUri = ConstantContactSession.GetUserAuthorizationUrlForToken(requestToken, CallbackUrl);

  

Since we'll need to reuse the information we configured earlier, I stored everything in the Session variable.  There are plenty of other ways to do this, from storing in a database to to using additional query parameters in the Callback URL.  I chose this for simplicity, you may need to customize this in your application.

 

Session.Add("ConstantContactUsername", TextBox1.Text);
Session.Add("ConstantContactRequestToken", requestToken);
Session.Add("ConstantContactSession", ConstantContactSession);

 

The rest of the Authentication flow is handled by Constant Contact OAuth server.  Once it's all done, we pass back to you the information you'll need to get the Authentication Token.  The file OAuthCallbackPage.aspx has all the code needed to this, except for the code where you store everything locally into your database for reuse!  First off, we need to load onto this page the data from the Session variables we saved on Default.aspx

 

private OAuthSession ConstantContactSession;
private String Username;
private IToken requestToken;
private IToken ConstantContactAccessToken;
private String VerficationToken;
private System.Text.UTF8Encoding encoder = new UTF8Encoding();
private OAuthContext OAuthRequestContext = new OAuthContext();

Username = Session .ToString();
requestToken = Session  as IToken;
ConstantContactSession = Session  as OAuthSession;

 

Next, we need to pull out the Verifier token from the query params of the Callback URL.  Once we have that, we can now exchange it for our Authentication Token.  At this point, OAuth is done and you're authorized!  Don't forget, save the Authorization Token for future use or your users will have to go through this everytime they try to use your integration.

 

VerficationToken = Request.QueryString .ToString();

ConstantContactAccessToken = ConstantContactSession.ExchangeRequestTokenForAccessToken(requestToken, VerficationToken);

  

The final piece I'm going to show is how to send an actual request with this library.  It's not entirely obvious how to configure the request, but once you understand it, it's not very different than using the HttpWebRequest class in System.Net.  First up, we need to configure our request Context.

  

OAuthRequestContext.UseAuthorizationHeader = true;
OAuthRequestContext.RawContentType = "application/atom+xml";
OAuthRequestContext.RequestMethod = "POST";
OAuthRequestContext.RawUri = new Uri("https://api.constantcontact.com/ws/customers/" + Username + "/lists");
OAuthRequestContext.RawContent = encoder.GetBytes(@"<entry xmlns=""http://www.w3.org/2005/Atom"">
  <id>data:,</id>
  <title />
  <author />
    <updated>2008-04-16</updated>
    <content type="
"application/vnd.ctct+xml"">
    <ContactList xmlns="
"http://ws.constantcontact.com/ns/1.0/"">
      <OptInDefault>false</OptInDefault>
            <Name>This is a test of OAuth</Name>
            <SortOrder>99</SortOrder>
        </ContactList>
    </content>
</entry>
"
);

 

Now that the request is set up, we can send it over to the Constant Contact API using OAuth.  The code to do this is also pretty short and uses the information we've already set up.  Here's the code:

 

ConsumerRequest httpRequest = new ConsumerRequest(
    OAuthRequestContext,
    ConstantContactSession.ConsumerContext,
    ConstantContactSession.AccessToken);

try
{
    String responseText = httpRequest.ToString();

    Label1.Text = responseText;
}

catch (Exception ex)
{
    Label1.Text = ex.Message;
}

  

And that's all there is to getting OAuth access through ASP.NET.  Everything after this is just usability improvments and making sure you store the data for future use.  Hope you find this helpful, please post questions or suggestions below.

Dave Berard
Senior Product Manager, Constant Contact
3 REPLIES 3
Moderator
Moved:

Re: C# ASP.NET OAuth Example

Re: C# ASP.NET OAuth Example

Can you please upload a Visual Studio project of your code?

 

Thanks.

CTCT Employee

Re: C# ASP.NET OAuth Example

Hi,

 

I would not recommend using this or any other OAuth 1 code/process.  We are deprecating support for OAuth1 and basic authentication.  You should use and implement OAuth2 going forward.

 

We have a PHP example of implementing OAuth2 in PHP, linked to here in Github.  As of now, we don't have an ASP.NET example of how to do this, but here is a description and schematic of the OAuth2 process.

 

Best Regards,

Shannon W.

API Support Specialist