Archive for March, 2015

Identity Server v3 LOB Part 3 Clients

March 5, 2015 Leave a comment

This is Part 3 of a series of three posts about setting up and configuring Identity Server for a Line of Business application.


Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code

In Part 3, we’re going to walk through the MyJWTConsole application which is a simple console application which gets a JWT token and makes calls to a Web Api service and then a WCF service.

As mentioned in Part 2, to build a WSDL from an WCF using the BearerTokenMessageInspector, you must disable this in the web.config file of the WCF service first. Generate the service reference and then re-enable the message inspector.

The rest of the code in this sample, took from the Identity Server Simple Oauth authentication sample. The main point of interest in this sample over the original sample is how to build an HTTP Authorization header to pass a Bearer JWT token to WCF.

At this time, only a JWT token retrieved from the GetUserToken() endpoint can be used for making a WCF service call to a WCF service utilizing our custom BearerTokenMessageInspector. (Please read Part 2 for more information on the BearerTokenMessageInspector.)

The console application call to GetClientToken results in an AccessToken. At this time there we don’t have code in place in the WCF solution to build a ClaimsPrincipal from the AccessToken generated from GetClientToken. If somebody knows how to do this, please send the code and I’ll update Part 2 of this series to include the code.

For now, the CallWCF() method is what we’ll discuss. I found the code to build an HttpRequest header from this post.

First an HttpRequestProperty is instantiated. Then an Authorization Bearer header is added. Then the WCF Operation context is instantiated and then the Authorization header is added to the OperationScopeContext.

This Authorization header is what’s inspecting in the WCF Bearer Token inspector we created in Part 2 of this series. It’s important that the header starts with the Bearer text, space and then the Jwt token. If not, then the WCF bearer inspector will reject the request.

Once the authorization header is added, then you use the WCF client to call your service endpoints as normal.

Here is the code to build the header:

void CallWcf(TokenResponse token)


var _httpRequestProperty = new


_httpRequestProperty.Headers[HttpRequestHeader.Authorization] = string.Format(“Bearer {0}”, token.AccessToken);

//_httpRequestProperty.Headers[HttpRequestHeader.Authorization] = string.Format(“Bearer {0}”, _token.AccessToken);

var _wcfClient = new


var _context = new


