Home > 2011 Fall DPS907, ASP.NET, Windows > Brief introduction to securing a WCF Web API service with an access token

Brief introduction to securing a WCF Web API service with an access token

October 30, 2011 Leave a comment Go to comments

This post is a brief introduction to securing a WCF Web API service with an access token.

This document was most recently updated in October 2011. It is intended to be used by entry-level web service programmers.

.

Overview of the scenario

Token-based schemes are often used for web services that require security. Recently, in class/lecture, we described many of the relevant security principles, and the implementation components, using the OAuth 2.0 Authorization Protocol as an example.

This post includes code that illustrates the bare essentials of handling an access token.

Warning – The code below is NOT a reference sample, or a best practice example. It simply illustrates the concept, in a clearly-understandable manner. Also, it does NOT deal with authentication and authorization issues, authorization stores, or the other “moving parts” that a full and complete solution includes.

.

Sample service code

Use your template to create a new WCF Web API service. Code the service class as follows:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Web service namespaces
using System.ServiceModel;
using System.ServiceModel.Web;
// Additional namespaces
using System.Net;
using System.Net.Http;
using Microsoft.ApplicationServer.Http.Dispatcher;
using System.Net.Http.Headers;

[ServiceContract]
public class Operations
{
    // Custom authorization token
    public string customToken { get; set; }

    // Collection of access tokens, which will be an in-memory "authorization store"
    protected List<string> AccessTokenStore;

    // Constructor
    public Operations()
    {
        this.customToken = HttpContext.Current.Request.Headers["X-ICTtoken"];

        // Un-comment the following if you want to protect the whole service
        //if (this.customToken != "whatever")
        //    throw new HttpResponseException(HttpStatusCode.Forbidden);

        // Create an in-memory "authorization store", with a few access tokens
        AccessTokenStore = new List<string>();
        AccessTokenStore.Add("triUt6ustoeQ");
        AccessTokenStore.Add("KOEn4Ejouqle");
        AccessTokenStore.Add("rIuv5u7hoeno");
        AccessTokenStore.Add("y7UcIeJ9eCIa");
        AccessTokenStore.Add("Joestievief9");
    }

    // Remove this method from an in-production (deployed) web service
    [WebGet(UriTemplate = "")]
    public string ServiceRoot()
    {
        return "Append /test to the URI to use the HTTP Test Client";
    }

    [WebGet(UriTemplate = "example1")]
    public List<string> Example1(HttpRequestMessage request)
    {
        // Get the authorization header
        AuthenticationHeaderValue auth = request.Headers.Authorization;
        // The scheme should be "Bearer", and the parameter should be the access token

        if (auth == null)
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
        else
        {
            // Create a response object
            List<string> response = new List<string>();
            // Report the results
            response.Add("The authorization scheme was: " + auth.Scheme);
            response.Add("The parameter was: " + auth.Parameter);

            // Check if the access token is in the store
            if (AccessTokenStore.Find(t => t == auth.Parameter) == null)
            {
                response.Add("The access token was NOT FOUND in the authorization store");
            }
            else
            {
                response.Add("This is a valid access token");
            }

            return response;
        }
    }

}

.

Test your service

Run the HTTP Test Client for the service.

Request the “example1″ URI. It should respond with 401 unauthorized.

Now, add an “authorization header”:

Authorization:Basic foobar

The response should appear as follows:


<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <string>The authorization scheme was: Basic</string>
  <string>The parameter was: foobar</string>
  <string>The access token was NOT FOUND in the authorization store</string>
</ArrayOfString>

.

Next, change the authorization header:

Authorization:Bearer rIuv5u7hoeno

(or one of the valid authorization codes)

The response should appear as follows:


<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <string>The authorization scheme was: Bearer</string>
  <string>The parameter was: rIuv5u7hoeno</string>
  <string>This is a valid access token</string>
</ArrayOfString>

.


.

.

.

About these ads
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 44 other followers

%d bloggers like this: