Filip Woj: Running multiple ASP.NET Web API pipelines side by side

Over the past 4 years or so, I have worked on many Web API projects, for a lot of different clients, and I thought I have seen almost everything.

Last week I came across an interesting new (well, at least to me) scenario though – with the requirement to run two Web API pipelines side by side, in the same process. Imagine having /api as one Web API “instance”, and then having /dashboard as completely separate one, with it’s own completely custom configuration (such as formatter settings, authentication or exception handling). And all of that running in the same process.

More after the jump.

The problem

On IIS, normally you would solve it having to separate web application assemblies and deploying them into different virtual directories. It gets more interesting, if you try to do this in the same process though.

Sure, this is what OWIN allows you to do – run multiple frameworks or “branches”, side by side. But turns out this is not that easy with the Web API OWIN integration.

Normally you’d go about doing this the following, right?

public class Startup
    public void Configuration(IAppBuilder app)
        app.Map("/api", map =>
            var config = new HttpConfiguration();

            // configure the API 1 here


        app.Map("/dashboard", map =>
            var config = new HttpConfiguration();

            // configure the API 2 here


Seems reasonable, typical usage of the OWIN middleware architecture.

The problem with this set up is that Web API doesn’t necessarily lend itself very well to such set up. This is mainly related to the way Web API discovers controllers and routes.

Since you want to have two pipelines side by side, in the same assembly, you want to have only specific controllers visible to specific pipeline.

By default Web API will look throughout the entire AppDomain for controllers and attribute routes, meaning that both of your pipelines will discover everything and you will end up with a huge mess.

The solution

In order to address that you can define the convention to divide your controllers into specific “areas” or, as we called it from the beginning, pipelines.

Then you can tell Web API configuration object, to only deal with this specific subset of types when discovering controllers and mapping attribute routes. This can be achieved in several ways – namespaces, attributes and so on. The simplest of which is probably using a base marker type though.

Let’s introduce two base controller types representing two different Web API pipelines that we defined earlier – /api and /dashboard.

public abstract class MyApiController : ApiController { }

public abstract class DashboardApiController : ApiController { }

Now we need to be able to set up HttpConfiguration, that’s used to define our Web API server, to respect these base controllers when looking for types that should be used as controllers and when discovering attribute routes.

This can be done by introducing a custom IHttpControllerTypeResolver and IDirectRouteProvider, that would only work with controllers that subclass a specific base class. These implementations are shown below.

public class TypedHttpControllerTypeResolver<TBaseController> : DefaultHttpControllerTypeResolver where TBaseController : IHttpController
    public TypedHttpControllerTypeResolver()
        : base(IsDashboardController)
    { }

    internal static bool IsDashboardController(Type t)
        if (t == null) throw new ArgumentNullException("t");

            t.IsClass &&
            t.IsVisible &&
            !t.IsAbstract &&
            typeof (TBaseController).IsAssignableFrom(t);

 public class TypedDirectRouteProvider<TBaseController> : DefaultDirectRouteProvider where TBaseController : IHttpController
    public override IReadOnlyList<RouteEntry> GetDirectRoutes(HttpControllerDescriptor controllerDescriptor, IReadOnlyList<HttpActionDescriptor> actionDescriptors,
        IInlineConstraintResolver constraintResolver)
        if (typeof(TBaseController).IsAssignableFrom(controllerDescriptor.ControllerType))
            var routes = base.GetDirectRoutes(controllerDescriptor, actionDescriptors, constraintResolver);
            return routes;

        return new RouteEntry[0];

In both cases, we are extending the default implementations – DefaultHttpControllerTypeResolver and DefaultDirectRouteProvider.

While Web API will still treat all AppDomain types as potential “controller” candidates, in TypedHttpControllerTypeResolver we use the same default constraint to discover controllers (must be class, must be public, must not be abstract) that Web API uses, but additionally we throw in the requirement to subclass our predefined base controller.

Similarly, for TypedDirectRouteProvider, Web API will inspect all controllers in the AppDomain, but we can define that routes should be picked up only from those controllers that extend our predefined base.

The final step is just to wire this in, which is very easy – the revised Startup class is shown below.

public class Startup
    public void Configuration(IAppBuilder app)
        app.Map("/api", map =>
            var config = CreateTypedConfiguration<MyApiController>();

            // configure the API 1 here


        app.Map("/dashboard", map =>
            var config = CreateTypedConfiguration<DashboardApiController>();

            // configure the API 2 here


    private static HttpConfiguration CreateTypedConfiguration<TBaseController>() where TBaseController : IHttpController
        var config = new HttpConfiguration();

        config.Services.Replace(typeof(IHttpControllerTypeResolver), new TypedHttpControllerTypeResolver<TBaseController>());
        config.MapHttpAttributeRoutes(new TypedDirectRouteProvider<TBaseController>());

        return config;


And that’s it! No more cross-pipeline conflicts, and two Web API instances running side by side.

Dominick Baier: IdentityServer4 on ASP.NET Core RC2

This week was quite busy ;) Besides doing a couple of talks and workshops at SDD in London – we also updated all the IdentityServer4 bits to RC2.

Many thanks to all the people in the community that were part of this effort!

Here are the relevant links:

IdentityServer4 repo / nuget
AccessTokenValidation repo / nuget
Samples repo

Now that RC2 is finally released, we will continue our work on IdentityServer4. Expect more changes and frequent updates soon. stay tuned!

Filed under: ASP.NET, IdentityServer, OAuth, OpenID Connect, WebAPI

Filip Woj: IP Filtering in ASP.NET Web API

One of the functionalities I had to use fairly often on different ASP.NET Web API projects that I was involved in in the past was IP filtering – restricting access to the whole API, or to parts of it, based on the caller’s IP address.

I thought it might be useful to share this here. More after the jump.


Whenever you build a functionality like that, there are two roads you might wanna take:
– as a whitelist – meaning deny the majority of the callers, and only let some predefined ones through
– as a blacklist – meaning allow the majority of the callers, and only block some predefines ones

While you could approach the task from many different angles, for the purpose of this post, let’s assume you want to have it configurable from the web.config file, and that you will use a whitelist approach (reject everyone, unless they are in the config).

Configuration in ASP.NET is far from the friendliest (at least until we can get ASP.NET Core), and there is some ugly configuration code we will have to write – to deal with configuration elements, sections and so on. We will be extending the types from System.Configuration to provide a reasonably friendly user experience.

We could probably achieve the same with just appSettings but having a dedicated configuration section would be a bit more elegant for the end user.

So let’s imagine we will want to have configuration like this:

    <section name="ipFiltering" type="Strathweb.IpFiltering.Configuration.IpFilteringSection, Strathweb.IpFiltering" />
      <add address="" />

To achieve this, here are our nasty ASP.NET configuration components. First the section:

public class IpFilteringSection : ConfigurationSection
    [ConfigurationProperty("ipAddresses", IsDefaultCollection = true)]
    public IpAddressElementCollection IpAddresses
        get { return (IpAddressElementCollection)this["ipAddresses"]; }
        set { this["ipAddresses"] = value; }

Next, the addresses collections:

public class IpAddressElementCollection : ConfigurationElementCollection
    protected override ConfigurationElement CreateNewElement()
        return new IpAddressElement();

    protected override object GetElementKey(ConfigurationElement element)
        return ((IpAddressElement)element).Address;

And finally the individual entries:

public class IpAddressElement : ConfigurationElement
    [ConfigurationProperty("address", IsKey = true, IsRequired = true)]
    public string Address
        get { return (string)this["address"]; }
        set { this["address"] = value; }

    [ConfigurationProperty("denied", IsRequired = false)]
    public bool Denied
        get { return (bool)this["denied"]; }
        set { this["denied"] = value; }

Implementation of IP filtering

Once we got the configuration out of the way, the usage can take four forms:

  • a message handler (wrapping your entire Web API)
  • a filter (applied on a specific action only)
  • an HttpRequestMessage extension methods (so that it can be called anywhere, i.e. inside a controller)
  • and, as a bonus, an OWIN middleware (wrapping your entire OWIN pipeline, if you are using it)

We should actually start with the extension method, as it’s going to be the base for everything – in the other components (except for OWIN middleware), we will just call that.

The extension method is shown below:

public static bool IsIpAllowed(this HttpRequestMessage request)
        if (!request.GetRequestContext().IsLocal)
            var ipAddress = request.GetClientIpAddress();
            var ipFiltering = ConfigurationManager.GetSection("ipFiltering") as IpFilteringSection;
            if (ipFiltering != null && ipFiltering.IpAddresses != null && ipFiltering.IpAddresses.Count > 0)
                if (ipFiltering.IpAddresses.Cast<IpAddressElement>().Any(ip => (ipAddress == ip.Address && !ip.Denied)))
                    return true;

                return false;

        return true;

So in the extension method, we check if the request is local, and if it isn’t we will proceed to grabbing the IP address from the request.

Then we consult our configuration and if the caller’s address is found in our configuration and check whether the IP should be allowed or not. This check could be done in a more elaborate way (see for example here) – but for our use case it’s enough to just compare them in a simple way, without working about stuff like IP ranges.

We made use of another extension method in the above snippet – (request.GetClientIpAddress()) – I blogged about it a while back and it has also been added to WebApiContrib but for the record, here it is:

public static class HttpRequestMessageExtensions
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
    private const string OwinContext = "MS_OwinContext";

    public static string GetClientIpAddress(this HttpRequestMessage request)
        if (request.Properties.ContainsKey(HttpContext))
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
                return ctx.Request.UserHostAddress;
        if (request.Properties.ContainsKey(RemoteEndpointMessage))
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
                return remoteEndpoint.Address;
        if (request.Properties.ContainsKey(OwinContext))
            dynamic ctx = request.Properties[OwinContext];
            if (ctx != null)
                return ctx.Request.RemoteIpAddress;
        return null;

So now we can proceed towards building our individual components, as they will all rely on the extension method that we created.

First a filter:

public class IpFilterAttribute : AuthorizeAttribute
    protected override bool IsAuthorized(HttpActionContext actionContext)
        return actionContext.Request.IsIpAllowed();

And now a handler:

public class IpFilterHandler : DelegatingHandler
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
        if (request.IsIpAllowed())
            return await base.SendAsync(request, cancellationToken);

        return request.CreateErrorResponse(HttpStatusCode.Forbidden, "Cannot view this resource");

We could make an OWIN middleware too. For this we will need a new extension method – working directly off the OWIN dictionary and grabbing the IP information from there.

For Project Katana purposes, we can make the middleware Microsoft specific, and as such we could build the extension method off IOwinContext instead of the raw OWIN dictionary (since Web API on OWIN relies on Katana anyway).

That code is shown below, and is quite similar to the HttpRequestMessage extension code we wrote a bit earlier.

public static class OwinContextExtensions
    public static bool IsIpAllowed(this IOwinContext ctx)
        var ipAddress = ctx.Request.RemoteIpAddress;
        var ipFiltering = ConfigurationManager.GetSection("ipFiltering") as IpFilteringSection;
        if (ipFiltering != null && ipFiltering.IpAddresses != null && ipFiltering.IpAddresses.Count > 0)
            if (ipFiltering.IpAddresses.Cast<IpAddressElement>().Any(ip => (ipAddress == ip.Address && !ip.Denied)))
                return true;

            return false;

        return true;

And finally, let’s add the middleware itself (again – Katana specific middleware to be precise):

public class IpFilterMiddleware : OwinMiddleware
    public IpFilterMiddleware(OwinMiddleware next) : base(next)

    public override async Task Invoke(IOwinContext context)
        if (context.IsIpAllowed())
            await Next.Invoke(context);
            context.Response.StatusCode = 403;

And that’s it! You can now use the components on:

  • individual actions or controller (the filter)
  • on the whole API (the message handler)
  • on the whole OWIN pipeline (the middleware)
  • or whereever you see fit (the Request extension method)

Of course you can make it much better and more robust, add support for submasks and such, add extra dynamic configuration, instead of static IP look up from web.config and so on – but hopefully this will be a good starting point.

All the source code for this article is at Github.

Henrik F. Nielsen: Announcing ASP.NET WebHooks Release Candidate 1 (Link)

We are very excited to announce the availability of ASP.NET WebHooks Release Candidate 1. ASP.NET WebHooks provides support for receiving WebHooks from other parties as well as sending WebHooks so that you can notify other parties about changes in your service:

Currently ASP.NET WebHooks targets ASP.NET Web API 2 and ASP.NET MVC 5. It is available as Open Source on GitHub, and you can use it as preview packages from Nuget. For feedback, fixes, and suggestions, you can use GitHub, StackOverflow using the tag, or send me a tweet.

For the full announcement, please see the blog Announcing ASP.NET WebHooks Release Candidate 1.

Have fun!


Pedro Félix: Using Fiddler for an Android and Windows VM development environment

In this post I describe the development environment that I use when creating Android apps that rely on ASP.NET based Web applications and Web APIs.

  • The development machine is a MBP running OS X with Android Studio.
  • Android virtual devices are run on Genymotion, which uses VirtualBox underneath.
  • Web applications and Web APIs are hosted on a Windows VM running on Parallels over the OS X host.

I use the Fiddler proxy to enable connectivity between Android and the ASP.NET apps, as well as to provide me full visibility on the HTTP messages. Fiddler also enables me to use HTTPS even on this development environment.

The main idea is to use Fiddler as the Android’s system HTTP proxy, in conjunction with a port forwarding rule that maps a port on the OS X host to the Windows VM. This is depicted in the following diagram.



The required configuration steps are:

  1. Start Fiddler on the Windows VM and allow remote computers to connect
    • Fiddler – Tools – Fiddler Options – Connections – check “Allow remote computers to connect”.
    • This will make Fiddler listen on
  2. Enable Fiddler to intercept HTTPS traffic
    • Fiddler – Tools – Fiddler Options –  HTTPS – check “Decrypt HTTPS traffic”.
    • This will add a new root certificate to the “Trusted Root Certification Authorities” Windows certificate store.
  3. Define a port forwarding rule mapping TCP port 8888 on the OS X host to port TCP 8888 on the Windows guest (where Fiddler is listening).
    • Parallels – Preferences – Network:change settings – Port forward rules  – add “TCP:8888 -> Windows:8888”.
  4. Check which “host-only network” is the Android VM using
    • VirtualBox Android VM – Settings – Network – Name (e.g. “vboxnet1”).
  5. Find the IP for the identified adapter
    • VirtualBox – Preferences – Network – Host-only Networks – “vboxnet1”.
    • In my case the IP is
  6. On Android, configure the Wi-Fi connection HTTP proxy (based on “Configure Fiddler for Android / Google Nexus 7”).
    • Settings – Wi-Fi – long tap on choosen network – modify network – enable advanced options – manual proxy
      • Set “Proxy hostname” to the IP identified in the previous step (e.g.
      • Set “Proxy port” to 8888.
    • With this step, all the HTTP traffic will be directed to the Fiddler HTTP proxy running on the Windows VM
  7. The last step is to install the Fiddler root certificate, so that the Fiddler generated certificates are accepted by the Android applications, such as the system browser (based on “Configure Fiddler for Android / Google Nexus 7”).
    • Open the browser and navigate to http://ipv4.fiddler:8888
    • Select the link “FiddlerRoot certificate” and on the Android dialog select “Credential use: VPN and apps”.

And that’s it: all HTTP traffic that uses the Android system’s proxy settings will be directed to Fiddler, with the following advantages

  • Visibility of the requests and responses on the Fiddler UI, namely the ones using HTTPS.
  • Access to Web applications running on the Windows VM, using both IIS hosting or self-hosting.
  • Access to external hosts on the Internet.
  • Use of the Windows “hosts” file host name overrides.
    • For development purposes I typically use host names other than “localhost”, such as “” or “”.
    • Since the name resolution will be done by the Fiddler proxy, these host names can be used directly on Android.

Here is the screenshot of Chrome running on Android and presenting a ASP.NET MVC application running on the Windows VM. Notice the green “https” icon.

Screen Shot 2016-03-05 at 19.31.53

And here is the Chrome screenshot of a IdentityServer3 login screen, also running on the Windows VM.

Screen Shot 2016-03-05 at 19.34.42

Hope this helps!

Pedro Félix: OAuth 2.0 and PKCE


Both Google and IdentityServer have recently announced support for the PKCE (Proof Key for Code Exchange by OAuth Public Clients) specification defined by RFC 7636.

This is an excellent opportunity to revisit the OAuth 2.0 authorization code flow and illustrate how PKCE addresses some of the security issues that exist when this flow is implemented on native applications.


On the authorization code flow, the redirect from the authorization server back to client is one of the most security sensitive parts of the OAuth 2.0 protocol. The main reason is that this redirect contains the code representing the authorization delegation performed by the User. On public clients, such as native applications, this code is enough to obtain the access tokens allowing access to the User’s resources.

The PKCE specification addresses an attack vector where an attacker creates a native application that registers the same URL scheme used by the Client application, therefore gaining access to the authorization code. Succinctly, the PKCE specification requires the exchange of the code for the access token to use a ephemeral secret information that is not available on the redirect, making the knowledge of the code insufficient to use it. This extra information (or a transformation of it) is sent on the initial authorization request.

A slightly longer version

The OAuth 2.0 cast of characters

  • The User is typically an human entity capable of granting access to resources.
  • The Resource Server (RS) is the entity exposing an HTTP API to access these resources.
  • The Client is an application (e.g. server-based Web application or native application) wanting to access these resources, via a authorization delegation performed by the User. Clients can be
    • confidential – client applications that can hold a secret. The typical example are Web applications, where a client secret is stored and used only on the server side.
    • public – client application that cannot hold a secret, such as native applications running on the User’s mobile device.
  • The Authorization Server (AS) is the entity that authenticates the user, captures her authorization consent and issues access tokens that the Client application can use to access the resources exposed on the RS.

Authorization code flow for Web Applications

The following diagram illustrates the authorization code flow for Web applications (the Client application is a Web server).



  1. The flow starts with the Client application server-side producing a redirect HTTP response (e.g. response with 302 status) with the authorization request URL in the Location header. This URL will contain the authorization request parameters such as the state, scope and redirect_uri.
  2. When receiving this response, the User’s browser automatically performs a GET HTTP request to the Authorization Server (AS) authorization endpoint, containing the OAuth 2.0 authorization request.
  3. The AS then starts an interaction sequence to authenticate the user (e.g. username and password, two-factor authentication, delegated authentication), and to obtain the user consent. This sequence is not defined by OAuth 2.0 and can take multiple steps.
  4. After having authenticated and obtained consent from the user, the AS returns a HTTP redirect response with the authorization response on the Location header. This URL points to the client application hostname and contains the the authorization response parameters, such as the state and the (security sensitive) code.
  5. When receiving this response, the user’s browser automatically performs a GET request to the Client redirect endpoint with the OAuth 2.0 authorization response. By using HTTPS on the request to the Client, the protocol minimises the chances of the code being leaked to an attacker.
  6. Having received that authorization code, the Client then uses it to obtain the access token from the AS token endpoint. Since the client is a confidencial client, this request is authenticated with the client credentials (client ID and client secret), typically sent in the Authorization header using the basic scheme. The AS checks if this code is valid, namely if it was issued to the requesting authenticated client. If everything is verified, a 200 response with the access token is returned.
  7. Finally, the client can use the received access token to access the protected resources.

Authorization code flow for native Applications

For a native application, the flow is slightly different, namely on the first phase (the authorization request). Recall that in this case the Client application is running in the User’s device


  1. The flow begins with the Client application starting the system’s browser (or a web view, more on this on another post) at a URL with the authorization request. For instance, on the Android platform this is achieved by sending an intent.
  2. The browser comes into the foreground and performs a GET request to the AS authorization endpoint containing the authorization request.
  3. The same authentication and consent dance occurs between the AS and the User’s browser.
  4. After having authenticated and obtained consent from the user, the AS returns a HTTP redirect response with the authorization response on the Location header. This URL contains the the authorization response parameters. However, there is something special in the redirect URL. Instead of using a http URL scheme, which would make the browser perform another HTTP request, the redirect URL contains a custom URI scheme.
  5. As a result, when the browser receives this response and processes the redirect an inter-application message (e.g. an intent in Android) is sent to the application associated to this scheme, which should be the Client application. This brings the Client application to the foreground and provides it with the authorization response parameters, namely the authorization code.
  6. From now on, the flow is similar to the Web based one. Namely, the Client application  uses the code to obtain the access token from the AS token endpoint. Since the client is a public client, this request is not authenticated, that is no client secret is used.
  7. Finally, having received the access token, the client application running on the device can access the User’s resources.

On both scenarios, the authorization code communication path, from the AS to the Client via User’s browser, is very security sensitive. This is specially relevant in the native scenario since the Client is public and the knowledge of that authorization code is enough to obtain the access token.

Hijacking the redirect

On the Web application scenario, the GET request with the authorization response has a HTTPS URL, which means that the browser will only send the code if the server correctly authenticates itself. However, on the native scenario, the intent will be sent to any installed application that registered the custom scheme. Unfortunately, there isn’t a central entity controlling and validating these scheme registrations, so an application can hijack the message from the browser to the client application, as shown in the following diagram.


Having obtained the authorization code, the attacker’s application has all the information required to retrieve a token and access the User’s resources.

The PKCE protection

The PKCE specification mitigates this vulnerability by requiring an extra code_verifier parameter on the exchange of the authorization code for the access token.Slide5

  • On step 1, the Client application generates a random secret, stores it and uses its hash value on the new code_challenge authorization request parameter.
  • On step 4, the AS somehow associates the returned code to the code_challenge.
  • On step 6, the Client includes a code_verifier parameter with the secret on the token request message. The AS computes the hash of the code_verifier value and compares it with the original code_challenge associated with the code. Only if they are equals is the code accepted and an access token returned.

This ensures that only the entity that started the flow (sent the code_challenge on the authorization request) can end the flow and obtain the access token. By using a cryptographic hash function on the code_challenge, the protocol is protected from attackers that have read access to the original authorization request. However, the protocol also allows the secret to be used directly on the code_challenge.

Finally, the PKCE support by an AS can be advertised on the OAuth 2.0 or OpenID Connect discovery document, using the code_challenge_methods_supported field. The following is the Google’s OpenID Connect discovery document, located at

 "issuer": "",
 "authorization_endpoint": "",
 "token_endpoint": "",
 "userinfo_endpoint": "",
 "revocation_endpoint": "",
 "jwks_uri": "",
 "response_types_supported": [
  "code token",
  "code id_token",
  "token id_token",
  "code token id_token",
 "subject_types_supported": [
 "id_token_signing_alg_values_supported": [
 "scopes_supported": [
 "token_endpoint_auth_methods_supported": [
 "claims_supported": [
 "code_challenge_methods_supported": [





Henrik F. Nielsen: ASP.NET WebHooks and Slack Slash Commands (Link)

We just added a couple of new features in ASP.NET WebHooks that make it easier to build some nice integrations with Slack Slash Commands. Slash Commands make it possible to trigger any kind of processing from a Slack channel by generating an HTTP request containing details about the command. For example, these commands typed in a Slack channel can be configured to send an HTTP request to an ASP.NET WebHook endpoint where processing can happen:

/list add <user>
/list list
/list remove <user>
Responses from Slash Commands can be structured documents containing text, data, images, and more:


In the post ASP.NET WebHooks and Slack Slash Commands we describe how ASP.NET WebHooks help you with parsing Slash Commands and generate structured responses so that you can build cool integrations with Slack.

Have fun!


Dominick Baier: NDC London 2016 Wrap-up

NDC has been fantastic again! Good fun, good talks and good company!

Brock and I did the usual 2-day version of our Identity & Access Control workshop at the pre-con. This was (probably) the last time we ran the 2-day version on Katana. At NDC in Oslo it will be all new material based on ASP.NET Core 1.0 (fingers crossed ;))

The main conference had dozens of interesting sessions and as always – pretty strong security content. On Wednesday I did a talk on (mostly) the new identity & authentication features of ASP.NET Core 1.0 [1]. This was also the perfect occasion to world-premier IdentityServer4 – the preview of the new version of IdentityServer for ASP.NET and .NET Core [2].

Right after my session, Barry focused on the new data protection and authorization APIs [3] and Brock did an introduction to IdentityServer (which is now finally on video [4]).

We also did a .NET Rocks [5] and Channel9 [6] interview – and our usual “user group meeting” at Brewdogs [7] ;)

All in all a really busy week – but well worth it!

[1] What’s new in Security in ASP.NET Core 1.0
[2] Announcing IdentityServer4
[3] A run around the new Data Protection and Authorization Stacks
[4] Introduction to IdentityServer
[5] .NET Rocks
[6] Channel9 Interview
[7] Brewdog Shepherd’s Bush


Filed under: .NET Security, ASP.NET, IdentityServer, OAuth, OpenID Connect, Uncategorized, WebAPI

Henrik F. Nielsen: Sending ASP.NET WebHooks from Azure WebJobs (Link)

Azure WebJobs is a great way for running any kind of script or executable as a background process in connection with an App Service Web App. You can upload an executable or script as a WebJob and run it either on a schedule or continuously. The WebJob can perform any function you can stick into a command line script or program and using the Azure WebJobs SDK, you can trigger actions to happen as a result of inputs from a Azure Queues, Blobs, Azure Service Bus, and much more.

WebHooks provide a simple mechanism for sending event notification across web applications and external services. For example, you can receive a WebHook when someone sends money to your PayPal account, or when a message is posted to Slack, or a picture is posted to Instagram.

The blog Sending ASP.NET WebHooks from Azure WebJobs describes how to send ASP.NET WebHooks from Azure WebJobs triggered by anything that can kick off a WebJob.

Have fun!


Dominick Baier: Which OpenID Connect/OAuth 2.0 Flow is the right One?

That is probably the most common question we get – and the answer is of course: it depends!

Machine to Machine Communication
This one is easy – since there is no human directly involved, client credentials are used to request tokens.

Browser-based Applications
This might be a JavaScript-based application or a “traditional” server-rendered web application. For those scenarios, you typically want to use the implicit flow (OpenID Connect / OAuth 2.0).

A side effect of the implicit flow is, that all tokens (identity and access tokens) are delivered through the browser front-channel. If you want to use the access token purely on the server side, this would result in an unnecessary exposure of the token to the client. In that case I would prefer the authorization code flow – or hybrid flow.

Native Applications
Strictly speaking, a native application has very similar security properties compared to a JavaScript application. Still they are generally considered a bit more easy to secure because you often have stronger platform support for protecting data and isolation.

That’s the reason why the current consensus is, that an authorization code based flow gives you “a bit more” security than implicit. The much more important reason IMO is, that there are a couple of (upcoming) protocols that are optimized for native clients, and they use code exchange and the token endpoint as a foundation – e.g. PKCE, Proof of Possession and AC/DC.

Remark 1: With native applications I mean applications that have access to platform-native APIs like data protection or maybe the system browser. Cordova applications are e.g. written in JavaScript, but I would not consider them to be a “browser-based application”.

Remark 2: For code based flows, you need to embed the client secret in the client application. Of course you can’t treat that as a secret anymore – no matter how good you protect it, a motivated attacker will be able to reverse engineer it. It is still a bit better than no secret at all. Specs like PKCE make it a bit better as well.

Remark 3: I often hear the argument that the client application does not care who the user is, it just needs an access token – thus we rather do OAuth 2.0 than OpenID Connect. While this might be strictly speaking true – OIDC is the superior protocol as it includes a couple of extra security features like nonces for replay protection or c_hash and at_hash to link the (verifiable) identity token to the (unverifiable) access token.

Remark 4: As an extension to remark 3 – always use OpenID Connect – and not OAuth 2.0 on its own. There should be client libraries for every platform of interest by now. ASP.NET has middleware, we have a library for JavaScript. Other platforms should be fine as as well.

Remark 5: Whenever you think about using authorization code flow – rather use hybrid flow. This gives you a verifiable token first before you make additional roundtrips (another extensions of remark 3 and 4).


Filed under: .NET Security, IdentityServer, OAuth, OpenID Connect, WebAPI

Darrel Miller: Azure API Management Resources

Although I know my HTTP and Web API pretty well, becoming an API Evangelist on the Azure API Management team means also needing to know the nitty gritty of the Azure API Management product too.  In my learning process I have discovered a wealth of useful information, but it is scattered around a little.  Some is on the Azure documentation site, some on Channel 9, some on YouTube and some awesome content from our Microsoft MVPs.  This post is my attempt to gather it together to make it a bit easier to find. 


This is a first cut at collecting together the material.  I’ll add more content as I find it and update this post.

Getting Started

There are lots of getting started videos for Azure API Management and a simple getting started article.  We’re currently working on a new getting started article that will demonstrate some of the new features the team has been adding recently.


Policy Features

The policy engine in API management is the piece that allows you to add all kinds of useful behaviour into your request/response HTTP pipeline.  We have basic articles showing you the syntax and operations of the policies and we have lots of videos and articles showing practical examples of using the policies.


Rate Limiting Policies


Logging Policies


Integration Policies


Security Policies


Caching Policies


Portal Customization

The developer portal is the self-serve interface for the consumers of your APIs.  This is a highly customizable place for developers to learn what APIs you have and how to consume them.  More customization cabilities will be released in the coming weeks.


Automation / DevOps

The API Management instance is a key piece of the overal system architecutre.  It needs to be just as automatable and manageable as other parts of your system.  Look out for some major enhancements coming soon in this area.


Use Cases

Learning from customer usage is the key to driving the future of the product in the right direction.  I’m sure there are more of these types of articles around and I’ll add them as I find them.

End To End Samples

Azure API Management Master Class

Dominick Baier: Announcing IdentityServer for ASP.NET 5 and .NET Core

Over the last couple of years, we’ve been working with the ASP.NET team on the authentication and authorization story for Web API, Katana and ASP.NET 5. This included the design around claims-based identity, authorization and token-based authentication.

In the Katana timeframe we also reviewed the OAuth 2.0 authorization server middleware (and the templates around it) and weren’t very happy with it. But as usual, there were deadlines and Web API needed a token-based security story, so it shipped the way it was.

One year ago the ASP.NET team decided to discontinue that middleware and rather focus on consuming tokens instead. They also asked us if IdentityServer can be the replacement going forward.

By that time there were many unknowns – ASP.NET was still in early betas and literally changing every day. Important features like x-plat crypto (and thus support for JWT) weren’t even existing. Nevertheless, we agreed that we will port IdentityServer to ASP.NET 5 and .NET Core once the builds are more stabilized.

With RC1 (and soon RC2), we decided that now would the right moment in time to start porting IdentityServer – and here it is: IdentityServer4 (github / nuget / samples)

What’s new
When we designed IdentityServer3, one of our main goals was to be able to run self-hosted. At that time MVC was tied to IIS so using it for our default views was not an option. We weren’t particularly keen on creating our own view engine/abstraction, but that’s what needed to be done. This is not an issue anymore in ASP.NET 5, and as a result we removed the view service from IdentityServer4.

In IdentityServer4 you have full control over all UI aspects – login, consent, logoff and any additional UI you want to show to your user. You also have full control over the technology you want to use to implement that UI – it will be even possible to implement the UI in a completely different web application. This would allow adding OAuth 2.0 / OpenID Connect capabilities to an existing or legacy login “application”.

There will be also a standard UI that you can simply add as a package as well as templates to get you started.

Furthermore, IdentityServer4 is a “real” ASP.NET 5 application using all the standard platform facilities like DI, Logging, configuration, data protection etc, which means you have to learn less IdentityServer specifics.

What’s not new
Everything else really – IdentityServer4 has (or will have) all the features of IdentityServer3. You still can connect to arbitrary user management back-ends and there will be out of the box support for ASP.NET Identity 3.

We still provide the same architecture focused modelling around users, clients and scopes and still shield you from the low level details to make sure no security holes are introduced.

Database artifacts like reference or refresh tokens are compatible which gives you a nice upgrade/migration story.

Next steps
We will not abandon IdentityServer3 – many people are successfully using it and are happy with it (so are we). We are also aware that not everybody wants to switch its identity platform to “the latest thing” but rather wait a little longer.

But we should also not forget that IdentityServer3 is built on a platform (Katana) which Microsoft is not investing in anymore – and that also applies to the authentication middleware we use to connect to external providers. ASP.NET 5 is the way forward.

We just published beta1 to nuget. There are still many things missing, and what’s there might change. We also started publishing samples (link) to showcase the various features. Please try them out, give us feedback, open issues.

Around the RC2 timeframe there will be also more documentation showing up in our docs as and the ASP.NET documentation site. At some point, there will be also templates for Visual Studio which will provide a starting point for common security scenarios.

IdentityServer3 was such a great success because of all the good community feedback and contributions. Let’s take this to the next level!

Filed under: ASP.NET, IdentityServer, OAuth, OpenID Connect, Uncategorized, WebAPI

Pedro Félix: Using Vagrant to test ASP.NET 5 RC1

The recent Release Candidate 1 (RC1) for ASP.NET 5 includes support for Linux and OS X via .NET Core. After trying it out on OS X, I wanted to do some experiments on Linux as well. For that I used Vagrant to automate the creation and provision of the Linux development environments. In this post I describe the steps required for this task, using OS X as the host (the steps on a Windows host will be similar).

Short version

Start by ensuring Vagrant and VirtualBox are installed on your host machine.
Then open a shell and do the following commands.
The vagrant up may take a while since it will not only download and boot the base virtual machine image, but also provision ASP.NET 5 RC1 and all its dependencies.

git clone (or your own fork URL instead)
cd vagrant-aspnet-rc1
vagrant up
vagrant ssh

After the last command completes you should have a SSH session into a Ubuntu Server with ASP.NET RC1 installed, running on a virtual machine (VM). Port 5000 on the host is mapped into port 5000 on the guest.

The vagrant-aspnet-rc1 host folder is mounted into the /vagrant guest folder, so you can use this to share files between host and guest.
For instance, a ASP.NET project published to vagrant-aspnet-rc1/published on the host will be visible on the /vagrant/published guest path.

For any comment or issue that you have, please raise an issue at

Longer (and perhaps more instructive) version

First, start by installing Vagrant and also VirtualBox, which will be required to run the virtual machine with Linux.

Afterwards, create a new folder (e.g. vagrant-aspnet-rc1) to host the Vagrant configuration.

dotnet pedro$ mkdir vagrant-aspnet-rc1
dotnet pedro$ cd vagrant-aspnet-rc1
vagrant-aspnet-rc1 pedro$

Then, initialize the Vagrant configuration using the init command.

vagrant-aspnet-rc1 pedro$ vagrant init ubuntu/trusty64
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`` for more information on using Vagrant.
vagrant-aspnet-rc1 pedro$ ls

The second parameter, ubuntu/trusty64, is the name of a box available on the Vagrant public catalog, which in this case contains a Ubuntu Server 14.04 LTS.
Notice also how a Vagrantfile file, containing the Vagrant configuration, was created on the current directory. We will be using this file latter on.

The next step is to start the virtual machine.

vagrant-aspnet-rc1 pedro$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/trusty64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/trusty64' is up to date...
==> default: Setting the name of the VM: vagrant-aspnet_default_1451428161431_85889
==> default: Clearing any previously set forwarded ports...
==> default: Fixed port collision for 22 =&amp;amp;gt; 2222. Now on port 2200.
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) =&amp;amp;gt; 2200 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address:
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default: Guest Additions Version: 4.3.34
    default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
    default: /vagrant =&amp;amp;gt; /Users/pedro/code/dotnet/vagrant-aspnet-rc1

As can be seen in the command output, a VM was booted and SSH was configured. So the next step is to open a SSH session into the machine to check if everything is working properly. This is accomplished using the ssh command.

vagrant-aspnet-rc1 pedro$ vagrant ssh
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-74-generic x86_64)

 * Documentation:

  System information as of Tue Dec 29 22:29:41 UTC 2015

  System load:  0.35              Processes:           80
  Usage of /:   3.4% of 39.34GB   Users logged in:     0
  Memory usage: 25%               IP address for eth0:
  Swap usage:   0%

  Graph this data and manage this system at:

  Get cloud support with Ubuntu Advantage Cloud Guest:

0 packages can be updated.
0 updates are security updates.

vagrant@vagrant-ubuntu-trusty-64:~$ hostname
vagrant@vagrant-ubuntu-trusty-64:~$ id
uid=1000(vagrant) gid=1000(vagrant) groups=1000(vagrant)

Notice how we end up with a session into a vagrant-ubuntu-trusty-64 machine, running under the vagrant user.
In addition to setting up SSH, Vagrant also mounted the vagrant-aspnet-rc1 host folder (the one were the Vagrantfile was created) into the /vagrant file on the guest.

vagrant@vagrant-ubuntu-trusty-64:~$ ls /vagrant

We could now start to install ASP.NET 5 following the procedure outlined at However, that would be the “old way of doing things” and would not provide us with a reproducable development environment.
A better solution is to create a provision script, called, and use it with Vagrant.

The provision script is simply a copy of the procedures at, slightly changed to allow unsupervised installation.

#!/usr/bin/env bash

# install dnvm pre-requisites
sudo apt-get install -y unzip curl
# install dnvm
curl -sSL | DNX_BRANCH=dev sh &amp;amp;amp;&amp;amp;amp; source ~/.dnx/dnvm/

# install dnx pre-requisites
sudo apt-get install -y libunwind8 gettext libssl-dev libcurl4-openssl-dev zlib1g libicu-dev uuid-dev
# install dnx via dnvm
dnvm upgrade -r coreclr

# install libuv from source
sudo apt-get install -y make automake libtool curl
curl -sSL | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.4.2
sudo sh
sudo ./configure
sudo make
sudo make install
sudo rm -rf /usr/local/src/libuv-1.4.2 &amp;amp;amp;&amp;amp;amp; cd ~/
sudo ldconfig

The next step is to edit the Vagrantfile so this provision script is run automatically by Vagrant.
We also change the port forwarding rule so that is matches the default 5000 port used by ASP.NET.

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config| = &amp;amp;quot;ubuntu/trusty64&amp;amp;quot;
  config.vm.provision :shell, path: &amp;amp;quot;;amp;quot;, privileged: false &amp;amp;quot;forwarded_port&amp;amp;quot;, guest: 5000, host: 5000

To check that everything is properly configured we redo the whole process by destroying the VM and creating it again.

vagrant-aspnet-rc1 pedro$ vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...
vagrant-aspnet-rc1 pedro$ vagrant up
( ... lots of things that take a while to happen ... )

Finally, do vagrant ssh and check that dnx is fully functional.

How about publish with runtime?

Instead of having to previously provision ASP.NET, wouldn’t it be nice to include all the dependencies on the published project so that we could deploy it on a plain vanilla Ubuntu or Debian machine?
Well, one one hand it is possible to configure the publish process to also include the runtime, via the --runtime parameter.

dnu publish --out ~/code/dotnet/vagrant-ubuntu/published --no-source --runtime dnx-coreclr-linux-x64.1.0.0-rc1-update1

On the other hand, in order to have the Linux DNX runtime available on OS X we just need to explicitly specify the OS on the dnvm command

dnvm install latest -OS linux -r coreclr

Unfortunately, this approach does not work because the published runtime is not self-sufficient.
For it to work properly it still requires some dependencies to be previously provisioned on the deployed machine.
This can be seen if we try to run the ASP.NET project

vagrant@vagrant-ubuntu-trusty-64:~$ /vagrant/published/approot/web
failed to locate libcoreclr with error cannot open shared object file: No such file or directory
vagrant@vagrant-ubuntu-trusty-64:~$ Connection to closed by remote host.
Connection to closed.

Notice how the failed to be opened.
So, for the time being, we need to provision at least the runtime dependencies on the deployed machine.
The runtime itself can be contained in the published project.

Henrik F. Nielsen: New Year Updates to ASP.NET WebHooks Preview (Link)

Posted New Year Updates to ASP.NET WebHooks Preview about the latest update of ASP.NET WebHooks. It has a couple of interesting new features on the WebHooks sender side – that is, when you want to send WebHooks to others when some event happens – including:

  1. Sending events to all users registered for a particular event.
  2. Scaling out and load balancing events using persistent queues.

For the full story, please see New Year Updates to ASP.NET WebHooks Preview.

Happy New Year!


Dominick Baier: Validating Scopes in ASP.NET 4 and 5

OAuth 2.0 scopes are a way to model (API) resources. This allows you to give logical “names” to APIs that clients can use to request tokens for.

You might have very granular scopes like e.g. api1 & api2, or very coarse grained like application.backend. Some people use functional names e.g. contacts.api and customers.api (which might or might not span multiple physical APIs) – some group by criteria like public or internal only. Some even sub-divide a single API – e.g. and calendar.readwrite. It is totally up to you (this is how Google uses scopes).

At the end of the day, the access token (be it self-contained or referenced) will be associated with the scopes the client was authorized for (and optionally – the user consented to).

IdentityServer does that by including claims of type scope in the access token – so really any technique that allows checking the claims of the current user will do.

As a side note – there is also a spec that deals with return codes for failed scope validation. In short – this should return a 403 instead of a 401.

We ourselves had some iterations in our thinking how we deal with scopes – here’s a summary and some options.


The most common way we do scope checking is via our token validation middleware (source/nuget), which combines token and scope validation into a single step:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        Authority = "https://localhost:44333/core",
        RequiredScopes = new[] { """calendar.readwrite" },

This would validate the token and require that either the or calendar.readwrite scope claims are present.

This middleware also emits the right response status code, Www-Authenticate header and respects CORS pre-flight requests.

For finer granularity we also once wrote a Web API authorization attribute – [ScopeAuthorize] that you can put on top of controllers and actions (source).

As mentioned before – you can always check inside your code for scope claims yourself using the claims collection.


We will have the same “all in one” IdentityServer token validation middleware for ASP.NET 5 – but this time split up into separate middleware that can be also used stand-alone (I wrote about the introspection aspect of it in my last post).

The scope validation part (source/nuget) of it looks like this:


This has the same OR semantics as described above.

You can also use the new ASP.NET 5 authorization API to do scope checks – e.g. as a global policy:

public void ConfigureServices(IServiceCollection services)
    var scopePolicy = new AuthorizationPolicyBuilder()
    services.AddMvc(options =>
        options.Filters.Add(new AuthorizeFilter(scopePolicy));

..or as a named policy to decorate individual controllers and actions:

services.AddAuthorization(options =>
        policy => policy.RequireClaim("scope"""));
        policy => policy.RequireClaim("scope""calendar.readwrite"));

and use it e.g. like that:

public class CalendarControllerController
    public IActionFilter Get() { ... }
    public IActionFilter Put() { ... }

One last remark: We get this question a lot – scopes are not used for authorizing users. They are used for modeling resources (and optionally to compose the consent screen as well as to specify which client might have access to these resources).


Filed under: ASP.NET, IdentityModel, IdentityServer, Katana, OAuth, Uncategorized, WebAPI

Pedro Félix: A first look at .NET Core and the dotnet CLI tool

A recent post by Scott Hanselman triggered my curiosity about the new dotnet Command Line Interface (CLI) tool for .NET Core, which aims to be a “cross-platform general purpose managed framework”. In this post I present my first look on using .NET Core and the dotnet tool on OS X.


For OS X, the recommended installation procedure is to use the “official PKG”. Unfortunately, this PKG doesn’t seem to be signed so trying to run it directly from the browser will result in an error. The workaround is use Finder to locate the downloaded file and then select “Open” on the file. Notice that this PKG requires administrative privileges to run, so proceed at your own risk (the .NET Core home page uses a https URI and the PKG is hosted on Azure Blob Storage, also using HTTPS –

After installation, the dotnet tool will be available on your shell.

~ pedro$ which dotnet

I confess that I was expecting the recommended installation procedure to use homebrew instead of a downloaded PKG.

Creating the application

To create an application we start by making an empty folder (e.g. HelloDotNet) and then run dotnet new on it.

dotnet pedro$ mkdir HelloDotNet
dotnet pedro$ cd HelloDotNet
HelloDotNet pedro$ dotnet new
Created new project in /Users/pedro/code/dotnet/HelloDotNet.

This newcommand creates three new files in the current folder.

HelloDotNet pedro$ tree .
├── NuGet.Config
├── Program.cs
└── project.json

0 directories, 3 files

The first one, NuGet.Config is an XML file containing the NuGet package sources, namely the feed containing .NET Core.

<?xml version="1.0" encoding="utf-8"?>
<!--To inherit the global NuGet package sources remove the <clear/> line below -->
<clear />
<add key="dotnet-core" value="" />
<add key="" value="" />

The second one is a C# source file containing the classical static void Main(string[] args) application entry point.

HelloDotNet pedro$ cat Program.cs
using System;

namespace ConsoleApplication
    public class Program
        public static void Main(string[] args)
            Console.WriteLine(&amp;amp;amp;amp;quot;Hello World!&amp;amp;amp;amp;quot;);

Finally, the third file is the project.json containing the project definitions, such as compilation options and library dependencies.

HelloDotNet pedro$ cat project.json
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true

"dependencies": {
"NETStandard.Library": "1.0.0-rc2-23616"

"frameworks": {
"dnxcore50": { }

Resolving dependencies

The next step is to ensure all dependencies required by our project are available. For that we use the restore command.

HelloDotNet pedro$ dotnet restore
Microsoft .NET Development Utility CoreClr-x64-1.0.0-rc1-16231

  OK 778ms
Restore complete, 40937ms elapsed

NuGet Config files used:

Feeds used:

    69 package(s) to /Users/pedro/.dnx/packages

After figuratively downloading almost half of the Internet, or 69 packages to be more precise, the restore process ends stating that the required dependencies where installed at ~/.dnx/packages.
Notice the dnx in the path, which shows the DNX heritage of the dotnet tool. I presume this names will change before the RTM version. Notice also that the only thing added to the current folder is the project.lock.json containing the complete dependency graph created by the restore process based on the direct dependencies.

HelloDotNet pedro$ tree .
├── NuGet.Config
├── Program.cs
├── project.json
└── project.lock.json

0 directories, 4 files

Namely, no dependencies where copied to the local folder.
Instead the global ~/.dnx/packages/ repository is used.

Running the application

After changing the greetings message to Hello dotnet we can run the application using the run command.

HelloDotNet pedro$ dotnet run
Hello dotnet!

Looking again into the current folder we notice that not extra files where created when running the application.

HelloDotNet pedro$ tree .
├── NuGet.Config
├── Program.cs
├── project.json
└── project.lock.json

0 directories, 4 files

This happens because the compilation produces in-memory assemblies, which aren’t persisted on any file. The CoreCLR virtual machine uses this in-memory assemblies when running the application.

Well, it seems I was wrong: the dotnet run command does indeed produce persisted files. This is a change when compare with dnx, which  did use in-memory assemblies.

We can see this behaviour by  using the -v switch

HelloDotNet pedro$ dotnet -v run
Running /usr/local/bin/dotnet-compile --output "/Users/pedro/code/dotnet/HelloDotNet/bin/.dotnetrun/3326e7b6940b4d50a30a12a02b5cdaba" --temp-output "/Users/pedro/code/dotnet/HelloDotNet/bin/.dotnetrun/3326e7b6940b4d50a30a12a02b5cdaba" --framework "DNXCore,Version=v5.0" --configuration "Debug" /Users/pedro/code/dotnet/HelloDotNet
Process ID: 20580
Compiling HelloDotNet for DNXCore,Version=v5.0
Running /usr/local/bin/dotnet-compile-csc @"/Users/pedro/code/dotnet/HelloDotNet/bin/.dotnetrun/3326e7b6940b4d50a30a12a02b5cdaba/dotnet-compile.HelloDotNet.rsp"
Process ID: 20581
Running csc -noconfig @"/Users/pedro/code/dotnet/HelloDotNet/bin/.dotnetrun/3326e7b6940b4d50a30a12a02b5cdaba/dotnet-compile-csc.rsp"
Process ID: 20582

Compilation succeeded.
0 Warning(s)
0 Error(s)

Time elapsed 00:00:01.4388306

Running /Users/pedro/code/dotnet/HelloDotNet/bin/.dotnetrun/3326e7b6940b4d50a30a12a02b5cdaba/HelloDotNet
Process ID: 20583
Hello dotnet!

Notice how it first calls the compile command (addressed in the next section) before running the application.

Compiling the application

The dotnet tool also allows the explicit compilation via its compile command.

HelloDotNet pedro$ dotnet compile
Compiling HelloDotNet for DNXCore,Version=v5.0

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

Time elapsed 00:00:01.4249439

The resulting artifacts are stored in two new folders

HelloDotNet pedro$ tree .
├── NuGet.Config
├── Program.cs
├── bin
│   └── Debug
│       └── dnxcore50
│           ├── HelloDotNet
│           ├── HelloDotNet.deps
│           ├── HelloDotNet.dll
│           ├── HelloDotNet.pdb
│           └── NuGet.Config
├── obj
│   └── Debug
│       └── dnxcore50
│           ├── dotnet-compile-csc.rsp
│           ├── dotnet-compile.HelloDotNet.rsp
│           └── dotnet-compile.assemblyinfo.cs
├── project.json
└── project.lock.json
6 directories, 12 files

The bin/Debug/dnxcore50 contains the most interesting outputs from the compilation process. The HelloDotNet is a native executable, visible by a _main symbol inside of it, that loads the CoreCLR virtual machine and uses it to run the application.

HelloDotNet pedro$ otool -tvV bin/Debug/dnxcore50/HelloDotNet | grep _main

otool is the object file displaying tool for OS X.

We can also see that the libcoreclr dynamic library is used by this bootstrap executable

HelloDotNet pedro$ otool -tvV bin/Debug/dnxcore50/HelloDotNet | grep libcoreclr.dylib
00000001000025b3    leaq    0x7351(%rip), %rsi      ## literal pool for: &amp;amp;amp;amp;quot;libcoreclr.dylib&amp;amp;amp;amp;quot;
00000001000074eb    leaq    0x2419(%rip), %rsi      ## literal pool for: &amp;amp;amp;amp;quot;libcoreclr.dylib&amp;amp;amp;amp;quot;
000000010000784b    leaq    0x20b9(%rip), %rsi      ## literal pool for: &amp;amp;amp;amp;quot;libcoreclr.dylib&amp;amp;amp;amp;quot;

The HelloDotNet.dll file is a .NET assembly (has dll extension and starts with the 4d 5a magic number) containing the compiled application.

HelloDotNet pedro$ hexdump -n 32 bin/Debug/dnxcore50/HelloDotNet.dll
0000000 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00
0000010 b8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00

Directly executing the HelloDotNet file runs the application.

HelloDotNet pedro$ bin/Debug/dnxcore50/HelloDotNet
Hello dotnet!

We can also see that the CoreCLR is hosted in executing process by examining the loaded libraries.

dotnet pedro$ ps | grep Hello
18981 ttys001    0:00.23 bin/Debug/dnxcore50/HelloDotNet
19311 ttys002    0:00.00 grep Hello
dotnet pedro$ sudo vmmap 18981 | grep libcoreclr
__TEXT                 0000000105225000-000000010557a000 [ 3412K] r-x/rwx SM=COW  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__TEXT                 000000010557b000-000000010575a000 [ 1916K] r-x/rwx SM=COW  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__TEXT                 000000010575b000-0000000105813000 [  736K] r-x/rwx SM=COW  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__LINKEDIT             0000000105859000-00000001059e1000 [ 1568K] r--/rwx SM=COW  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__TEXT                 000000010557a000-000000010557b000 [    4K] rwx/rwx SM=PRV  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__TEXT                 000000010575a000-000000010575b000 [    4K] rwx/rwx SM=PRV  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__DATA                 0000000105813000-0000000105841000 [  184K] rw-/rwx SM=PRV  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib
__DATA                 0000000105841000-0000000105859000 [   96K] rw-/rwx SM=ZER  /usr/local/share/dotnet/runtime/coreclr/libcoreclr.dylib

Native compilation

One of the most interesting features on .NET Core and the dotnet tool is the ability to create a native executable containing the complete program and not just a boot strap into the virtual machine. For that, we use the --native option on the compile command.

HelloDotNet pedro$ ls
NuGet.Config        Program.cs      project.json        project.lock.json
HelloDotNet pedro$ dotnet compile --native
Compiling HelloDotNet for DNXCore,Version=v5.0

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

Time elapsed 00:00:01.1267350

The output of this compilation is a new native folder containing another HelloDotNet executable.

HelloDotNet pedro$ tree .
├── NuGet.Config
├── Program.cs
├── bin
│   └── Debug
│       └── dnxcore50
│           ├── HelloDotNet
│           ├── HelloDotNet.deps
│           ├── HelloDotNet.dll
│           ├── HelloDotNet.pdb
│           ├── NuGet.Config
│           └── native
│               ├── HelloDotNet
│               └── HelloDotNet.dSYM
│                   └── Contents
│                       ├── Info.plist
│                           └── Resources
│                               └── DWARF
│                                   └── HelloDotNet
├── obj
│   └── Debug
│   └── dnxcore50
│   └── HelloDotNet.obj
├── project.json
└── project.lock.json

11 directories, 13 files

Running the executable produces the expected result

HelloDotNet pedro$ bin/Debug/dnxcore50/native/HelloDotNet
Hello dotnet!

At first sight, this new executable is rather bigger that the first one, since it isn’t just a bootstrap into the virtual machine: it contains the complete application.

HelloDotNet pedro$ ls -la bin/Debug/dnxcore50/HelloDotNet
-rwxr-xr-x  1 pedro  staff  66368 Dec 28 10:12 bin/Debug/dnxcore50/HelloDotNet
HelloDotNet pedro$ ls -la bin/Debug/dnxcore50/native/HelloDotNet
-rwxr-xr-x  1 pedro  staff  987872 Dec 28 10:12 bin/Debug/dnxcore50/native/HelloDotNet

There are two more signs that this new executable is the application. First, there aren’t any references to the libcoreclr dynamic library.

HelloDotNet pedro$ otool -tvV bin/Debug/dnxcore50/HelloDotNet | grep libcoreclr.dylib
00000001000025b3    leaq    0x7351(%rip), %rsi      ## literal pool for: &amp;amp;amp;amp;quot;libcoreclr.dylib&amp;amp;amp;amp;quot;
00000001000074eb    leaq    0x2419(%rip), %rsi      ## literal pool for: &amp;amp;amp;amp;quot;libcoreclr.dylib&amp;amp;amp;amp;quot;
000000010000784b    leaq    0x20b9(%rip), %rsi      ## literal pool for: &amp;amp;amp;amp;quot;libcoreclr.dylib&amp;amp;amp;amp;quot;
HelloDotNet pedro$ otool -tvV bin/Debug/dnxcore50/native/HelloDotNet | grep libcoreclr.dylib
HelloDotNet pedro$

Second, it contains a ___managed__Main symbol with the static void Main(string[] args) native code

HelloDotNet pedro$ otool -tvV bin/Debug/dnxcore50/native/HelloDotNet | grep -A 8 managed__Main:
0000000100001b20    pushq   %rax
0000000100001b21    movq    ___ThreadStaticRegionStart(%rip), %rdi
0000000100001b28    movq    (%rdi), %rdi
0000000100001b2b    callq   _System_Console_System_Console__WriteLine_13
0000000100001b30    nop
0000000100001b31    addq    $0x8, %rsp
0000000100001b35    retq
0000000100001b36    nop

In addition to the HelloDotNet executable, the compile --native command also creates a bin/Debug/dnxcore50/native/HelloDotNet.dSYM folder the native debug information.

Unfortunately, the .NET Core native support seems to be in the very early stages and I was unable to compile anything more complex than a simple “Hello World”. However, I’m looking forward to further developments in this area.

Dominick Baier: OAuth 2.0 Token Introspection Middleware for ASP.NET 5

In my last post I described the value of reference tokens and how the OAuth 2.0 token introspection spec (aka rfc7662) gives us a standard way of using them.

Over the christmas break I worked on an ASP.NET 5-based middleware for token introspection – it is pretty simple to use:

app.UseOAuth2IntrospectionAuthentication(options =>
    options.AutomaticAuthenticate = true;
    options.ScopeName = "api1";
    options.ScopeSecret = "secret";
    options.Authority = "";

If your token issuer supports discovery, all you need to do is to pass in the base URL – the token introspection endpoint is then found via metadata (there is also a way to explicitly pass in the endpoint address).

ScopeName and ScopeSecret are used to authenticate against the introspection endpoint (you can also use an HTTP message handler if you need more control over the wire format).

The result will – as usual – get turned into a claims principal and your pipeline/business logic will have access to the claims.

The token introspection spec is quite new – but needless to say, this works with IdentityServer.

source code / nuget package

PS. This is the first beta version – there is definitely room for improvement. One thing that is missing right now is caching – but I will get to that soon. Please use github to give feedback. thanks!

Filed under: ASP.NET, IdentityServer, OAuth, WebAPI

Henrik F. Nielsen: Sharing Windows 10 Store Apps with your Family

This is not a typical blog subject of mine, but after having gone through it myself, I thought it could be of interest to others as well. The challenge started when I, like many others, bought a nice new Windows 10 laptop for the family in time for the holidays. I wanted to set it up so that our two children could use each their Microsoft Account in order not to step on each other and to benefit from the age appropriate content filters provided by the Windows Store.

The issue is that Windows Store apps are not shared between users, so unlike ‘classic’ Windows desktop apps, you can’t install them once and have them be available to all users on a particular device. That is, if I buy a Windows Store app and install it on the PC, it is not automatically made available to anybody else. The Windows Store Licensing Model allows you to install apps across a number of devices and users. However, before you can actually share your apps, there are a few hoops you need to go through first. Hence this blog!

Creating a Family of Microsoft Accounts

The first step is to create Microsoft Accounts for your family members and configure them as being part of the same family. Assuming you already have a Microsoft Account, you can go to Your Family and add your children and other adults with each their Microsoft Accounts. It should look something like this:


In addition to setting up your family, you can also control a lot of settings including what your kids have access to, what time of day they have access, etc.

Enabling Family Members to Sign in to your Device

The second step is to allow all family members to sign into your device. Sign in as you and then go to All Settings in the Action Center:


In Settings, select Accounts and then Family and other users where you should see your family members. To enable them to sign in to the device, click on each one and select Allow. You can also change the account type if you want, but typically they should not be administrators.


In addition to enabling your family to sign in, I recommend that each member sets up their own PIN code for signing in. In general, it is a lot easier to remember a PIN than a full password. Each member can set up a PIN by going to the same Accounts settings, but instead select Sign-in options and then set the PIN:


Sharing Windows Store Apps

Each member of your family can now sign in to your device using a short PIN but each will see their own Windows Store tailored to them. To share apps with a family member, you first sign in as that member and then change the account used to interact with the Windows Store. That is, while signed in as family member, you switch the account used to talk to the Windows Store enabling you to install your apps into your family member’s account. This is a little tricky, so let’s do it step-by-step.

First sign in as the family member you want to share the app with, then open the Windows Store. You will see the family member’s account in the upper right corner:


After selecting the account entry, you will see something like this:


Click on the account and then select Sign out:


Now select the account again and sign in to the store as you:


As of Dec 25 2015, there seems to be a bug in the Windows Store sign in process as it may ask for your PIN code but it actually wants your family member’s PIN code. That is, at least at the time of this writing, use the PIN of the signed in family member even though it asks for your PIN!


You should now be signed into the Windows Store while the overall account is still that of your family member. You can now either buy and share a new app or share an already bought app with that family member.  In the first case you just go through the normal payment process as you and hit Install to share the app with your family member.

If you have already bought the app then you should see something like this: “You own this product and can install it on this device”. Hit Install to share the app with your family member.

Once done you can flip the Windows Store sign in back to the family member.

Hope this helps!


Pedro Félix: How to fail in HTTP APIs

In the HTTP protocol, clients use request messages to perform operations, defined by request methods, on resources identified by request URIs.
However, servers aren’t always able or willing to completely and successfully perform these requested operations.
The subject of this post is to present proper ways for HTTP servers to express these non-success outcomes.

Status codes

The primary way to communicate the request completion result is via the response message’s status code.
The status code is a three-digit integer divided into five classes, (list adapted from RFC 7231):

  • “1xx (Informational): The request was received, continuing process”
  • “2xx (Successful): The request was successfully received, understood, and accepted”
  • “3xx (Redirection): Further action needs to be taken in order to complete the request”
  • “4xx (Client Error): The request contains bad syntax or cannot be fulfilled”
  • “5xx (Server Error): The server failed to fulfill an apparently valid request”

The last two of these five classes, 4xx and 5xx, are used to represent non-success outcomes.
The 4xx class is used when the request is not completely understood by the server (e.g. incorrect HTTP syntax) or fails to satisfy the server requirements for successful handling (e.g. client must be authenticated).
These are commonly referred as client errors.
On the other hand, 5xx codes should be strictly reserved for server errors, i.e., situations where the request is not successfully completed due to a abnormal behavior on the server.

Here are some of basic rules that I tend to use when choosing status codes:

  • Never use a 2xx to represent a non-success outcome.
    Namely, always use a 4xx or 5xx to represent those situations, except when the request can be completed by taking further actions, in which a 3xx could be used.
  • Reserve the 5xx status code for errors where the fault is indeed on the server side.
    Examples are infrastructural problems, such as the inability to connect to external systems, such as a database or service, or programming errors such as an indexation out of bounds or a null dereference.
    Inability to successfully fulfill a request due to malformed or invalid information in the request must instead be signaled with 4xx status codes.
    Some examples are: the request URI does not match any known resource; the request body uses an unsupported format; the request body has invalid information.

As a rule of thumb, and perhaps a little hyperbolically, if an error does not require waking up someone in the middle of night then probably it shouldn’t be signaled using a 5xx class code, because it does not signals a server malfunction.

The HTTP specification also defines a set of 41 concrete status codes and associated semantics, from which 19 belong to the 4xx class and 6 belong to the 5xx class.
These standard codes are a valuable resource for the Web API designer, which should simultaneously respect and take advantage of this semantic richness when designing the API responses.
Here are some rule of thumb:

  • Use 500 for server unexpected errors, reserving 503 for planned service unavailability.
  • Reserve the 502 and 504 codes for reverse proxies.
    A failure when contacting an internal third-party system should still use a 500 when this internal system is not visible to the client.
  • Use 401 when the request has invalid or missing authentication/authorization information required to perform the operation.
    If this authentication/authorization information is valid but the operation is still not allowed, then use 403.
  • Use 404 when the resource identified by the request URI does not exist or the server does not want to reveal its existence.
  • Use 400 if parts of the request are not valid, such as fields in the request body.
    For invalid query string parameters I tend to use 404 since the query string is an integral part of the URI, however using 400 is also acceptable.

HTTP status codes are extensible, meaning that other specifications, such as WebDav can define additional values.
The complete list of codes is maintained by IANA at the Hypertext Transfer Protocol (HTTP) Status Code Registry.
This extensibility means that HTTP clients and intermediaries are not obliged to understand all status codes.
However, they must understand each code class semantics.
For instance, if a client receives the (not yet defined) 499 status code, then it should treat it as a 400 and not as a 200 or a 500.

Despite its richness, there aren’t HTTP status code for all possible failure scenarios.
Namely, by being uniform, these status code don’t have any domain-specific semantics.
However, there are scenarios where the server needs to provide the client with a more detailed error cause, namely using domain-specific information.
Two common anti-patterns are:

  • Redefining the meaning of standard code for a particular set of resources.
    This solution breaks the uniform interface contract: the semantics of the status code should be the same independently of the request’s target resource.
  • Using an unassigned status code in the 4xx or 5xx classes.
    Unless this is done via a proper registration of the new status code in IANA, this decision will hinder evolution and most probably will collide with future extensions to the HTTP protocol.

Error representations

Instead of fiddling with the status codes, a better solution is to use the response payload to provide a complementary representation of the error cause.
And yes, a response message may (and probably should) contain a body even when it represents an error outcome – response bodies are not exclusive of successful responses.

The Problem Details for HTTP APIs is an Internet Draft defining JSON and XML formats to represent such error information.
The following excerpt, taken from the draft specification, exemplifies how further information can be conveyed on a response with 403 (Forbidden) status code, stating the domain specific reason for the request prohibition.

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
Content-Language: en

    "type": "",
    "title": "You do not have enough credit.",
    "detail": "Your current balance is 30, but that costs 50.",
    "instance": "/account/12345/msgs/abc",
    "balance": 30,
    "accounts": ["/account/12345","/account/67890"]

The application/problem+json media type informs the receiver that the payload is using this format and should be processed according to its rules.
The payload is comprised by a JSON object containing both fields defined by the specification and fields that are kept domain specific.
The type, title, detail and instance are of the first type, having their semantics defined by the specification

  • type – URI identifier defining the domain-specific error type. If it is URL, then its dereference can provide further information on the error type.
  • title – Human-readable description of the error type.
  • detail – Human-readable description of this specific error occurrence.
  • instance – URI identifier for this specific error occurrence.

On the other hand, the balance and accounts fields are domain specific extensions and their semantics is scoped to the type identifier.
This allows the same extensions to be used by different Web APIS with different semantics as long as the use type identifiers are different.
I recommend an HTTP API to have a central place documenting all type values as well as the domain specific fields associated to each one of these values.

Using this format presents several advantages when compared with constantly “reinventing the wheel” with ad-hoc formats:

  • Taking advantage of rich and well defined semantics for the specification defined fields – type, title, detail and instance.
  • Making the non-success responses easier to understand and handle, namely for developers that are familiar with this common format.
  • Being able to use common libraries to produce and consume this format.

When using a response payload to represent the error details one might wonder if there is still a need to use proper 4xx or 5xx class codes to represents error.
Namely, can’t we just use 200 for every response, independently of the outcome and have the client use the payload to distinguish them?
My answer is an emphatic no: using 2xx status to represent non-success breaks the HTTP contract, which can have consequences on the behavior of intermediary components.
For instance, a cache will happily cache a 200 response even it’s payload is in the application/problem+json format.
Notice that the operation of most intermediaries is independent of the messages payload.
And yes, HTTP intermediaries are still relevant on an HTTPS world: intermediaries can live before (e.g. client caching) and after (e.g. output caching) the TLS connection endpoints.

The HTTP protocol and associated ecosystem provides richer ways to express non-success outcomes, via response status codes and error representations.
Taking advantage of those is harnessing the power of the Web for HTTP APIs.

Additional Resources

Dominick Baier: Reference Tokens and Introspection

Access tokens can come in two shapes: self-contained and reference.

Self-contained tokens are using a protected, time-limited data structure that contains metadata and claims to communicate the identity of the user or client over the wire. A popular format would be JSON Web Tokens (JWT). The recipient of a self-contained token can validate the token locally by checking the signature, expected issuer name and expected audience or scope.

Reference tokens (sometimes also called opaque tokens) on the other hand are just identifiers for a token stored on the token service. The token service stores the contents of the token in some data store, associates it with an infeasible-to-guess id and passes the id back to the client. The recipient then needs to open a back-channel to the token service, send the token to a validation endpoint, and if valid, retrieves the contents as the response.

A nice feature of reference tokens is that you have much more control over their lifetime. Where a self-contained token is hard to revoke before its expiration time, a reference token only lives as long as it exists in the STS data store. This allows for scenarios like

  • revoking the token in an “emergency” case (lost phone, phishing attack etc.)
  • invalidate tokens at user logout time or app uninstall

The downside of reference tokens is the needed back-channel communication from resource server to STS.

This might not be possible from a network point of view, and some people also have concerns about the extra round-trips and the load that gets put on the STS. The last two issues can be easily fixed using caching.

I presented this concept of the last years to many of my customers and the preferred architecture is becoming more and more like this:

If the token leaves the company infrastructure (e.g. to a browser or a mobile device), use reference tokens to be in complete control over lifetime. If the token is used internally only, self contained tokens are fine.

I am also mentioning (and demo-ing) reference tokens here starting minute 36.

IdentityServer3 supports the reference token concept since day one. You can set the access token type to either JWT or Reference per client, and the ITokenHandleStore interface takes care of persistence and revocation of reference tokens.

For validating reference tokens we provide a simple endpoint called the access token validation endpoint. This endpoint is e.g. used by our access token validation middleware, which is clever enough to distinguish between self-contained and reference tokens and does the validation either locally or using the endpoint. All of this is completely transparent to the API.

You simply specify the Authority (the base URL of IdentityServer) and the middleware will use that to pull the configuration (keys, issuer name etc) and construct the URL to the validation endpoint:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        Authority = "https://localhost:44333/core",
        RequiredScopes = new[] { "api1" }

The middleware also supports caching and scope validation – check the docs here.

There are also multiple ways to revoke a token – e.g. through the application permission self-service page, the token revocation endpoint, by writing code against the ITokenHandle store interface (e.g. from your user service to clean up tokens during logout) or by simply deleting the token from your data store.

One thing our validation endpoint does not support is authentication – this is a non issue as long as you don’t want to use the reference token mechanism for confidentiality.

Token Introspection
Many token services have a reference token feature, and all of them, like us, invented their own proprietary validation endpoint. A couple of weeks ago RFC 7662 – “OAuth 2.0 Token Introspection”, which defines a standard protocol, has been published.

IdentityServer3 v2.2 as well as the token validation middleware starting with v2.3 have support for it.

The most important difference is that authentication is now required to access the introspection endpoint. Since this endpoint is not accessed by clients, but by resource servers, we hang the credential (aka secret) off the scope definition, e.g.:

var api1Scope = new Scope
    Name = "api1",
    Type = ScopeType.Resource,
    ScopeSecrets = new List<Secret>
        new Secret("secret".Sha256())

For secret parsing and validation we use the same extensible mechanism that we use for client secrets. That means you can use shared secrets, client certificates or anything custom.

This also means that only scopes that are included in the access token can introspect the token. For any other scope, the token will simply look like invalid.

IdentityModel has a client library for the token introspection endpoint which pretty much self explanatory:

var client = new IntrospectionClient(
var request = new IntrospectionRequest
    Token = accessToken
var result = client.SendAsync(request).Result;
if (result.IsError)
    if (result.IsActive)
        result.Claims.ToList().ForEach(c => Console.WriteLine("{0}: {1}",
            c.Item1, c.Item2));
        Console.WriteLine("token is not active");

This client is also used in the validation middleware. Once we see the additional secret configuration, the middleware switches from the old validation endpoint to the new introspection endpoint:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        Authority = "https://localhost:44333/core",
        RequiredScopes = new[] { "api1" },
        ClientId = "api1",
        ClientSecret = "secret"

Once you switched to introspection, you can disable the old validation endpoint on the IdentityServerOptions:

var idsrvOptions = new IdentityServerOptions
    Factory = factory,
    SigningCertificate = Cert.Load(),
    Endpoints = new EndpointOptions
        EnableAccessTokenValidationEndpoint = false

Reference tokens are a real problem solver for many situations and the inclusion of the introspection spec and authentication makes this mechanism even more robust and a good basis for future features around access token lifetime management (spoiler alert).


Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OWIN, Uncategorized, WebAPI

Dominick Baier: IdentityServer3 v2.2

Yesterday we published v2.2 to nuget and github. You can see the release notes here.

Besides a couple of bug fixes and refinements – the big features are support for the introspection specification (rfc 7662) and the OpenID Connect HTTP-based logout specification.

The next post will give you some perspective on introspection and Brock will write up the new features around logout. stay tuned!

PS. Brock and I will be at NDC London in January. If you are interested in identity & access control with Katana and ASP.NET (4&5) – join us!

Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, Uncategorized, WebAPI

Henrik F. Nielsen: Using ASP.NET WebHooks with IFTTT and Zapier to Monitor Twitter and Google Sheets (Link)

Posted the blog Using ASP.NET WebHooks with IFTTT and Zapier to Monitor Twitter and Google Sheets describing how to use ASP.NET WebHooks in connection with IFTTT and Zapier. Both IFTTT and Zapier provide a huge number of integrations in areas such as productivity, automotive, blogging, CRM, commerce, project management, IoT, social, mobile, collaboration, and much more. In this blog we’ll show how to leverage this to build two simple integrations – one with IFTTT and one with Zapier – and then use ASP.NET WebHooks to receive the result. For IFTTT we wire it up to Twitter monitoring when a tweet is sent, and for Zapier we wire it up to a Google Sheet monitoring when a row is added. These are of course just examples – the possibilities for integrations are endless!

Have fun!


Darrel Miller: A Fresh Coat Of REST Paint On A SOAP Stack

In my experience, once a SOAP API gets into production and is working, nobody wants to touch it.  They can be very finicky beasts. Sometimes the most innocuous update can stop a client application in its  tracks.  Exposing a SOAP API to external customers just raises the risk level.  One approach I frequently see is putting an HTTP or REST API in front of the SOAP stack.  This adds a layer of indirection that allows some wiggle room into the exposed API.  This blog posts talks about some of the issues to consider when trying to build a resource oriented HTTP API as a façade to a SOAP API.


Anatomy Of A SOAP Call

Here is an example of a SOAP request:


Most SOAP requests you will see in the wild are HTTP POST requests.  Although the SOAP specification did define a WebMethod feature to allow use of other HTTP methods it was rarely implemented.  There is value in changing the request method to more accurately reflect the characteristics of the request.

SOAP requests are usually targeted at a single URL that represents the entire service.  In our example case, the service is identified by . Different operations in the service are identified by the contents of the request payload.  In a HTTP oriented design, each interesting concept, aka resource, is identified by a URL and the HTTP methods are used to perform a variety of operations on that resource.

The operation parameters are also part of the request payload, whereas with HTTP style APIs, the parameters are part of either the URL path or query string.

The corresponding response to the HTTP request is shown below:


The response body from a SOAP request always uses an XML envelope to surround the actual response body.  In this example, the actual XML response is escaped using entity names to avoid any potential clashes with the envelope.  The success or failure of the response is difficult to determine in any standardized way because result codes are often defined in ways that are specific to the particular API or operation.

Let The Resources Multiply

Possibly the first and easiest change that can be made is to lift the action out of the request body and into the URL.  The most mechanical thing we could do for our example request is,{?CityName,CountryName}

This would work and is a perfectly valid resource identifier.  However,  there are a few improvements that are possible. 

Legacy Cruft

The .asmx extension is a remnant of the days when web resources were commonly to stored as files on disk of a web server.  The convention continued into the services world as a way of routing requests to particular handling code.  However, most modern web frameworks don't need us to expose these implementation details anymore. 

Redundancy and Contradiction

The second change we can make is to remove the Get prefix.  Developers that are using HTTP to make requests to an API will learn there are a predefined set of methods that can be used with a resource.  The GET method is one of those methods and maps most closely to the read-only nature of this operation.  Once we are using the GET HTTP method, having Get in the resource identifier is redundant.  What is worse is if the API decides to implement one of the HTTP other methods on the resource then Get becomes contradictory.  Doing a PUT to a GetWeather resource becomes very confusing!

Our new resource identifier becomes:{?CityName,CountryName}

Service Boundaries

There seems to be some additional redundancy between GlobalWeather and Weather.  In the SOAP oriented world, it was common to group a set of operations into a logical service, that has a corresponding implementation with the same boundary.  This practice has followed into the HTTP world through the use of the term API, but it is not actually necessary.  As long as a resource identifier can be mapped to its corresponding implementation, there is no need to expose to the outside world what are the implementation service boundaries
So, we could just drop the globalweather path segment:{?CityName,CountryName}

Sometimes it does make sense to logically group resources, and using path segments is the ideal way to do this.  However, don't assume that the most logical grouping to the consumer of the resources maps identically to the API implementation boundaries.

Parameterized Resource Space

It is common to translate parameters to service methods into query string parameters and in many cases that is the optimum solution.  There is however a scenario where it makes more sense to move the parameters into the path.  The one characteristic that distinguishes path segments from query string parameters is that path segments define a hierarchical resource space, whereas query string parameters are independent dimensions

In our example, country name and city name are a natural hierarchy.  Our resource identifier could look like,{CountryName}/{CityName}

Find A Better Method

For most operations that are read-only, the decision to use HTTP GET method instead of the SOAP POST should be an easy one.  One of the main reasons that SOAP did not allow GET, in early versions, is the fact that GET methods are not allowed to use request bodies.  SOAP relied on the body to communicate the action name and parameters, but we have seen how we can move all that information into the URL and remove the need to send a request body. 

Safe Operations

There are only two reasons that we should not map the GET method to an underlying SOAP call:

The first is if the size or format of a parameter makes it too difficult to put into a URL.  For example if the purpose of a call is for the client to upload an image which the server does some image processing on and then returns the updated image.  Encoding image data into a URL query string is like to be ugly, bloated and probably run into physical URL length limitations imposed by network component implementations.

The second reason is if the client is intentionally trying to change some data in the system, then GET is not the right method.  If when retrieving some data, there are internal system updates that cause timestamps to be updated and counts to be incremented then GET is still fine.

Unsafe Operations

If GET cannot be used, then the next methods to consider are DELETE and PUT.  If a resource is being removed conceptually from the system, then DELETE is most appropriate.    

If a resource is being replaced then PUT is the best option.  If just a portion of an existing resource is being changed then PATCH is the first choice.

If a new resource is being created and the client is able to assign the resource identifier itself, then PUT works well. 

And The Rest

If none of the above cases fit, then POST is the fallback method.

Changing the Response

The response is significantly easier to deal with than the request. 

Unwrap The Body

SOAP responses are always wrapped inside an XML envelope payload.  The soap:envelope and soap:body should be removed and if any kind of encoding has been applied to the body, as in our example, it should be removed. 

Correct The Response Description

The Content-Length header should be adjusted to reflect the new body size and the Content Type header should be updated to accurately describe the semantics of the message being returned.

But What About The REST?

Following the suggestions that I have laid out so far will enable converting a SOAP API into a resource oriented HTTP API that may or may not satisfy the "self-descriptive" constraint of REST depending on the media types chosen.  However, my experience is that most SOAP APIs are built to expose a different set of data than you would if you were building an API based on the principles of REST, described by Roy Fielding.  There is really no way to do a mechanical translation of a SOAP API into a REST API that is designed to maximize evolvability through the use of self-describing messages and hypermedia.  If extremely loose coupling and independently evolvable components are important objectives  then it is unlikely that there will be a 1-1 mapping between SOAP operations and HTTP resources and therefore the guidance in this article will be of limited use.

So yes, the title of the article is a misnomer, but I'd rather see more HTTP-based resource oriented APIs than argue about the imprecision of commonly used terms!

Henrik F. Nielsen: Updates to Microsoft ASP.NET WebHooks Preview (Link)

Posted the blog Updates to Microsoft ASP.NET WebHooks Preview describing Beta4 of ASP.NET WebHooks Preview with a nice set of new features based on feedback and help from the community! Always let us know what you think – either by raising a issue on GitHub or pinging me on twitter. You can get the update from by looking for the packages under Microsoft.AspNet.WebHooks.*. If you haven’t heard about ASP.NET WebHooks then you may want to look at Introducing Microsoft ASP.NET WebHooks Preview.

Have fun!


Darrel Miller: In The Mood For HTTP - Episode 3

The recording for episode #3 is now available on Crowdcast and YouTube. In this episode we cover issues like API description languages, security weaknesses in HTTP APIs and the illusive HTTP status code 410 Gone.

Glenn Miller


Some of the questions we attempted to answer this week include:

  • What is your take on things like Swagger? Didn't we learn our lessons with WSDL?
  • What are the biggest security flaws on HTTP API designs and implementations you are seeing quite often?
  • Is there any advantage of returning HTTP status code 410 rather than 404?
  • I have an API that needs to scale. I can add HTTP caches and load balancers. Will using a message bus on the server help?
  • Those days looks like REST and JSON are strictly correlated, I would love to hear you demistify this and introduce content negotiation.

Links from the show include:

Keep your eyes on and our twitter accounts @darrel_miller and @gblock for the announcement of our next episode and get your questions ready!

Image Credits:

Dominick Baier: IdentityServer3 Logging & Monitoring using Serilog and Seq

IdentityServer has two fundamental “monitoring” facilities : development-time logging and production-time eventing. The original docs are here.

Logging is for developers – in fact – when I start a new IdentityServer3 project, that’s the first thing I configure. For security reasons (and to be spec compliant) the error messages in IdentityServer are pretty vague – logging gives you a detailed inside view of what’s really going on.

We use the fabulous LibLog library for logging, which means we support logging frameworks like SeriLog, NLog, Log4Net and others out of the box. If you want to directly connect to a custom logging framework – we have a sample for that as well.

Depending on how much logging sources you enable, the logs will contain sensitive data like passwords, claims and tokens. This is where eventing comes in.

Events are more suitable for production scenarios where you want more high level – but also queryable – data. This includes typical events like login failed/success, errors etc… to connect IdentityServer to an event processing system (ELK being the most popular), you would implement the IEventService interface.

For this post I want to show you how to connect IdentityServer to Serilog for logging and a local Seq instance for querying and parsing events.

That’s super easy – first get Serilog from Nuget

install-package Serilog

If you are using an IIS hosted IdentityServer, you probably want to log to a text file using System.Diagnostics (here’s a nice tail tool to view those logs in real time). In that case, add the following Serilog setup to your Startup:

Log.Logger = new LoggerConfiguration()

..and add the following snippet to your web.config:

  <trace autoflush="true" indentsize="4">
      <add name="myListener" 
            initializeData="Trace.log" />

That’s it. LibLog will detect that Serilog has been configured in the host and will start piping all IdentityServer logging to it.

If you prefer self-hosts for IdentityServer (I do for dev time) – there’s a nice console log formatter:

install-package Serilog.Sinks.Literate

In that case add the following Serilog setup to your host:

Log.Logger = new LoggerConfiguration()
    .LiterateConsole(outputTemplate: "{Timestamp:HH:MM} [{Level}] ({Name:l}){NewLine} {Message}{NewLine}{Exception}")

This gives you nicely formatted console output


Seq is free for single user, easy to use and easy to setup. To connect IdentityServer to Seq, I wrote the following event service:

class SeqEventService : IEventService
    static readonly ILogger Log;
    static SeqEventService()
        Log = new LoggerConfiguration()
    public Task RaiseAsync<T>(Event<T> evt)
        Log.Information("{Id}: {Name} / {Category} ({EventType}), Context: {@context}, Details: {@details}",
        return Task.FromResult(0);

..and registered it like this:

factory.EventService = new Registration<IEventServiceSeqEventService>();

Using the Seq console, you can now query the events – e.g. for failed logons, IP addresses etc..


Nice! HTH.

(full source code can be found here)

Filed under: .NET Security, ASP.NET, IdentityServer, OAuth, OpenID Connect, OWIN, WebAPI

Darrel Miller: In The Mood For HTTP - Open Q&A

As a software developer today it is pretty difficult to avoid working with HTTP in some capacity.  There also seems to be a growing desire among developers to get a deeper understanding of the protocol.  Recently Glenn Block and I decided it might be interesting to do a online Q&A about HTTP and try and answer developer questions.


You Don't Know If You Don't Try

The first episode is available on along with the questions we attempted to answer indexed into the video.  If you would rather not log into Crowdcast to watch, the video is also available on YouTube.

Some of the questions we addressed in the show include:

  • Are there fundamental differences to consider when it comes to internal HTTP requests between microservices vs. a public API?
  • Where should I put my API Key?
  • What are your suggestions for HTTP API discoverability?
  • Pro and Cons of Custom Headers
  • What should we return in the body from POST or PUT?
  • Browser client (JavaScript calling hypermedia api) versus code-on-demand ajax calls?

Links from the show include:

Was It A Fluke?

We didn't manage to make it through all the questions in the first episode, and people seemed to like the conversation, so we decided to have another go.  The video and questions for episode 2 are also on and on YouTube.

Some of the questions we answered include:

  • Is it common practice to use Media Types for supplying different type of data (and not just versioning) when posting using the Content-Type header, e.g. /payment could take a and
  • What actually is HTTP caching? Is it caching the payload?
  • SPDY and HTTP/2
  • Can you recommend an API gateway, open-source or otherwise?
  • What are your thoughts on using tools like AutoRest for client generation?

Links from the show include:

Coming up next

There have been a number of Swagger and other API description language related questions that we have only indirectly touched on. So, we are going to start the next episode with a full on discussion on API description languages, their strengths and their pitfalls.

Dominick Baier: The State of Security in ASP.NET 5 and MVC 6: Authorization

The hardest part in designing an application is authorization. The requirements are always so app-specific that for 10 applications you often see 12 different implementations.

To make things worse, ASP.NET and MVC traditionally had not much more built-in to offer than boring role checks. This lead to either unmaintainable code (hard coded role names and Authorize attributes) or complete custom implementations – or both.

In ASP.NET 5, a brand new authorization API is supposed to improve that situation – and IMHO – oh yes it does. Let’s have a look.

ASP.NET 5 supports two styles of authorization out of the box – policy-based and resource-based.

Both styles are a substantial improvement over the current ASP.NET authorization features and reduce the need to write your own authorization attribute/filter/infrastructure – though this is still totally possible.

The new Authorize Attribute
My main gripe with the old attribute is that it pushes developers towards hard-coding roles (or even worse – names) into their controller code. It violates separation of concerns and leads to hard to maintain code with roles names sprinkled all over your code base.

Also – let’s face it – declarative, role-based security might be nice for demos but is nowhere near flexible enough to write  anything but trivial applications.

The new Authorize attribute can still do role checks like this:

[Authorize(Roles = "Sales")]
public IActionResult DoSalesyStuff()
{ /* .. */ }

But this is mainly for backwards compatibility (the ability to check for names is gone). The more recommended pattern is to use so called authorization policies instead:

public IActionResult DoSalesyStuff()
{ /* .. */ }

Let’s have a look at policies next.

Policies & Requirements
Policies are a way to create re-usable authorization logic. Policies consist of one or more so called requirements. If all requirements of a policy are met, the authorization check is successful – otherwise it fails.

Policies are created using a policy builder, and the following snippet creates a very simple policy (aka “require authenticated users”) and sets that globally in MVC:

public class Startup
    public void ConfigureServices(IServiceCollection services)
        // only allow authenticated users
        var defaultPolicy = new AuthorizationPolicyBuilder()
        services.AddMvc(setup =>
            setup.Filters.Add(new AuthorizeFilter(defaultPolicy));

There are more extension methods similar to RequireAuthenticatedUser – e.g. RequireClaim or RequireRole.

Another common use case are named policies which can be referenced like the above SalesOnly example (again in Startup.ConfigureServices):

services.AddAuthorization(options =>
    // inline policies
    options.AddPolicy("SalesOnly", policy =>
    options.AddPolicy("SalesSenior", policy =>

You can also encapsulate requirements in classes, e.g.:

public class StatusRequirement : AuthorizationHandler<StatusRequirement>, IAuthorizationRequirement
    private readonly string _status;
    private readonly string _department;
    public StatusRequirement(string department, string status, bool isSupervisorAllowed = true)
        _department = department;
        _status = status;
    protected override void Handle(AuthorizationContext context, StatusRequirement requirement)
        if (context.User.IsInRole("supervisor"))
        if (context.User.HasClaim("department", _department) &&
            context.User.HasClaim("status", _status))

Which can then be added like this:

options.AddPolicy("DevInterns", policy =>
    policy.AddRequirements(new StatusRequirement("development""intern"));
    // ..or using an extension method
    //policy.RequireStatus("development", "intern");

Under the covers, the AddAuthorization extension method also puts an IAuthorizationService (or more specifically the DefaultAuthorizationService) into the DI container. This class can be used to programmatically evaluate policies (amongst other things – more on that later).

To make the authorization service available – simply add it to e.g. a controller constructor:

public class TestController : Controller
    private readonly IAuthorizationService _authz;
    public TestController(IAuthorizationService authz)
        _authz = authz;

..and then use it in an action:

public async Task<IActionResult> SalesSeniorImperative()
    if (await _authz.AuthorizeAsync(User, "SalesSenior"))
        return View("success");
    return new ChallengeResult();

Scott used a slightly different approach, but using the same underlying infrastructure.

Remark ChallengeResult can be used to trigger an “access denied” condition in MVC. The cookie middleware e.g. will translate that either into a redirect to a login page for anonymous users, or a redirect to an access denied page for authenticated users.

Remark 2 Since views in MVC 6 also support DI, you can inject the authorization service there as well. Some people like this approach to conditionally render UI elements.

    ViewData["Title"] = "Home Page";
    @using Microsoft.AspNet.Authorization
    @inject IAuthorizationService _authz
@if (await _authz.AuthorizeAsync(User, "SalesOnly"))
        <a href="test/salesOnly">Sales only</a>

This is a nice way to centralize authorization policies and re-use them throughout the application.

The only thing I don’t like about this approach is, that it pushes you towards using the claims collection as the sole data source for authorization decisions. As we all know, claims describe the identity of the user, and are not a general purpose dumping ground for all sorts of data – e.g. permissions.

It would be nice if one could use the DI system of ASP.NET to make further data source accessible in custom requirement. I’ve opened an issue for that – we’ll see what happens.

Resource-based Authorization
This is a new approach for ASP.NET and is inspired by the resource/action based approach that we had in WIF before (which was ultimately inspired by XACML). We also like that approach a lot, but the problem with the WIF implementation (and also ours) was always that due to the lack of strong typing, the implementation became messy quickly (or at least you needed a certain amount of discipline to keep it clean over multiple iterations).

The idea is simple – you identify resources that your application is dealing with – e.g. customers, orders, products (yawn). Then you write a so called handler for each of these resources where you express the authorization requirements in code.

You use requirements to express whatever action is supposed to be applied to the resource, and conclude with a success/failure, e.g.:

public class CustomerAuthorizationHandler : 
    protected override void Handle(AuthorizationContext context, 
        OperationAuthorizationRequirement requirement, 
        Customer resource)
        // implement authorization policy for customer resource

Operation requirements are built-in and can be used to model simple string-based actions – but you can also write your own, or derive from OperationAuthorizationRequirement.

public static class CustomerOperations
    public static OperationAuthorizationRequirement Manage = 
        new OperationAuthorizationRequirement { Name = "Manage" };
    public static OperationAuthorizationRequirement SendMail =
        new OperationAuthorizationRequirement { Name = "SendMail" };
    public static OperationAuthorizationRequirement GiveDiscount(int amount)
        return new DiscountOperationAuthorizationRequirement
            Name = "GiveDiscount",
            Amount = amount

You then register the resource handler with the DI system and can access it imperatively from within your controllers (using the above mentioned authorization service):

public async Task<IActionResult> Discount(int amount)
    var customer = new Customer
        Name = "Acme Corp",
        Region = "south",
        Fortune500 = true
    if (await _authz.AuthorizeAsync(User, customer, 
        return View("success");
    return new ChallengeResult();

What I like about this approach is that the authorization policy has full strong typed access to the domain object it implements authorization for, as well as the principal. This is a huge improvement over the WIF API. It also makes it easy to unit test your controller without the authorization code – and even more importantly (at least for security guy) – it allows unit testing the authorization policy itself.

protected override void Handle(AuthorizationContext context, 
    OperationAuthorizationRequirement requirement, 
    Customer resource)
    // user must be in sales
    if (!context.User.HasClaim("department""sales"))
    // ...and responsible for customer region
    if (!context.User.HasClaim("region", resource.Region))
    // if customer is fortune 500 - sales rep must be senior
    if (resource.Fortune500)
        if (!context.User.HasClaim("status""senior"))
    if (requirement.Name == "GiveDiscount")
        HandleDiscountOperation(context, requirement, resource);

In addition, the resource handler can make full use of the DI system. That means we can inject access to arbitrary data stores. A very common use case is to use some sort of database to query permission tables or similar. This makes it very flexible.

Imagine a permission service that queries your authorization using some backing store (the _permissions variable):

private void HandleDiscountOperation(
    AuthorizationContext context, 
    OperationAuthorizationRequirement requirement, 
    Customer resource)
    var discountOperation = requirement as DiscountOperationAuthorizationRequirement;
    var salesRep = context.User.FindFirst("sub").Value;
    var result = _permissions.IsDiscountAllowed(
    if (result)

All in all – I am very pleased with this new API and it will be interesting to see how it performs in a real application.

The full source code of the sample can be found here and the repo for the authorization API is here (open an issue if you have feedback)

Have fun!

Filed under: .NET Security, ASP.NET, WebAPI

Filip Woj: Global route prefixes with attribute routing in ASP.NET Web API

As you may have learnt from some of the older posts, I am a big fan, and a big proponent of attribute routing in ASP.NET Web API.

One of the things that is missing out of the box in Web API’s implementation of attribute routing, is the ability to define global prefixes (i.e. a global “api” that would be prepended to every route) – that would allow you to avoid repeating the same part of the URL over and over again on different resources. However, using the available extensibility points, you can provide that functionality yourself.

Let’s have a look.


ASP.NET Web API allows you to provide a common route prefix for all the routes within a controller via RoutePrefixAttribute. This is obviously very convenient, but unfortunately that attribute, out of the box, cannot be used globally.

Here’s a typical use case per controller:

public class ItemsController : ApiController
    public IEnumerable<Item> Get() { ... }

    public Item Get(int id) { ... }

    public HttpResponseMessage Post(Item item) { ... }

Of course in use cases like the one above, it would be nice to have to avoid that “api” repeated on every single controller.

Applying a route prefix globally

In order to apply route prefix globally, you will need to customize the way ASP.NET Web API creates routes from the route attributes. The way to do that, is to implement a custom IDirectRouteProvider, which can be used to feed custom routes into the Web API pipeline at application startup.

public interface IDirectRouteProvider
    IReadOnlyList<RouteEntry> GetDirectRoutes(
        HttpControllerDescriptor controllerDescriptor, 
        IReadOnlyList<HttpActionDescriptor> actionDescriptors,
        IInlineConstraintResolver constraintResolver);

That would typically mean a lot of work though, since you would need to manually deal with everything from A to Z – like manually processing controller and action descriptors. A much easier approach is to subclass the existing default implementation, DirectRouteProvider, and override just the method that deals with route prefixes (GetRoutePrefix). Normally, that method will only recognize route prefixes from the controller level, but we want it to also allow global prefixes.

DirectRouteProvider exposes all of its members as virtual – allowing you to tap into the route creation process at different stages i.e. when reading route prefixes, when reading controller route attributes or when reading action route attributes. This is shown in the next snippet:

public class CentralizedPrefixProvider : DefaultDirectRouteProvider
    private readonly string _centralizedPrefix;

    public CentralizedPrefixProvider(string centralizedPrefix)
        _centralizedPrefix = centralizedPrefix;

    protected override string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor)
        var existingPrefix = base.GetRoutePrefix(controllerDescriptor);
        if (existingPrefix == null) return _centralizedPrefix;

        return string.Format("{0}/{1}", _centralizedPrefix, existingPrefix);

The CentralizedPrefixProvider shown above, takes a prefix that is globally prepended to every route. If a particular controller has it’s own route prefix (obtained via the base.GetRoutePrefix method invocation), then the centralized prefix is simply prepended to that one too.

Finally, the usage of this provider is as follows – instead of invoking the “regular” version of MapHttpAttributeRoutes method, you need to use the overload that takes in an instance of IDirectRouteProvider:

config.MapHttpAttributeRoutes(new CentralizedPrefixProvider("api"));

In this example, all attribute routes would get “api” prepended to the route template.

In more interesting scenarios, you can also use parameters with CentralizedPrefixProvider – after all, we are just building up a regular route template here. For example, the following set up, defining a global version parameter as part of every route, is perfectly valid too:

config.MapHttpAttributeRoutes(new CentralizedPrefixProvider("api/v{version:int}"));

Now in any action method signature, you can add an additional version integer parameter, even though you don’t have it in the route template beside the action – because it will be propagated down from the CentralizedPrefixProvider. For example:

public class ItemsController : ApiController
    public Item Get(int id, int version) { ... }

And obviously – the “api” in the controller level RoutePrefixAttribute is no longer needed too.

Darrel Miller: 302 - Found

After an interesting summer of working on OSS projects, doing a keynote in Australia at DDDMelbourne, and getting ever closer to finishing that Pluralsight course, I now have a new role to sink my teeth into

I have joined Microsoft as an API Evangelist.   That means if you are building HTTP APIs, my role is to try and help.  Whether you are building APIs using ASP.NET, or you are looking at Azure infrastructure for hosting or managing APIs, I want to make it easier for you to find answers to your questions.

Right At Home

I've spent a significant part of my 20 year career developing software on the Microsoft stack.  There are aspects of the stack I really like and some parts I don't.  The reality is, that every platform has its flaws.  Over the past six years, as a Web API Advisor and then an MVP, I've had the opportunity to interact with a significant number of MS employees and I have been consistently impressed by the attitude and the desire to make the developer ecosystem better.  In the past few years Microsoft really seems to be succeeding in changing the direction of the behemoth and  I am excited about having the opportunity to join Microsoft and help push forward in this new direction.

Information Overload

ASP.NET is heading towards releasing some major changes in the coming year and Azure is continuously adding new features.  It is a major challenge for developers to stay up to date with the capabilities that are available and evaluate which are most appropriate for their scenario.  I hope to use my experience with the platform, and my experience building HTTP APIs to provide practical guidance for developers working with APIs.

More Of The Same

This role really involves me doing more of what I already enjoy doing in my spare time.  So, expect more blog posts, more screencasts and more conference talks.  In fact, if you are free next Tuesday, why don't you join Glenn Block and myself for a casual HTTP Q&A.


Yep, this is pretty much how I'm feeling right now.

Henrik F. Nielsen: Receive WebHooks from Azure Alerts and Kudu (Azure Web App Deployment)

Posted a new blog on receiving WebHooks from Azure Alerts and Kudu (Azure Web App Deployment) and how to monitor your Azure Web App with Kudu and Azure Alert WebHooks using  Microsoft ASP.NET WebHooks.

Have fun!


Darrel Miller: Navigating DRY IETF Specs

I've been reading IETF specifications for a number of years now and I find them fairly pleasant to read.  But I remember when I started there were a whole bunch of huh!? moments.  Since then I have learned many of the conventions and developed a few tricks that make the process easier.  I was just reminded of one of those huh!? moments and figured I would share my solution.


I was reading through RFC 7235 which is the HTTP Authentication specification because I wanted to get a good picture of what the header and parameter values actually look like. 

Where To Start

I always start with the HTML version of the spec (there are also a .txt and .pdf version of all specs) so that I can use the hyperlinks in the contents page.  The contents page showed me what I was looking for:


I clicked on the link for section 4.2 and got this,


Ok, so Authorization = credentials !!!.  How completely useless is that? 

A Slight Detour

However, because we are looking at a header definition, I know that what is on the left of the equals is the text that will actually appear in the HTTP request.  All HTTP headers are formatted the same way:


I happen to know this information is in RFC 7230.  One of the tricky parts to working with IETF specs is that they are the ultimate example of DRY.  In order to avoid ambiguous definitions, things tend to be only defined once and everything builds on other things that have been defined elsewhere.  It leads to lots of digging for details. 

So getting back to our example.  We know that an Authorization header-field is made up of the field-name Authorization followed by a colon and then a field-value which is defined as credentials. But how do we know what that means? 

Needle In A Haystack

Looking in the contents page will not find a reference for credentials.  Searching on the term credentials returns 56 results. The trick is to search on "credentials =".  IETF specifications define syntax using ABNF and that means that somewhere in the document will be a syntax assignment.    Adding the space and equals reduces that search down to just two results. 

The first results is:


Now we can start to see how the field-value is defined.  But now we have more definitions to search for.

Things Are Getting Easier

The reason there are two matches for the credentials = search is because recent IETF specifications have started creating an appendix called Collected ABNF.  This makes it easier to find all the definitions that are used in the current document.


When you drill down, you will find that not everything is defined in the current document.  The syntax for token is defined elsewhere, but there is a link to locate that definition in another spec. 

Some Stuff Is Written In Stone

Older specifications do not have the Collected ABNF appendix so the search trick becomes really helpful when you hunt for obscure syntax definitions in arcane specs that you really don't want to read in full.

What Are Your Secrets?

If you have other tips that you use for deciphering specifications that you read, I'd love to hear about them.

Image Credits: Reading

Darrel Miller: There Is Almost Nothing to See Here

I just read Adam Ralph's post Blog == Weblog and I was inspired.  I started blogging 10 years ago because I wanted an outlet for my thoughts.  I didn't take it particularly seriously as you would see if you dig back to the early days.  [ed note: which would be easier if my blog host actually provided an index to those old posts.] However,  I enjoyed reading about the miscellaneous thoughts that went through the heads of people who I respected, and I enjoyed sharing my own.

I'm not going to admit how many half written blog posts that I have in my drafts folder, that I do have every intention of finishing one day.  I like reading and writing technical content that has been properly researched and tells a well crafted story.  But I also like hearing what people think and I enjoy simply sharing my thoughts..  I guess twitter has been the replacement for me.  But 140 characters really doesn't cut it sometimes.

I will continue to try and provide articles with some meat on a regular basis, but don't be surprised if you find random musings of minimal value interspersed between them.  And with that I'm going to go back to working on my HttpClient course and writing that media type spec for conference proposals Smile.

Dominick Baier: Upcoming Identity & Access Control Workshops in Europe

Brock and I will be in London in November and January to hold our identity & access control workshop.

In November we are at the SDD Deep Dive event and do a very special three day version which includes extra content around IdentityServer3 and migrating to ASP.NET 5 and MVC6.

In January we will be at NDC London for a two day workshop which will also include the ASP.NET 5 content.

I will be also in Oslo in January to do the same two day version of the workshop.

Hope to see you at one of those events!

Filed under: .NET Security, ASP.NET, IdentityServer, OAuth, OpenID Connect, WebAPI

Henrik F. Nielsen: Integrating with Instagram Using ASP.NET WebHooks Preview (Link)

In the blog Integrating with Instagram using ASP.NET WebHooks Preview we describe how to integrate with Instagram using Microsoft ASP.NET WebHooks. This enables you to get notified when pictures are posted, for example within a 1000 meter radius or the Seattle Space Needle!

Have fun!


Henrik F. Nielsen: Sending WebHooks with ASP.NET WebHooks Preview (Link)

In the blog Introducing Microsoft ASP.NET WebHooks Preview, we gave an overview of how to work with Microsoft ASP.NET WebHooks. We mentioned that it is not only possible to receive WebHooks from others but also to add support for sending WebHooks from your Web Application. The blog Sending WebHooks with ASP.NET WebHooks Preview goes into detail on how to do that.

Have fun!


Darrel Miller: Service Discovery : Redux

Yesterday, I had a thought.  It didn't fit into a tweet so wrote a few paragraphs.  I was very pleased with myself, finally getting round to writing again after a few months off.  That was, until two different people who I respect highly, told me I was wrong.  That part sucked.


Who Can Do This For Me?

Mike Amundsen stated in comments on the blog that what I was describing was simply the usage of a service, not the discovery of service.  Mike has written about the process of service discovery as part of a series of articles in Infoq.  Mike uses the term Service Discovery to describe the process of identifying who will be providing a particular service as part of an application.

If we were to consider a real example, consider the need to provide security services within an application.  One part of that process is the role of an authentication manager.  Some service needs to take credentials and provide an identity.  There are a whole range of choices.  An application developer could create their own service.  They could use an open source product like IdentityServer, or a hosted service like Auth0 or Stormpath.  Many different identity providers also provide service APIs for doing authentication. e.g. AzureAD, Facebook, Google, LinkedIn, Twitter, Github.

Currently there are minimal facilities for doing this "service discovery" in any kind of automated way.  If we look into the past, some will remember UDDI as promising this kind of capability. More recently, was created as a search engine to facilitate the discovery process.

Where Is It Now?

John Sheehan also felt that I was misappropriating the Service Discovery term.  From his perspective,

Being a past member of the Runscope team, I know how critical the microservices architecture is to their product.  I also have a good idea of how much devops work they have done to enable the agility of their product. Being able to separate the logical identity of a service from the physical identity is hugely valuable when it comes building scalable, reliable and evolvable systems.

When building products that are composed of many different services it can challenging to to seamlessly support dev, test and production environments.  The same goes for being able to roll back deployed services and fail-over services.  Having systems in place that allow you to dynamically change physical addresses of machines for logical services is essential.

What Identifier Should I use?

Both Mike and John we correct.  I was using the term Service Discovery to describe something different.  But interestingly, so were they. 

What I described was a distinct process that falls somewhere in-between their definitions.  I was describing the use of a URL as a service identifier.  Once an application has "discovered" which authentication service they are going to use, an identifier for that service needs to be communicated in some way to components of the application in order for them to interact with the service.  This could be done as simply as adding a config entry for each application component.  It could be centralized in some kind of registry service that other services use to discover the identifier, or as I was suggesting it could be delivered via hypermedia.


The idea is that a component that needs access to authorization capabilities only needs to know in advance the link relation type identifier used to advertise authorization services, it doesn't need to find out until runtime what the identifier for that service is.  Having some kind of semantically significant type associated to the service identifier is a key concept for enabling this type of discovery.

I'm not going to deny that there is some smoke and mirrors going on here because interchangeable services from different identity providers is still fairly uncommon.  However,  standards like OAuth2 do provide a certain level of consistency.  Just because something isn't possible today, doesn't mean it is not a good idea Smile.

Naming is Hard

I believe all three scenarios are valid and could easily be described as "service discovery".  That's not going to help though!  For my own sanity, I decided to try and come up with distinct names for these different types of discovery.


  • Provider Discovery is the process of finding a service that can provide the desired capabilities.
  • Service Identification is the process of getting an identifier for a service that will provide a certain type of service.
  • Service resolution is the process of taking a service identifier and locating a specific implementation of that service.

I have no illusions that these definitions are "right" or that they will gain any traction, but it will help me have conversations about a topic that I think is very important.


Image Credits: Seal

Darrel Miller: Service Discovery, The Easy Way

Here's a thought that wouldn't fit into a tweet and will serve the purpose of breaking my blogging dry spell.  With all the attention that microservices is currently receiving I regularly hear people talking about service discovery.  When trying to co-ordinate multiple different services working together, it is critical to be able to dynamically configure which services will perform what services, for which consumers.

Before spending too much time architecting a "service discovery service" to allow services to discover other services, consider taking one of my favourite pieces of advice. What would a web browser do? keys

When you visit <insert site here> in the morning for your daily dose of internet intellectual fodder, how does your web browser discover what CDN to use, what ad provider, what analytics tracking service, what error logging service?

Including links in content that point to the services to be used and using link relations types to identify the purpose of those links, provide a truly decentralized service discovery mechanism for microservices that requires minimal effort.


Image Credits: Keys

Filip Woj: Disposing resources at the end of Web API request

Sometimes you have resources in your code that are implementing IDisposable, and that you’d like them to be disposed only at the end of the HTTP request. I have seen a solution to this problem rolled out by hand in a few code bases in the past – but in fact this feature is already built into Web API, which I don’t think a lot of people are aware of.

Let’s have a quick look.


ASP.NET Web API contains an extension method for HttpRequestMessage that’s called RegisterForDispose – which allows you to pass in a single instance or a collection of instances of IDisposable.

What happens under the hood, is that Web API will simply store those object references in the properties dictionary of the request message (under HttpPropertyKeys.DisposableRequestResourcesKey key), and at the end of the Web API request lifetime, will iterate through those objects and call Dispose on them. This is the responsibility of the Web API host, so each of the existing hosting layers – Web Host (“classic” ASP.NET), self host (WCF based) and OWIN host (the Katana adapter) is explicitly implementing this feature. It is guaranteed to happen (for example, the Katana adapter uses a try/catch block around the entire Web API pipeline and performs the disposal in finally.

As a result you can do things like the code below. Imagine a message handler that opens a stream, writes to it, then saves the stream into request properties (so that other Web API components such as other message handlers, filters, controllers etc can use it too):

public class WriterHandler : DelegatingHandler
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        var writer = new StreamWriter("c:\\file.txt", true);
        //save the writer for later use
        request.Properties["filewriter"] = writer;

        await writer.WriteLineAsync("some important information");

        return await base.SendAsync(request, cancellationToken);

You don’t have to use a using statement here, as registering for disposal using Web API resource tracking feature will ensure that the stream writer is disposed of at the end of the request lifetime. This is very convenient, as other components during the HTTP request, can share the same resource.

It is also worth adding that resource tracking is also used if you ever use Web API GetDependencyScope feature – which allows you to resolve services from the registered dependency resolver:

var myService = request.GetDependencyScope().GetService(typeof(IMyService));

In the above case, the instance of IMyService will be registered for disposal at the end of Web API request.

One final note – at any time you can also take a peek into the resources currently registered for disposal, using a GetResourcesForDisposal extension method on HttpRequestMessage.

Dominick Baier: IdentityModel 1.0.0 released

Part of the ongoing effort to modernize our libraries, I released IdentityModel today.

IdentityModel contains useful helpers, extension methods and constants when working with claims-based identity in general and OAuth 2.0 and OpenID Connect in particular.

See the overview here and nuget here.

Feedback and PRs welcome.

Filed under: .NET Security, IdentityModel, OAuth, OpenID Connect, WebAPI

Dominick Baier: The State of Security in ASP.NET 5 and MVC 6: OAuth 2.0, OpenID Connect and IdentityServer

ASP.NET 5 contains a middleware for consuming tokens – but not anymore for producing them. I personally have never been a big fan of the Katana authorization server middleware (see my thoughts here) – and according to this, it seems that the ASP.NET teams sees IdentityServer as the replacement for it going forward.

So let’s have a look at the bits & pieces and how IdentityServer can help in implementing authentication for MVC web apps and APIs.

IdentityServer is an extensible OAuth 2.0 authorization server and OpenID Connect provider framework. It is different from the old authorization server middleware as it operates on a higher level of abstraction. IdentityServer takes care of all the protocol and data management details while you only need to model your application architecture using clients, users and resources (see the big picture and terminology pages).

IdentityServer is currently available as OWIN middleware only (as opposed to native ASP.NET 5 middleware) – that means it can be used in Katana-based hosts and ASP.NET 5 hosts targeting the “full .NET framework” aka DNX451. It does currently not run on the Core CLR – but we are working on it.

There is an integration package for bridging OWIN into ASP.NET 5 which allows wiring up IdentityServer using the typical application builder extension method pattern:

var certFile = env.ApplicationBasePath + "\\idsrv3test.pfx";
var idsrvOptions = new IdentityServerOptions
    Factory = new IdentityServerServiceFactory()
    SigningCertificate = new X509Certificate2(certFile, "idsrv3test"),

For this sample we use in-memory data sources, but you can connect to any data source you like.

The Users class simply defines two test users (Alice and Bob of course) – I won’t bore you with the details. Scopes on the other hand define the resources in your application, e.g. identity resources like email addresses or roles, or resource scopes that represent your APIs:

public static IEnumerable<Scope> Get()
    return new[]
        // standard OpenID Connect scopes
        // API - access token will 
        // contain roles of user
        new Scope
            Name = "api1",
            DisplayName = "API 1",
            Type = ScopeType.Resource,
            Claims = new List<ScopeClaim>
                new ScopeClaim("role")

Clients on the other hand represent the applications that will request authentication tokens (also called identity tokens) and access tokens.

public static List<Client> Get()
    return new List<Client>
        new Client
            ClientName = "Test Client",
            ClientId = "test",
            ClientSecrets = new List<Secret>
                new Secret("secret".Sha256())
            // server to server communication
            Flow = Flows.ClientCredentials,
            // only allowed to access api1
            AllowedScopes = new List<string>
        new Client
            ClientName = "MVC6 Demo Client",
            ClientId = "mvc6",
            // human involved
            Flow = Flows.Implicit,
            RedirectUris = new List<string>
            PostLogoutRedirectUris = new List<string>
            // access to identity data and api1
            AllowedScopes = new List<string>

With these definitions in place we can now add an MVC application that uses IdentityServer for authentication, as well as an API that supports token-based access control.

MVC Web Application
ASP.NET 5 includes middleware for OpenID Connect authentication. With this middleware you can use any OpenID Connect compliant provider (see here) to outsource the authentication logic.

Simply add the cookie middleware (for local signin) and the OpenID Connect middleware pointing to our IdentityServer to the pipeline. You need to supply the base URL to IdentityServer (so the middleware can fetch the discovery document), the client ID, scopes, and redirect URI (compare to our client definition we did earlier). The following snippet requests the user’s ID, email and profile claims in addition to an access token that can be used for the “api1” resource.

app.UseCookieAuthentication(options =>
    options.AuthenticationScheme = "Cookies";
    options.AutomaticAuthenticate = true;
app.UseOpenIdConnectAuthentication(options =>
    options.AutomaticChallenge = true;
    options.AuthenticationScheme = "Oidc";
    options.SignInScheme = "Cookies";
    options.Authority = "http://localhost:5000";
    options.RequireHttpsMetadata = false;
    options.ClientId = "mvc6";
    options.ResponseType = "id_token token";

Building web APIs with MVC that are secured by IdentityServer is equally simple – the ASP.NET 5 OAuth 2.0 middleware supports JWTs out of the box and even understands discovery documents now.

app.UseJwtBearerAuthentication(options =>
    options.Authority = "http://localhost:5000";
    options.RequireHttpsMetadata = false;
    options.Audience = "http://localhost:5000/resources";
    options.AutomaticAuthenticate = true;
app.UseMiddleware<RequiredScopesMiddleware>(new List<string> { "api1" });

Again Authority points to the base-address of IdentityServer so the middleware can download the metadata and learn about the signing keys.

Since the built-in middleware does not understand the concept of scopes, I had to fix that by adding the extra scope middleware.

Expect this be improved in future versions.

API Client
Tokens can be also requested programmatically – e.g. for server-to-server communication scenarios. Our IdentityModel library has a TokenClient helper class which makes that very easy:

async Task<TokenResponse> GetTokenAsync()
    var tokenClient = new TokenClient(
    return await tokenClient.RequestClientCredentialsAsync("api1");

…and using the token:

async Task<HttpResponseMessage> CallApi(string accessToken)
    var client = new HttpClient();
    return await client.GetAsync("http://localhost:19806/identity");

The full source code can be found here.

IdentityServer can be a replacement for the Katana authorization server middleware – but as I said it is a different mindset, since IdentityServer is not protocol oriented – but rather focusing on your application architecture. I should mention that there is actually a middleware for ASP.NET 5 that mimics the Katana approach – you can find it here.

In the end it is all about personal preference, and most importantly how comfortable you are with the low level details of the protocols.

There are actually much more samples on how to use IdentityServer in the samples repo. Give it a try.

Filed under: .NET Security, ASP.NET, IdentityServer, OAuth, OpenID Connect, OWIN, WebAPI

Dominick Baier: The State of Security in ASP.NET 5 and MVC 6: Claims & Authentication

Disclaimer: Microsoft announced the roadmap for ASP.NET 5 yesterday – the current release date of the final version is Q1 2016. Some details of the features and APIs I mention will change between now and then. This post is about beta 5.

I started talking about claims-based identity back in 2005. That was the time when Microsoft introduced a new assembly to the .NET Framework called System.IdentityModel. This assembly contained the first attempt of introducing claims to .NET, but it was only used by WCF and was a bit over-engineered (go figure). The claims model was subsequently re-worked by the WIF guys a couple of years later (kudos!) and then re-integrated into .NET with version 4.5.

Starting with .NET 4.5, every built-in identity/principal implementation was based on claims, essentially replacing the 12+ years old antiquated IIdentity/IPrincipal interfaces. Katana – but more importantly ASP.NET 5 is the first framework that now uses ClaimsPrincipal and ClaimsIdentity as first class citizens – identities are now always based on claims – and finally – no more down-casting!

HttpContext.User and Controller.User are now ClaimsPrincipals – and writing the following code feels as natural as it should be:

var email = User.FindFirst(“email”);

This might not seem like a big deal – but given that it took almost ten years to get there, shows just how slow things are moving sometimes. I also had to take part in a number of discussions with people at Microsoft over the years to convince them that this is actually the right thing to do…

Authentication API
Another thing that ASP.NET was missing is a uniform authentication API – this was fixed in Katana via the IAuthenticationManager and was pretty much identically brought over to ASP.NET 5.

AuthenticationManager hangs off the HttpContext and is a uniform APIs over the various authentication middleware that do the actual grunt work. The major APIs are:

  • SignIn/SignOut
    Instructs a middleware to do a signin/signout gesture
  • Challenge
    Instructs a middleware to trigger some external authentication handshake (this is further abstracted by the new ChallengeResult in MVC 6)
  • Authenticate
    Triggers validation of an incoming credential and conversion to claims
  • GetAuthenticationSchemes
    Enumerates the registered authentication middleware, e.g. for populating a login UI dynamically

Authentication Middleware
The actual authentication mechanisms and protocols are implemented as middleware. If you are coming from Katana then this is a no brainer. If your background is ASP.NET.OLD think of middleware as HTTP modules – just more flexible and lightweight.

For web UIs the following middleware is included:

  • Cookie-based authentication (as a replacement for good old forms authentication or the session authentication module from WIF times)
  • Google, Twitter, Facebook and Microsoft Account
  • OpenID Connect

WS-Federation is missing right now. It is also worth mentioning that there is now a generic middleware for OAuth2-style authentication (sigh). This will make it easier to write middleware for the various OAuth2 dialects without having to duplicate all the boilerplate code and will make the life of these guys much easier.

Wiring up the cookie middleware looks like this:

app.UseCookieAuthentication(options =>
    options.LoginPath = new PathString(“/account/login”);
    options.AutomaticAuthentication = true;
    options.AuthenticationScheme = “Cookies”;               

The coding style is a little different – instead of passing in an options instance, you now use an Action<Option>. AuthenticationType has been renamed to AuthenticationScheme (and the weird re-purposing of IIdentity.AuthenticationType is gone for good). All authentication middleware is now passive – setting them to active means setting AutomaticAuthentication to true.

For signing in a user, you create the necessary claims and wrap them in a ClaimsPrincipal. Then you call SignIn to instruct the cookie middleware to set the cookie.

var claims = new List<Claim>
    new Claim(“sub”, model.UserName),
    new Claim(“name”, “bob”),
    new Claim(“email”, “”)

var id = new ClaimsIdentity(claims, “local”, “name”, “role”);
Context.Authentication.SignIn(“Cookies”, new ClaimsPrincipal(id));

Google authentication as an example looks like this:

app.UseGoogleAuthentication(options =>
    options.ClientId = “xxx”;
    options.ClientSecret = “yyy”;

    options.AuthenticationScheme = “Google”;
    options.SignInScheme = “Cookies”;

The external authentication middleware implements the authentication protocol only – and when done – hands over to the middleware that does the local sign-in. That’s typically the cookie middleware. For this purpose you set the SignInScheme to the name of the middleware that should take over (this has been renamed from SignInAsAuthenticationType – again clearly an improvement).

Also the pattern of having more than one cookie middleware to be able to inspect claims from external authentication systems before turning them into a trusted cookie still exists. That’s probably a separate post.

For web APIs there is only one relevant middleware – consuming bearer tokens. This middleware has support for JWTs out of the box and is extensible to use different token types and different strategies to convert the tokens to claims. One notable new feature is support for OpenID Connect metadata. That means if your OAuth2 authorization server also happens to be an OpenID Connect provider with support for a discovery document (e.g. IdentityServer or Azure Active Directory) the middleware can auto-configure the issuer name and signing keys.

One thing that is “missing” when coming from Katana, is the OAuth2 authorization server middleware. There are currently no plans to bring that forward. IdentityServer can be a replacement for that. I will dedicate a separate blog post to that topic.

If you are coming from Katana, this all does not look terribly new to you. AuthenticationManager and authentication middleware works almost identical. Learning that, was no waste of time.

If you are coming from plain ASP.NET (and maybe even WIF or DotNetOpenAuth) this all works radically different under the covers and is really only “conceptually compatible”. In that case you have quite a lot of new tech to learn to make the jump to ASP.NET 5.

Unfortunately (as always) the ASP.NET templates are not very helpful in learning the new features. You either get an empty one, or the full-blown-all-bells-and-whistles-complexity-hidden-by-extensions-method-over-more-abstractions version of that. Therefore I created the (almost) simplest possible cookie-based starter template here. More to follow.

Filed under: .NET Security, ASP.NET, IdentityServer, OAuth, OpenID Connect, WebAPI

Dominick Baier: The State of Security in ASP.NET 5 and MVC 6

We’ve been closely following ASP.NET 5 and MVC 6 since the days it was presented behind closed doors, through the “vNext” and “Project K” phase up to recent beta builds.

I personally monitored all developments in the security space in particular and was even involved in one or the other decision making process – particularly around authorization which makes me also a little bit proud.

In preparation for the planned ASP.NET and MVC 6 security course for PluralSight, I always maintained a (more or less structured) list of changes and new features.

Tomorrow will be the release of Visual Studio 2015, which does NOT include the final release of ASP.NET 5. Instead we are between Beta 5 and 6 right now and the rough feature set has more or less been decided on. That’s why I think that now is a good time to do a couple of overview posts on what’s new.

Many details are still very much in flux and the best way to keep up with that is to subscribe to the various security related repos on github. Many things are not set in stone yet, so this is also an opportunity to take part in the discussion which I would encourage you to do.

The planned feature posts are:

Since training is very much about the details, we are holding off right now with recording any content until the code has been locked down for “v1”. So stay tuned.

The first public appearance of our updated “identity & access control” training for ASP.NET will be at NDC in London in January 2016.

Update: The final release of ASP.NET 5 is currently scheduled for Q1 2016 (

Filed under: .NET Security, ASP.NET, Conferences & Training, IdentityServer, WebAPI

Dominick Baier: Security at NDC Oslo

For a developer conference, NDC Oslo had a really strong security track this year. Also the audience appreciated that – from the five highest ranked talks – three were about security. Troy has the proof.

I even got to see Bruce Schneier for the first time. It is fair to say that his “Secrets & Lies” book changed my life and was one of the major reasons I got interested in security (besides Enno).

Brock and I did a two day workshop on securing modern web applications and APIs followed by a talk on Web API security patterns and how to implement authentication and authorization in JavaScript applications.

Other talks worth watching (I hope I haven’t missed anything):

Well done, NDC!

Filed under: .NET Security, IdentityModel, IdentityServer, OAuth, OpenID Connect, WebAPI

Dominick Baier: Give your WCF Security Architecture a Makeover with IdentityServer3

Not everybody has the luxury of being able to start over and build the new & modern version of their software from scratch. Many people I speak to have existing investments in WCF and their “old-school” desktop/intranet architecture.

Moving to an internet/mobile world while preserving the existing services is not easy because the technologies (and in my case the security technologies) are fundamentally incompatible. Your new mobile/modern clients will not be seamlessly able to request tokens from your existing WS-Trust STS and SOAP is not really compatible with OAuth2. So what to do?

You could try to teach your WS-Trust STS some basic HTTP based token service capabilities and continue using SAML tokens. You could provide some sort of SAML/JWT conversion mechanism and create Web APIs for your new clients that proxy / convert to the WCF world. Or you could provide to separate token services and establish trust between them. All approaches have their own advantages and disadvantages.

For a project I am currently working on I chose a different approach – get rid of the old WS-Trust STS altogether, replace it with an OAuth2 authorization server (IdentityServer3) and make your WCF services consume JWT tokens. This way both old and new clients can request tokens via OAuth2 and use them with either existing WCF services and the new Web APIs (which ultimately will be also used in the desktop version of the product). How does that work?

Requesting the token
The OAuth2 resource owner flow is what comes closest to WS-Trust and it is easy to replace the WCF WSTrustChannel code with that. Going forward the web view based flows actually give more features like external IdPs etc. but need a bit more restructuring of the existing clients. New clients can use them straight away.

Sending the token
This is the tricky part. WCF can not deal with JWTs directly since they are not XML based. You first need to wrap them in an XML data structure and the typical approach for that is to use a so called binary security token. This worked fine at some point but the latest version of WCF and the JWT token handler don’t seem to work together anymore (here’s a nice write up from Mickael describing the problem).

Since WCF is really done – I did not expect anyone to fix that bug anytime soon, so I needed a different solution.

Another XML container data structure that is well tested and does the job equally well is SAML – so I simply created a minimal SAML assertion to hold the JWT token.

static GenericXmlSecurityToken WrapJwt(string jwt)
var subject = new ClaimsIdentity("saml"
new Claim("jwt"
, jwt));

var descriptor = new SecurityTokenDescriptor
        TokenType =
        TokenIssuerName =
        Subject = subject

var handler = new Saml2SecurityTokenHandler
token = handler.CreateToken(descriptor);

var xmlToken = new GenericXmlSecurityToken

return xmlToken;

Since we are using SAML solely as a container, there is no signature, no audience URI and just a single attribute statement containing the JWT.

After that you can use the wrapped JWT with the CreateChannelWithIssuedToken method over a federation binding:

var binding = new WS2007FederationHttpBinding(
binding.Security.Message.EstablishSecurityContext = false;
binding.Security.Message.IssuedKeyType =
var factory = new ChannelFactory<IService
new EndpointAddress(https://localhost:44335/token

var channel = factory.CreateChannelWithIssuedToken(xmlToken);

Validating the token
On the service side I sub-classed the SAML2 security token handler to get the SAML deserialization. In the ValidateToken method I retrieve the JWT token from the assertion and validate it.

Since I have to do the validation manually anyways, I wanted feature parity with our token validation middleware for Web API which means that the token handler can auto-configure itself using the OpenID Connect discovery document as well as do the scope validation.

new IdentityServerWrappedJwtHandler("https://localhost:44333/core", "write"));

The end result is that both WCF and Web API can now consumes JWT tokens from IdentityServer and the customer can smoothly migrate and extend their architecture.

The POC can be found here. It is “sample quality” right now – feel free to make it more robust and send me a PR.

Filed under: .NET Security, IdentityServer, OAuth, WCF, WebAPI

Darrel Miller: Everything is Going to be… 308 Permanent Redirect

The last year has been been a very interesting one.  In April 2014, I announced that I was joining Runscope as a developer advocate.


This will be my 50th blog post since that one.  I've covered all kinds of topics from the intricacies of HTTP to API design guidelines, tricks for using ASP.NET Web API, reviews of APIs, and summaries of some of the conferences that I have attended.  I've had the opportunity to attend 17 different developer events and gave talks at all but 3.  I have worked on numerous .net based OSS projects. I have met many interesting people and learned so much about how people are building and consuming HTTP based APIs.

I have also had the pleasure of working with the Runscope team and learned the myriad of ways that the Runscope tooling can help developers build better APIs.  I've seen the team triple in size and watch the product continuously be enhanced.

It has been a fabulous year.  But now it is time for a redirect of my own.  If 308 does not look like a familiar status code, it is because it is fairly new.  It was only introduced in 2014 in RFC 7238.  A 308 is a like the 301(Moved Permanently), but does not allow the HTTP method to be changed during the redirect. 

As of this week, I will be moving on from Runscope and exploring other opportunities.  I won't go into reasons for the change,  but suffice it to say I would highly recommend Runscope as a place to work, and I would not hesitate using them as a reference for future work.  There is no bad blood here.

The first thing on my agenda is to finish the Advanced HttpClient Pluralsight course that has been on the back-burner for the last twelve months.

Beyond that, I do not know, and I'm open to suggestions Smile.  I like the human side of developer advocacy, but I also need to continue writing code that will actually be deployed into production.  Without that feedback loop, I cannot, in good faith, continue offering guidance.

When I started this adventure with Runscope, my blog post was titled It’s time for a change, and more of the same.  Well once again, it is time for a change, and more of the same.


Image credit: Fork
Image credit: Start Line

Dominick Baier: Three days of Identity & Access Control Workshop at SDD Deep Dive – November 2015, London

As part of the SDD Deep Dive event in London – Brock and I will deliver an updated version of our “Identity & Access Control for modern Web Applications and APIs” workshop.

For the first time, this will be a three day version covering everything you need to know to implement authentication & authorization in your ASP.NET web applications and APIs.

The additional third day will focus on IdentityServer3 internals and customization as well as an outlook on how to migrate your security architecture to ASP.NET 5 and MVC6.

Come by and say hello! (also get some of our rare IdentityServer stickers)

Filed under: .NET Security, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI

Ali Kheyrollahi: PerfIt! decoupled from Web API: measure down to a closure in your .NET application

Level [T2]

Performance monitoring is an essential part of doing any serious-scale software. Unfortunately in .NET ecosystem, historically first looking for direction and tooling from Microsoft, there has been a real lack of good tooling - for some reason or another effective monitoring has not been a priority for Microsoft although this could be changing now. Healthy growth of .NET Open Source community in the last few years brought a few innovations in this space (Glimpse being one) but they focused on solving development problems rather than application telemetry.

2 years ago, while trying to build and deploy large scale APIs, I was unable to find anything suitable to save me having to write a lot of boilerplate code to add performance counters to my applications so I coded a working prototype of performance counters for ASP .NET Web API and open sourced and shared it on Github, calling it PerfIt! for the lack of a better name. Over the last few years PerfIt! has been deployed to production in a good number of companies running .NET. I added the client support too to measure calls made by HttpClient and it was a handy addition.

From Flickr

This is all not bad but in reality, REST API calls do not cover all your outgoing or incoming server communications (which you naturally would like to measure): you need to communicate to databases (relational or NoSQL), caches (e.g. Redis), Blob Storages, and many other. On top of that, there could be some other parts of your code that you would like to measure such as CPU intensive algorithms, reading or writing large local files, running Machine Learning classifiers, etc. Of course, PerfIt! in this current incarnation cannot help with any of those cases.

It turned out with a little change and separating performance monitoring from Web API semantic (which is changing with vNext again) this can be done. Actually, not getting much credit for it, it was mainly ideas from two of my best colleagues which I am grateful for their contribution: Andres Del Rio and JaiGanesh Sundaravel.

New PerfIt! features (and limitations)

So currently at version alpha2, you can get the new PerfIt! by using nuget (when it works):
PM> install-package PerfIt -pre
Here are the extra features that you get from the new PerfIt!.

Measure metrics for a closure

So at the lowest level of an aspect abstraction, you might be interested in measuring metrics for a closure, for example:
Action action = Thread.Sleep(1000);
action(); // measure
Or in case of an async operation:
foo result = null;
Func<Task> asyncCall = async () => result = await _command.ExecuteScalar();

// and then
await asyncCall();
This closure could be wrapped in a method of course, but there again, having a unified closure interface is essential in building a common tool: each method can have different inputs of outputs while all can be presented in a closure having the same interface.

Thames Barriers Closure - Flickr. Sorry couldn't find a more related picture, but enjoy all the same
So in order to measure metrics for the action closure, all we need to do is:
var ins = new SimpleInstrumentor(new InstrumentationInfo() 
Counters = CounterTypes.StandardCounters,
Description = "test",
InstanceName = "Test instance"

ins.Instrument(() => Thread.Sleep(100));

A few things here:
  • SimpleInstrumentor is responsible for providing a hook to instrument your closures. 
  • InstrumentationInfo contains the metadata for publishing the performance counters. You provide the name of the counters to raise to it (provided if they are not standard, you have already defined )
  • You will be more likely to create a single instrumentor instance for each aspect of your code that you would like to instrument.
  • This example assumes the counters and their category are installed. PerfitRuntime class provides mechanism to register your counters on the box - which is covered in previous posts.
  • Instrument method has an option to pass the context as a string parameter. This context can be used to correlate metrics with application context in ETW events (see below).

Doing an async operation is not that different:
ins.InstrumentAsync(async () => await Task.Delay(100));

//or even simpler:
ins.InstrumentAsync(() => Task.Delay(100))

SimpleInstrumentor is the building block for higher level abstractions of instrumentation. For example, PerfitClientDelegatingHandler now uses SimpleInstrumentor behind the scene.

Raise ETW events, effortlessly

Event Tracing for Windows (ETW) is a low overhead framework for logging, instrumentation, tracing and monitoring that has been in Windows since version 2000. Version 4.5 of the .NET Framework exposes this feature in the class EventSource. Probably suffice to say, if you are not using ETW you are doing it wrong.

One problem with Performance Counters is that they use sampling, rather than events. This is all well and good but lacks the resolution you sometimes need to find problems. For example, if 1% of calls take > 2 seconds, you need on average 100 samples and if you are unlucky a lot more to see the spike.

Another problem is lack of context with the measurements. When you see such a high response, there is really no way to find out what was the context (e.g. customerId) for which it took wrong. This makes finding performance bottlenecks more difficult.

So SimpleInstrumentor, in addition to doing counters for you, raises InstrumentationEventSource ETW events. Of course, you can turn it off or just leave it as it has almost no impact. But so much better, is that use a sink (Table Storage, ElasticSearch, etc) and persist these events to a store and then analyse using something like ElasticSearch and Kibana - as we do it in ASOS. Here is a console log sink, subscribed to these events:
var listener = ConsoleLog.CreateListener();
listener.EnableEvents(InstrumentationEventSource.Instance, EventLevel.LogAlways,
And you would see:

Obviously this might not look very impressive but when you take into account that you have the timeTakenMilli (here 102ms) and have the option to pass instrumentationContext string (here "test..."), you could correlate performance with the context of in your application.

PerfIt for Web API is all there just in a different nuget package

If you have been using previous versions of PerfIt, do not panic! We are not going to move the cheese, so the client and server delegating handlers are all there only in a different package, so you just need to install Perfit.WebApi package:
PM> install-package PerfIt.WebApi -pre
The rest is just the same.

Only .NET 4.5 or higher

After spending a lot of time writing async code in CacheCow which was .NET 4.0, I do not think anyone should be subjected to such torture, so my apologies to those using .NET 4.0 but I had to move PerfIt! to .NET 4.5. Sorry .NET 4.0 users.

PerfIt for MVC, Windsor Castle interceptors and more

Yeah, there is more coming. PerfIt for MVC has been long asked by the community and castle interceptors can simply remove all cross cutting concern codes out of your core business code. Stay tuned and please provide feedback before going fully to v1!

Darrel Miller: The Simplest Possible ASP.NET Web API Template

I recently needed to create a new Web API project for some content I'm working on for a talk.  I decided I might as well use the ASP.NET Web API Template to get started.


The resulting project looked like this:


75 class files, 23 Razor templates, 34 unique Nuget packages, and 28 Javascript files before I wrote a single line of my own code.  I'm sure there is a ton of value in all of that code. However, I know that I don't currently need most of it and far worse I don't know what much of it does.  I really don't like having code in my projects that I don't understand, when I have the option of not having it there.

Bare Bones

The other option I had was to use the "Empty" template with Web API references.


This template looks a whole lot more manageable but I prefer having my API related code in a separate project to my hosting code.

Separation Of Concerns

Like this,


The advantage of this approach is that each project gets considerably simpler in terms of dependencies.  It also allows me to add a console host project, which I find much easier for debugging purposes. 


In order to run an API in a console we need to pull in the "Self Host" support libraries.  The way self host works changed in Web API 2.  Earlier versions used to be based on a thin WCF wrapper around HttpListener.  Since 2.0 it uses a Katana flavoured Owin wrapper around HttpListener. 

Installing the following Nuget into the Console app will get you started,


Hello Magic Incantation

I've built self-host APIs using the old 1.0 Web API many times.  It's a fairly simple process, create a configuration object, pass it to an instance of a HTTPServer and call Start.  In Web API 2.X it uses Katana bootstrapping code to get a HTTP server up and running.

There are two parts to bootstrapping in Katana.  One part is initializing the HTTP server and the other is initializing the Owin based application.  The challenge is finding the magic incantation code.  You need to call a static method on a class that is not the easiest to guess, and then you need to create a class that has to have a method with a signature that you need to guess.  Here is the article I found that reminded me how to do it.

The first is to call the static method Start on the WebApp class.

static void Main(string[] args)
    using (WebApp.Start<Startup>(""))


This code is in the Console Host project.  The Startup class which is referenced here should be in the API project.

The API project will need to take a dependency on the following Nuget in order to create the Startup class:


public class Startup
    public void Configuration(IAppBuilder app)
        var httpConfiguration = new HttpConfiguration();

I kept the WebApiConfig.Register method around just follow the convention.  It could just as easily be in-lined.

There are a few gotchas to running self-host.  You either need to be running Visual Studio as an administrator, or you need to authorize the process to open a HTTP Server on the base URL you provide.  If you use localhost it will just work, however if you use any other URL you will need to set the URL ACL using netsh.

That Doesn't Sound Too Painful

Seems pretty straight forward right?  For hosting in IIS/IISExpress you just use the Web Host Nuget packages.  The dependencies look like this,


And for the Self Hosted Console we need the Owin Host stuff.


The actual API project that contains all the controllers is just a class library project and only really needs access to the Core Web API nugets and the Web API to Owin adapter.


Here Is Where It Gets Whacky

The confusion starts if you go and look back at the normal non-empty ASP.NET template project.  It's a web hosted project but there is a Startup class in there.  Actually, there are two Startup classes in there that are defined as partial classes for extra bonus confusion.


So, if we are using Microsoft.AspNet.WebApi.WebHost for hosting the API, why do we need a Startup class that is part of Katana flavoured Owin?  The answer, I believe, lies in some of those 34 nuget packages that the template pulled in.


In a noble effort to build infrastructure that could be used on any Owin (with some Katana flavouring) compatible application, the security modules are built as Owin middleware. 

The absolute irony of this is the original Owin community went to great lengths to define the Owin interface in a way that required zero binary dependencies.  Unfortunately, Katana decided binary dependencies were necessary for "ease of use" and so a bunch of Katana/Owin related Nugets need to be pulled in to support these pieces of middleware, even though Owin is not actually being used to abstract away the host!

And It Gets Worse

Earlier I mentioned there were some magic incantations necessary to get the Katana host going.  And then the Katana host would call into the Startup class.  The problem is, the Webhost doesn't need use this magic.  It uses the different Global.asax WebApiApplication magic for bootstrapping.  So, how do these pieces of Security middleware get fired up?

Enter a new guest to this party,


This is one of those packages that I consider EVIL (ok, so maybe I exaggerate).  This package causes a DLL to be referenced that makes stuff happen just because I referenced it.  That's just nasty.  Anyway, this package is what you use to host an Owin-ish application using IIS.  I believe it contains the equivalent to WebApp.Start to fire up the Startup class.  This allows the security middleware to do its thing. [update: thanks to James' comment, I found an article that talks more about the SystemWeb startup process]

So here is the question.  The default Web API template references both Microsoft.Owin.Host.SystemWeb and Microsoft.AspNet.WebApi.WebHost, it contains a Global.asax and Startup classes.  Which of these two mechanisms, both of which are capable of connecting a WebAPI application to IIS is actually being used?  I have no idea and considering everything is changing again in MVC6, I have little motivation to go spelunking.  However, if I can avoid it, I'm not going to have both in the same project.  Who knows what subtle interactions exist between the two mechanisms.

Simplicity Rules

In the end, I decided to remove the Microsoft.AspNet.WebApi.WebHost reference from my WebHost project and stick with just the Owin hosting layer.  This left my Web project with just these dependencies:


Note that my web host project now has no dependencies at all on Web API.  Even more freaky is that, there isn't any code at all in the Web Host project.  The Microsoft.Owin.Host.SystemWeb  magically bootstraps the Startup class that is in the referenced API Project.  The Console host project also has no dependencies on Web API and my API project has no dependency on hosting related code.  That's what Owin is supposed to do.  But when everything is mashed up into a single project, you don't see the isolation benefits.

I've posted a complete project structure up on Github.  It doesn't have built in security, or account management, or help pages, but I'm considering doing future posts on how to add those in incrementally.

I'm not completely sure whether I wrote this post simply to get this stuff straight in my head, or whether this might actually be useful for others who are struggling to see how all the pieces fit together.  So, if you find this kind of post useful, let me know.

Image Credit: Cookie Cutter

Dominick Baier: OpenID Connect Certification for IdentityServer3

I am extremely happy to announce that IdentityServer3 is now officially certified by the OpenID Foundation.


Version 1.6 and onwards is now fully compatible with the basic, implicit, hybrid and configuration profile of OpenID Connect.

Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI

Don't contact us via this ( email address.