using (new


_context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = _httpRequestProperty;


var _response = _wcfClient.GetData(10);


Console.WriteLine(string.Format(“WCF GetData() Call: {0}”, _response));




We like to build client service classes as PCL and add create the Service references in these classes. We then abstract away code such as setting up the Http Header. We also do this because we convert data we receive from services into Models which we can do things such as add validation code, calculated properties, implement IEditable and such.

In closing, most of the heavy lifting was done in WCF covered in Part 2. We hope these samples and posts will help others trying to figure out how to integrate Identity into their applications. Then we also hope they can help build off what we’ve started with the goal of making it easier and easier for developers to implement good solid security into their applications without it taking up so much time.

Please share any comments or send any updates you have that may help others.

Kris Frost

Lead Software Architect

SmartLogix, Inc



Categories: Identity Server

Identity Server v3 LOB Part 2 Web Api & WCF Configuration

March 5, 2015 2 comments

This is Part 2 of a series of three posts about setting up and configuring Identity Server for a Line of Business application.


Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code

In Part 2, we’re going to walk through the Web Api & WCF setup. Web Api is simple and straight forward. I’m adding a stub here for it in case we need to add more information down the road.

Web Api

While writing this post, I don’t recall if we added the IdentityWebApis to the Thinktecture.IdentityServer3 solution or the original zip contained it but the configuration is in the Starup.cs file.

In the UseIdentityServerBearerTokenAuthentication() method. Set the Authority to the URL of your Identity Server web app. Required scopes will not need to be changed unless you changed the scope for the IdSvr startup and the client application.

If you want to force authentication, in the WebApiConfig.cs you add the following line of code: config.Filters.Add(new

That’s pretty much it Web Api.


WCF was built for SOAP and natively for claims authentication, WIF is typically used with SAML tokens. However, WCF is highly configurable and with the help of some online posts we figured out how to create a custom IDispatcherMessageInspector to handle bearer tokens. The WCFJWTServices is the web app inside the Thinktecture.IdentityServer3 solution the sample we’ll use to walk through how to configure WCF to build a ClaimsPrincipal out of a JWT token obtained from IDS v3.

The following NuGet packages are required for the code below to work.

Identity Protocol Extensions for Microsoft .Net Framework 4.5

JSON Web Token Handler for Microsoft .Net Framework 4.5


The BearerTokenMessageInspector class contains the custom code which will allow our WCF services to build a ClaimsPrincipal from a JWT token.

AfterReceiveRequest() method inspects the HttpRequest headers and makes sure there is an AuthorizationHeader passed in. In Part 3 of this series, we will cover how to build an Http Authorization header to pass into WCF.

The Authenticate class is where the JWT is processed.

First to make sure we’re dealing with a JWT token, we check for Bearer at the start of the header. If present we extract the JWT token from the string.

We make a call to CanReadToken() to make sure the token is readable.

Next, we must instantiate a TokenValidationParamters variable. We use a private CreateTokenValidationParameters() method to build these options. The key here is to make sure the audience is valid and we build a X509SecurityToken which be used to Validate the JWT token.

To build the Json Web Key (JWK) dynamically, first we make a call to Identity services /core/.well-known/jwks endpoint because we need the x5c value. We parse the string into a JObject. Then we write code to parse out the x5c value. We use the x5c value to ultimately build an X509SecurityToken. Note, you can use a browser and browse to the URL, get the value and hard code it in a config file or somewhere if you don’t care about doing this dynamically.

Once we have the TokenValidationParameters, then we make a call to ValidateToken(). To do this, we must use the JwtSecurityTokenHandler. In other samples, you define your SecurityTokenHandlers in the web.config. However, what I found is that using JwtSecurityTokenHandler, the call to FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.ValidateToken() only takes one parameter. To process a JWT token, JwtSecurityTokenHandler requires you pass in the token, validationparameters and then a reference to a SecurityToken which will get built if ValidateToken() is successful.

The call to ValidateToken() if successful will generate a ClaimsPrincipal which will used to Authenticate. Once authenticated, then the Service AuthorizationContext is populated and completes the authentication.


Note: Most of the code for the Bearer Token inspector and WCF configuration below came from this post. The code to for CreateTokenValidationParameters is based off code found here.


WCF Configuration

Once the WCF code above is completed, we must make changes to the web.config for the WCF service for the new code to work. First, to wire up the BearerTokenMessageInspector, we must add an extensions element to the system.servicemodel element.



type=WCFJWTServices.BearerTokenExtensionElement, WCFJWTServices />



Next, in the Servicebehavior section, add the newly created extension.




<!– To avoid disclosing metadata information, set the values below to false before deployment –>


<!– To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information –>



useIdentityConfiguration=true />

principalPermissionMode=Always />


<!– Comment this out to update WSDL –>

<bearerTokenRequired />





Note, at the writing of this post, I find when we make changes to our services, we must comment out <bearerTokenRequired /> to generate or update the WSDL. When done, uncomment. Otherwise you will get an exception.

Additionally we have to configuration for IdentityModel.

First the following configSections are added:


type=System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089 />

type=System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089 />



The config file I use contains an element for System.IdentityModel.Services in the Compilation/Assemblies section.

The system.IdentityModel section is where define the JwtSecurityTokenHandler. I had issues with the IssuerNameRegistry section that’s commented out in the sample.




value=users />



<clear />

<!–<add type=”System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />–>

type=System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt />


certificateValidationMode=None />

<!–<issuerNameRegistry type=”System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel”>


<add thumbprint=”97249e … 158de” name=”” />








With the above configuration, any calls made to your WCF services, the BearerTokenMessageInspector code should run for any call. If there are problems, the exception reported back to the client at this point is generic and not helpful most of the time. I’d advise attaching to the IIS process and setting a break point in the AfterReceiveRequest() first then work your way from there.

Again, if you want to test the service endpoint loads in a browser to check for issues or you need to generate a WSDL, you must comment out the <bearerTokenRequired /> from the ServiceBehavior. This disables security so be sure and re-enable it when finished.


Categories: Identity Server

Identity Server v3 LOB Part 1 Hosting IDS v3 with IIS

March 4, 2015 Leave a comment

This is Part 1 of a series of three posts about setting up and configuring Identity Server for a Line Of Business application.


Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code


In part one, we are going to do a walkthrough a modified version of the Thinktecture.IdentityServer3 solution which can be found here.

In this post, we’re going to cover:

  1. How to setup a 2048+ bit certificate and then how to make sure your app pool account has permissions.
  2. Hard coding our Client & Scope data. We won’t go into many details as its fairly straight forward for the examples.
  3. We will create a simple LocalClaimsProvider as well as a Local User Service. We won’t tie directly to a database. However, in these classes you will be able to write your own code to use whatever type of repository you like.

The link for Identity Server Code above is the solution we will be working our way through in this post. I’m not going to go into how to create the entire solution from scratch.

2048 Bit Certificate

We work with predominately Microsoft technology. So we will walk through how to install a certificate on a Windows 8 computer running IIS.

  1. Start clicking Start, type in Run and in the Run text box, type in MMC.
  2. Next File, Add Remove Snap-In, Highlight Certificates and click Add

  1. When prompted, make sure to select Computer Account and click next.

  1. Leave Local Computer selected and click Finish.
  2. Expand Certificates/Persona/Certificates and right click on Certificate.
  3. Next, if you are importing a Certificate, choose Import.
  4. If you want to get a Certificate from an Active Directory, select Request New Certificate.

  1. After the certificate shows up in the Certificates folder, right click on it and select Manage Private Keys.
  2. A Permissions window will popup, click Add.
  3. In the Select Users, Computers, Service Accounts or Groups window, if your computer is in a domain, click on Locations and select your computer and click Ok.
  4. Next enter the name of the App Pool being used by the web application hosting the IdSrv web app in the Thinktecture IdentityServer3 solution you downloaded. The format would be IIS AppPool\<Type Identity’s name here>
    1. This assumes you opened the solution in a Visual Studio 2013 instance which you opened up as administrator.
    2. Doing so, a web directory in IIS should have been created. If not, however you go about doing it, make sure a virtual directory is setup in IIS.
    3. Then select or create an AppPool to use.
  5. Click Ok and you should see the Identity of the AppPool. May sure it has at least Read permissions. (May require full control, I’m not 100% sure.)
  6. Now we must open up IIS manager and make sure the web site which contains the Virtual Directory for IdSrv has its Https Binding configured to use the Certificate we just imported/created.

Virtual Directory configuration

In the IDS solution, now you will need to change app.settings to your environment. All app settings for the IdSvr web app are in IdSrv.config.

  1. First you need to configure the IdentityCertCommonName to make the subject name of the certificate we setup in the previous section. (The key for this could have been named better.). You can open the certificate and look at the subject to get the values you need to update here.
  2. If you’re running Identity locally, you can leave the other settings. I would suggest you change the IdentitySiteName to whatever you want your site name to be. This value shows up in the Login page.
  3. EnableIdentityLogging, I would leave set to true while in Dev. Obviously you would want to change this value to false in production.

Client & Scope

I haven’t had that much time to get into client and scope so I’ve just hard coded values in the existing IDS Client and Scope classes. Maybe at a later date a blog post on how to dynamically create these is warranted.

Local User Service

Our custom applications we have our own credential related tables which store user, role and security information. Identity Server Framework allows you to easily build a custom user server. In the sample code, the custom user service can be found in the IdentityServices project.

In the sample we create user bob in the LocalUserService constructor and load it into memory. However, you can do the look up in the AuthenticateLocalAsyn method if you need to authenticate against a repository.

In the Startup.cs configuration method, we instantiate the custom LocalClaimsProvider class. Then we register it with factories UserService.

Local Claims Provider

To pull back our records and build custom claims, we create a custom LocalClaimsProvider class which you can also find in the IdentityServices project. We created a custom GetUserClaims() method. Currently we manually create some claims. However, you could make your database calls here and pull back records to build your custom claims.

Note, we had to add the nameidentifier claim to satisfy @Html.AntiForgeryToken() in MVC websites.

As with the Local User Services, instantiate the custom Claims provider in Startup and add it to the factory ClaimsProvider.












Categories: Identity Server