New Pluralsight Course: “Web API v2 Security”

It is finally online! Hope you like it.

http://pluralsight.com/training/Courses/TableOfContents/webapi-v2-security

Posted in ASP.NET, AuthorizationServer, Katana, OAuth, OWIN, WebAPI | 6 Comments

List of Libaries and Projects for OpenID Connect and JWT

..can be found here

http://openid.net/developers/libraries/

Posted in OAuth, OpenID Connect, WebAPI | Leave a comment

Introducing Thinktecture IdentityManager

Originally posted on brockallen:

Back in 2005 when Microsoft released the ASP.NET MembershipProvider API, they also included in Visual Studio the ASP.NET WebSite Administration tool. This was used by developers to quickly create and edit users to populate the MembershipProvider database. Given Microsoft’s move away from Membership, this tool was removed from Visual Studio and many developers have missed it. In a similar vein, ever since I built MembershipReboot I’ve been meaning to provide an admin tool to allow similar functionality that was in the ASP.NET WebSite Administration tool.

Well, I finally got around to building said tool — introducing Thinktecture IdentityManager.

IdentityManager is developed as OWIN middleware and can easily be hosted in any OWIN host. Also given the recent release and popularity of ASP.NET Identity, I designed it to support both MembershipReboot and ASP.NET Identity.

It’s very early in its development, but this first preview version is intended to allow developers…

View original 167 more words

Posted in Uncategorized | Leave a comment

Announcing Thinktecture IdentityServer v3 – Preview 1

The last months we’ve been heads down re-writing IdentityServer from scratch (see here for background) – and we are now at a point where we think we have enough up and running to show it to you!

What we’ve done so far

  • Started with File –> New
  • Implemented OpenID Connect basic and implicit client profile (including support for form post response mode)
  • Implemented support for OpenID Connect discovery documents and session logout
  • Implemented OAuth2 code, client credentials, password and assertion grants
  • Created a general purpose login page and consent screen for local and external accounts
    • created out of the box support for MembershipReboot and ASP.NET Identity
    • integrated existing Katana authentication middleware for social providers
      • and made that all pluggable
  • Defined an authorization enforcement policy around clients, flows, redirect URIs and scopes
  • Designed everything to run on minimal data access interfaces so you can seamlessly scale from in-memory objects to simple config files up to relational or document databases for configuration and state management
  • Designed everything to be API-first
  • Defined several extensibility points that allow customization of request validation, token creation, claims acquisition and transformation and more
    • and yes, we don’t use MEF anymore …
  • Split up IdSrv into composable components like core token engine and authentication, configuration APIs, configuration UIs and user management
    • These components use OWIN/Katana and Web API as abstractions which means we have quite a bit of flexibility when it comes to logical hosting – embeddable in an existing application or standalone
    • When it comes to physical hosting, we have no dependency on IIS and System.Web which means you can use a command line, OWIN host, an NT Service, of course IIS or any other OWIN/Katana compatible server

Minimal startup code:

public void Configuration(IAppBuilder app)

