OWIN Bearer Token AuthZ

OWIN Bearer Token AuthZ

31 October 2015

I created some tests to experiment with bearer token authorization (AuthZ). The important lesson was using tests to help define the required AuthZ behaviour. I wanted only requests with the claim type of scope with the value of colsapp to succeed.

The blueprint below shows a request to / with an Authorization header containing a jwt bearer token.

# GET /

+ Request

  + Headers

    Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6ImNvbHNhcHAiLCJpc3MiOiJodHRwOi8vY2h3aWxsaWFtc29uLm1lLnVrIiwiYXVkIjoiaHR0cDovL2Nod2lsbGlhbXNvbi5tZS51ay9hdWRpZW5jZSIsImV4cCI6MTQ0NDMzMzYzOSwibmJmIjoxNDQ0MjQ3MjM5fQ.95qHYRMySlBP5i3o8vbXOTOI6hcPXtr5EZdnurWz41M

  + Response 200

  + Body

    Hello

The payload contains a scope claim with the value colsapp.

{
  "scope": "colsapp",
  "iss": "http://chwilliamson.me.uk",
  "aud": "http://chwilliamson.me.uk/audience",
  "exp": 1444333639,
  "nbf": 1444247239
}

One of the successful tests is shown below; expecting an Http status code of 200 while encoding the claim type of scope with the value of colsapp in the authorization header.

[Fact]
public async void ShouldAllowWithScopeOfColsApp()
{
  using (var s = CreateHelloReturnServerWithJwtBearerAuthN())
  {
    // add scope=colsapp
    var request = s.CreateRequest("/").AddHeader("Authorization","Bearer " + NewBearerToken(new Claim("scope","colsapp")));
    var response = await request.GetAsync();
    response.StatusCode.ShouldBeEquivalentTo(HttpStatusCode.OK,"a bearer token with exected claim should be allowed");
  }
}

The test below expects that an Http Status Code of 403 Forbidden is returned when the scope claim is not supplied.

public async void ShouldDenyWhenMissingScopeOfColsApp()
{
  using (var s = CreateHelloReturnServerWithJwtBearerAuthN())
  {
    var request = s.CreateRequest("/").AddHeader("Authorization", "Bearer " + NewBearerToken());
    var response = await request.GetAsync();
    response.StatusCode.ShouldBeEquivalentTo(HttpStatusCode.Forbidden, "a bearer token which does not have an expected scope should result in a 403 (Forbidden)");
  }
}

You can view the full file below.

See the test file

.NET AuthN AuthZ Frameworks oAuth OpenId-Connect-1.0 OWIN Testing XUnit