Using AuthorizationServer with Nancy

Yesterday I tried to find out what it takes to connect a Nancy application to AuthorizationServer. Given the OWIN promise, the “hard parts” like JWT validation should come for free now:

public class Startup

{

    public void Configuration(IAppBuilder app)

    {

        // validate JWT tokens from AuthorizationServer

        app.UseJsonWebToken(

            issuer: Constants.AS.IssuerName,

            audience: Constants.Audience,

            signingKey: Constants.AS.SigningKey);

 

        app.UseNancy();

    }

}

…and in the Nancy module I simply have to reach into the OWIN context to retrieve the ClaimsPrincipal like this:

public class IdentityModule : NancyModule

{

    public IdentityModule()

    {

        Get[“/api/identity”] = _ =>

            {

                var principal = Context.GetOwinPrincipal();

                   

                if (!principal.Identity.IsAuthenticated)

                {

                    return HttpStatusCode.Unauthorized;

                }

 

                var claims = from c in principal.Claims

                                select new ViewClaim

                                {

                                    Type = c.Type,

                                    Value = c.Value

                                };

 

                return Response.AsJson<IEnumerable<ViewClaim>>(claims);

            };

    }

}

This was my first ever Nancy code and writing this sample took me (with the help of @grumpydev and @randompunter – thanks guys) around 20 minutes. Kudos!

Note: I was told that the Nancy/OWIN/Security integration is not done yet. The above code will be more elegant once it is. Things like module level security settings and no direct dependency to ClaimsPrincipal will soon be included.

Nancy makes it really easy to write Web APIs and has has support for view engines outside of IIS *today* – this makes it really compelling IMO!

Sample is here.

This entry was posted in AuthorizationServer, WebAPI. Bookmark the permalink.

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 )

Connecting to %s