{

    app.Map(“/core”, coreApp =>

        {

            var factory = TestOptionsFactory.Create(

                issuerUri:         https://idsrv3.com,

                siteName:          “Thinktecture IdentityServer v3″,

                certificateName:   “CN=idsrv3test”,

                publicHostAddress: http://localhost:3333);

                   

            var opts = new IdentityServerCoreOptions

            {

                Factory = factory,

            };

 

            coreApp.UseIdentityServerCore(opts);

        });

}

What’s missing?

  • quite a bit, e.g.
  • a persistence layer for configuration and state – everything is in-memory right now which is good enough for testing
  • Refresh tokens
  • Admin UI and APIs
  • OpenID Connect session management and cleanup
  • Support for WS-Federation and OpenID Connect based identity providers for federation
  • A lot more testing
  • Your feedback!

What’s next?

  • We’ve defined several milestones over the next months for implementing the next rounds of features. We currently plan to be done with v1 around end of summer.
  • Participate in OpenID Connect compatibility and interop testing (see here).

Where to get it?

The github repo is here, the issue tracker here and the wiki here. We also recorded videos on Overview, Samples Walkthrough and Extensibility Check them out…

Oh – and I should mention – while designing IdentityServer v3 we realized that we really also need a good solution for managing users, identity, claims etc – and that this should be ideally a separate project – so I’d also like to announce Thinktecture IdentityManager – head over to Brock’s blog to find out more!!!

Looking forward to your feedback!

Posted in ASP.NET, AuthorizationServer, IdentityModel, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI | 5 Comments

Integrating AuthorizationServer with Auth0

AuthorizationServer is a lightweight OAuth2 implementation that is designed to integrate with arbitrary identity management systems. I wrote about integration with Thinktecture IdentityServer, ADFS and even plain Windows integrated authentication before.

Another really compelling and feature rich identity management is Auth0. Auth0 supports local account databases, federation with almost anything you can imagine, claims transformation, UI customization and a great documentation and SDKs. The fact that it is also available as an on-premises appliance (in addition to their cloud offering) is especially interesting for my European customers and me.

Here’s what I had to do to integrate AuthorizationServer with Auth0.

1 Create a new application in Auth0
Auth0 has support for many pre-packaged application types like Salesforce, Office 365 or SharePoint. Since AS is a WIF-based application, I chose WS-Fed (WIF) App.

1 Create App

Next, you can choose which identity providers or account types you want to allow for your new application (Auth0 calls that connections). I decided to start with local accounts only, and to add other connections later once I have the basic setup up and running.

2 Select Connections

One thing I especially like about Auth0 is their personalized documentation and walkthroughs. All of the samples and config snippets they show already have your URLs, keys etc. in it, so you can simply copy and paste the “sample” configuration to your local project. You start by entering some basic information about your application:

3 Initial Config

..and are being presented with a fully working WIF configuration:

4 Config Snippet

Another option would be to point your Identity & Access Tool or the ASP.NET project template to your personalized WS-Federation metadata endpoint. Very nice!

Next, I created a user account in Auth0 that should act as an AuthorizationServer administrator:

5 Admin User

2 Setup AuthorizationServer
I then grabbed a fresh copy of AuthorizationServer from Github and did the standard installation steps (see here).
Since Auth0 already gave me a ready to use federation configuration, I only had to copy that over to the identityModel.config and identityModel.services.config files (in the config folder) respectively. Then I ran the initial configuration “wizard” and entered the user ID of the admin account I created earlier.

6 AS Initial Config

Now when I try to enter the admin UI, I am presented with the Auth0 login screen and I can start creating AS applications, clients, etc. (see also this walkthrough).

7 Auth0 Login

3 Using AuthorizationServer with Auth0 Accounts
To do some testing, I quickly created a few more local accounts (alice and bob of course) and used the standard AS sample to inspect the resulting access tokens. Here’s the output for the code flow sample client:

{
    “iss”: “AS”,
    “aud”: “users”,
    “nbf”: 1394728033,
    “exp”: 1394731633,
    “client_id”: “codeclient”,
    “scope”: [
        "read",
        "search"
    ],
    “sub”: “auth0|52e50b42f66ae38e8f00057e”
}

Auth0 uses a NameIdentifier claims and the idp|userid format to uniquely identify a user account. AS understands that by default and strips away all other claims. If you want to pass through all claims from Auth0, you can set the filterIncomingClaims appSetting in web.config to false, which results in all profile claims, e.g.:

{
  “iss”: “AS”,
  “aud”: “users”,
  “nbf”: 1394728205,
  “exp”: 1394731805,
  “client_id”: “codeclient”,
  “scope”: [
    "read",
    "search"
  ],
  “sub”: “auth0|52e50b42f66ae38e8f00057e”,
  “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier “: “auth0|52e50b42f66ae38e8f00057e”,
  “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress “: “bob@leastprivilege.com”,
  “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name “: “bob@leastprivilege.com”,
  “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn “: “bob@leastprivilege.com”,
  “http://schemas.auth0.com/identities/default/provider “: “auth0″,
  “http://schemas.auth0.com/identities/default/connection “: “Username-Password-Authentication”,
  “http://schemas.auth0.com/identities/default/isSocial “: “false”,
  “http://schemas.auth0.com/clientID “: “wU1MA7nUlpoMryMUqrd39CeXTMio1O6x”,
  “http://schemas.auth0.com/created_at “: “Sun Jan 26 2014 13:18:58 GMT+0000 (UTC)”,
  “http://schemas.auth0.com/email_verified “: “false”,
  “http://schemas.auth0.com/nickname “: “bob”,
  “http://schemas.auth0.com/picture “: https://secure.gravatar.com/…silhouette80.png,
  “http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod “: “http://schemas.microsoft.com/ws/2008/06/identity/authenticationmethod/password “,
  “http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant “: “2014-03-14T00:29:57.101Z”
}

So you can get a whole lot of information about the Auth0 user from their authentication token. You can either modify the claims via the Auth0 profile editor in the web interface or modify the claims transformation logic either in Auth0 or AS to just pick the claims that are relevant to your APIs.

8 Profile editor

4 Adding external Accounts
Auth0 also allows adding external identity providers, e.g. social logins like Facebook or Google as well as enterprise systems like ADFS, WAAD, Ping Identity or LDAP and SAML2p based systems. You can simply “activate” those connections per application.

9 External connections

Once activated, you will see the new identity providers on the login dialog.

5 Resource Owner Password Flow and programmatic authentication with Auth0
For supporting the OAuth2 resource owner password flow, AS needs programmatic access to the Auth0 authentication endpoint. That’s easily possible too, and via the excellent documentation system, you can inspect the relevant endpoint as well as a sample payload.

10 API Docs

The above endpoint will return an OpenID Connect style JWT identity token. With that information, you can use the standard AS extensibility point for resource owner flow to programmatically authenticate users against the Auth0 user store:

public class Auth0ResourceOwnerCredentialValidation : IResourceOwnerCredentialValidation

{

    string endpoint = https://leastprivilege.auth0.com/oauth/ro”;

    string issuer = https://leastprivilege.auth0.com/”;

    string client_id = “wU…6x”;

    string client_secret = “j6a…Z9″;

 

    public ClaimsPrincipal Validate(string userName, string password)

    {

        var client = new Thinktecture.IdentityModel.Client.OAuth2Client(

            new Uri(endpoint),

            client_id,

            client_secret,

            OAuth2Client.ClientAuthenticationStyle.PostValues);

 

        var response = client.RequestResourceOwnerPasswordAsync(

            userName,

            password,

            “openid profile”,

            new Dictionary<string, string>

            {

                { “connection”, “Username-Password-Authentication” }

            }).Result;

 

 

        if (!response.IsError)

        {

            return FederatedAuthentication.FederationConfiguration

                                            .IdentityConfiguration

                                            .ClaimsAuthenticationManager

                                            .Authenticate(“”, ValidateIdentityToken(response.IdentityToken));

        }

 

        throw new InvalidOperationException(response.Error);

    }

 

    private ClaimsPrincipal ValidateIdentityToken(string identityToken)

    {

        var handler = new JwtSecurityTokenHandler();

          

        var parameters = new TokenValidationParameters

        {

            AllowedAudience = client_id,

            ValidIssuer = issuer,

            SigningToken = new BinarySecretSecurityToken(
             
Base64Url
.Decode(client_secret))

        };

 

        return handler.ValidateToken(identityToken, parameters);

    }

}

4 Where to go from here
There are some advanced features I haven’t tried but wanted to mention. First of all you have full control over the login page look and feel by updating the HTML/script/CSS of your tenant. You can also write dynamic claims transformation rules using JavaScript, which looks pretty powerful. And last but not least, when you run Auth0 on-premises, you can also connect it to Active Directory as well as custom databases like SQL Server.
So all in all this is a pretty complete package when you are looking for an out of the box identity and federation solution – and together with AuthorizationServer you get OAuth2 application authorization model backed by all the various authentication options that Auth0 provides. Nice!

Posted in ASP.NET, AuthorizationServer, OAuth, WebAPI | Leave a comment

The Web API v2 OAuth2 Authorization Server Middleware–Is it worth it?

Adding the concept of an authorization server to your web APIs is the recommended architecture for managing authentication and authorization. But writing such a service from scratch is not an easy task.

To simplify that, Microsoft included an OAuth2 based authorization server “toolkit” as part of the Katana project, which is also used in the standard Web API templates that ship with Visual Studio 2013. I get a lot of questions about how this middleware works, whether I like it, what the limitations are and if I would use it at all. To make this discussion easier in the future – here’s my take.

What I like
Microsoft’s intentions were really noble – they tried to make it very easy for the “average” (read: not security expert) developer to do the right thing – namely push them to an architecture where authentication and authorization decisions can be abstracted away into a separate “component” while using a standard protocol (OAuth2). This would result in token-based authentication in general – and would also get rid of the cookie and CSRF problems for SPAs in particular. The pit of success so to speak.

The middleware produces encrypted and signed tokens (protected with the usual machine key mechanism) which can be automatically consumed by the corresponding token middleware, creates separate endpoints,  forces you to at least think about client validation and requires SSL by default.

The two most common flows I see for Web API clients is resource owner flow and implicit flow. Resource owner flow is now very easy to implement with the new AS middleware. It really just takes a few lines of code and you are done. I like that a lot (if resource owner flow is the right architecture for you – which is a different discussion). I wrote about the implementation here.

The same applies to client credentials flow (not so common), and custom grant types (even less common).

What I don’t like
If you want to do anything beyond what I described so far, the complexity increases unproportionally – e.g. adding a “simple” extension to resource owner flow – namely the concept of refresh tokens, suddenly forces you to understand OAuth2 (see here) and the security implications around it. You also have to implement persistence yourself – which on its own is challenging if you would follow security best practices and the OAuth2 threat model. No pit of success.

Another example is implicit flow, which is often the more appropriate flow for native or JS based applications. Unfortunately the middleware implementation is riddled by the fact there is no Katana or Web API based view engine yet, which means you need to use an additional framework when you want to render proper login or consent screens. Scattering the logic of the flow between views, controllers and middleware providers doesn’t make it more intuitive. And when you made it that far, it seems some parts of the protocol are just missing – like returning proper errors from the UI.

In other words – the middleware forces you to understand the underlying protocol, forces you to understand the middleware itself and all its various callbacks and extensibility points, makes you implement the hard (and security related) things yourself, and in the end you have to live with the restrictions that the thin abstraction imposes on you.

Next is documentation – the built-in templates don’t do a very good job of isolating the features and trade-offs of the middleware. They combine all the new concepts of Katana, OWIN, OAuth2 and ASP.NET identity into a hard to follow sample “application”. It took me three blog posts (see here) to describe how the “Individual Accounts” sample works – and I am sure I missed some of the subtleties.

Just recently Microsoft released this very long article that describes all the aspects of the OAuth2 middleware – read it here. It’s good that this document finally exists, but I am not a huge fan of this disclaimer – after you followed the 83 easy steps:

Note: This outline should not be intended to be used for creating a secure production app. This tutorial is intended to provide only an outline on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware.

What would I like to see instead?
Well – it is always easy to bitch and moan about other people’s work – but I was actually asked for feedback during the development of the middleware – and this is just a repeat of what I said back then.

OAuth2 is not the most straightforward protocol to implement – but it is also not too hard. When you start working on it, you realize that the “protocol aspects” of it – like query string formats or response message layouts are actually the easiest part. The hard part is state management, secure data storage, input validation etc. And my main point of criticism is, that the middleware does not help you in any way with that. It simply implements a framework that exposes a developer to a limited subset of OAuth2 without really understanding the use cases.

Much more useful would have been super easy to use, focused and specific implementations of the two most common flows for Web API apps: resource owner and implicit – including ready to use support for login and consent page, scope handling and refresh tokens. That would have also included a persistence layer and state management. Our OSS project AuthorizationServer e.g. takes care of all that.

So overall I’d conclude with saying – even when the intentions were good – the whole authorization server middleware project was a little over ambitious and I can’t really recommend using it (besides for the most simplest cases).

Posted in AuthorizationServer, IdentityServer, Katana, OAuth, OWIN, WebAPI | 5 Comments

OAuth2 and OpenID Connect Scope Validation for OWIN/Katana

In OAuth2 or OpenID Connect you don’t necessarily always use the audience to partition your token space – the scope concept is also commonly used (see also Vittorio’s post from yesterday). A while ago I created a Web API authorize attribute to do the validation based on scopes (see here).

Since scope-based token validation can become so fundamental to your APIs – I moved the logic to an OWIN/Katana component so all frameworks can benefit from it, e.g.:

public class Startup

{

    public void Configuration(IAppBuilder app)

    {

        // read OR write

        app.RequireScopes(“read”, “write”);

 

        app.UseWebApi(WebApiConfig.Register());

    }

}

or…

public class Startup

{

    public void Configuration(IAppBuilder app)

    {

        // read AND write

        app.RequireScopes(“read”);

        app.RequireScopes(“write”);

 

        app.UseWebApi(WebApiConfig.Register());

    }

}

 

Source code here, sample here, nuget here.

Posted in IdentityModel, Katana, OAuth, OpenID Connect, OWIN, WebAPI | 1 Comment