Tuesday, 26 July 2016

How to install ADFS 2.0 and configure SAML for SSO (auto login/AD login integration)

I’ve recently had an experience of setting up Single Sign On (SSO) for an application that we sell in work (Oracle RightNow) which provides a SAML 2.0 interface for authentication and found that there is very little, useful instructions on how to install and especially to configure SAML – hopefully this information will help anyone else in a similar situation.

First of all it’s useful to know that Microsoft provide a product called Active Directory Federation Services which enables AD integration to third party services. The version of ADFS that comes with Windows Server 2008 R2 is actually version 1 which isn’t compatible with SAML and so for this article we will be using ADFS 2.0 – this can be downloaded from:http://www.microsoft.com/en-us/download/details.aspx?id=10909 (you must click Continue before you can see the Download button for the appropriate version) and there is additionally a hotfix available from: http://support.microsoft.com/kb/2681584.
Installation
This installation should ideally be carried out on a server that is web facing with an installed (not self-signed) SSL certificate and which has access to Active Directory.
  1. Run AdfsSetup.exe
  2. Click Next
  3. Click “I accept the terms in the License Agreement” and then click Next
  4. Click “Federation server” and then click Next (you may wish to setup a proxy and a farm but this is outside of the scope of this article)
  5. Click Next
  6. Once the installation is complete click Finish (the “Start the AD FS 2.0 Management snap-in when this wizard closes” tickbox is automatically checked)
SAML Configuration
  1. Click “AD FS 2.0 Federation Server Configuration Wizard”
  2. Click Next (“Create a new Federation Service” should be automatically selected – note that setting up a Federation server farm is out of scope of this article)
  3. Click “Stand-alone federation server” and then click Next
  4. Select your SSL certificate and the default Federation Service name and click Next (note that this SSL certificate should ideally be signed by a provider e.g. Thawte or Verisign and should be public facing or else you may experience issues further along)
  5. Click Next
  6. Click Close
  7. Click “Required: Add a trusted relying party”
  8. Click Start
  9. If you have a URL or file containing the configuration use this otherwise select “Enter data about the relying party manually” and click Next
  10. Enter a Display name and click Next
  11. Select AD FS 2.0 profile and click Next
  12. Click Browse and select the same certificate you used earlier and then click Next
  13. Select “Enable support for the SAML 2.0 WebSSO protocol”, enter the URL to the service providing the integration and then click Next
  14. Enter a “Relying party trust identifier” and click Add, then click Next (note it seems that this is sometimes used by the provider to confirm identification but isn’t always used)
  15. Click Next – “Permit all users to access this relying party” is automatically selected, you may want to change this later once testing is complete
  16. Click Next
  17. Click Close (“Open the Edit Claim Rules dialog for this relying party trust when the wizard closes” should be automatically selected)
  18. Click “Add Rule…”
  19. Click Next (“Send LDAP Attributes as Claims” should be automatically selected – note that only Active Directory integration is in scope for this article)
  20. Enter a “Claim rule name” and then select Active Directory under “Attribute store” (note that only Active Directory integration is in scope for this article)
  21. Select an LDAP Attribute e.g. E-Mail Addresses, and a corresponding Outgoing Claim Type e.g. E-Mail Address, and click Finish
  22. Click OK
Please note that if your provider authenticates your requests using your SSL certificate Thumbprint then expand Service (in the tree on the left hand side under AD FS 2.0) and click Certificates then double click the certificate under “Token-signing”. Click Details and you will find the Thumbprint at the bottom.
You are now ready to test your SSO:
  1. Open up a browser (ideally Internet Explorer) and navigate to https://[server address]/adfs/ls/IdpInitiatedSignon.aspx
  2. Select “Sign in to this site” (so that we know it is working) and then click “Continue to Sign In”
  3. Your site should be automatically selected so just click Go – your application should now load and you should be successfully logged in!
If you aren’t able to login go back over your settings and make sure that you have gotten everything correct. They key areas for failure are the endpoint URL (step 13 of the configuration) being incorrect, the rules (step 21) not passing the correct authentication data, your Active Directory profile being out of date or lacking data, or your SSL certificate not authenticating correctly (check my note below the configuration steps).

ASP.NET MVC 4, ADFS 2.0 and 3rd party STS integration (IdentityServer2)


Introduction

I am currently going through the architectural process of enabling 3rd party claims authentication via both active directory and a custom authentication store.  This is a common requirement for the enterprise where a users primary login is not necessarily active directory.  This complex scenario enables a single user to login via both an application account or the windows account, providing ultimate authentication flexibility.
So, how is this achieved via ADFS 2.0?.. The honest answer is it isn’t.  ADFS does not provide a pluggable model for custom authentication and only supports active directory authentication out of the box.  Custom authentication needs to be provided via the utilisation of a custom Trusted STS and ADFS 2.0.  Producing a reliable STS is no simple feat, the management, security and protocol support required to produce a working token service is a lot of work.  Luckily for us, Dominick Baier (@leastprivilege) has taken all of this pain away via Identity Server 2.0. 
Identity server 2.0 is an Open Source STS providing the ability to “swap out” elements of the architecture and wrap a custom identity store.  Once wrapped, this store can be accessed via the claims protocols (WS-Trust) and provide alternative authentication tokens.  These tokens can be used to sign-in to ADFS and authenticate the user.  With authentication complete, subsequent claims transforms can be applied inside ADFS.  This is a challenging use-case, not one for the feint hearted.
In the first part of this 2 part series I will configure ADFS 2.0 and Setup the relying party trust to an ASP.NET MVC application.  In the 2nd part in the series I will install identity server v2 and modify the ADFS forms process to delegate access to the identity server provider via WS-Trust.

Environment

To get started you will need a Windows 2012 domain server, Windows 8 (IIS configured with a self-signed cert) and Visual Studio 2012 along with Identity Server 2.0.  Knowledge of ASP.NET MVC 4.0 and Windows Identity Foundation is a bonus.
Identity Server can be downloaded from here.
  • On the Windows 2012 Server, Add the ADFS 2.0 role and configure a self-signed IIS certificate with the correct bindings.  This is explained exceptionally on the sysadminblog. Installing ADFS 2.0
  • Once installed, install and configure identity server as described in the video athttp://vimeo.com/51088126.
  • .NET 4.5 and Windows 8 ship with WIF.
  • Visual Studio 2012 ships with ASP.NET MVC 4.0, to make life easy to you enable the “Identity and Access Tool” from Tools, Extensions and Updates extension manager.  This provides an application level menu to configure your .NET application against the new federation service.

Configuring ADFS 2.0 for Forms Authentication

ADFS 2.0 by default is configured to hook directly into your existing active directory via integrated security through the browser.  To utilise the ability to login to the 3rd party STS (IdentityServer) you need to change the default configuration to Forms (more on this in part 2).  This is achieved by modifying the ADFS web.config (Found at c:\inetpub\adfs\ls\web.config) authentication preference (as below).  You can also achieve this directly by embedding the authentication type into authenticating applications url via the wauth parameter.  I.E: https://windows2012/adfs/ls?wauth=Forms
<microsoft.identityServer.web>
    <localAuthenticationTypes>
      <add name="Forms" page="FormsSignIn.aspx" />
      <add name="Integrated" page="auth/integrated/" />
      <add name="TlsClient" page="auth/sslclient/" />
      <add name="Basic" page="auth/basic/" />
    </localAuthenticationTypes>
    <commonDomainCookie writer="" reader="" />
    <context hidden="true" />
    <error page="Error.aspx" />
    <acceptedFederationProtocols saml="true" wsFederation="true" />
    <homeRealmDiscovery page="HomeRealmDiscovery.aspx" />
    <persistIdentityProviderInformation enabled="true" lifetimeInDays="30" />
    <singleSignOn enabled="true" />
</microsoft.identityServer.web>



Take note of the FormsSignIn.aspx page, this one of very few customisation points in ADFS 2.0.  We will be using this later to redirect our credentials to our 3rd party STS.


With ADFS configured, take note of the metadata address from the ADFS management console.  This is found under the service, endpoints folder, for the purposes of this post we will use the Federation Metadata endpoint.  As you can’t copy this from the MMC, here is the endpoint suffix:


/FederationMetadata/2007-06/FederationMetadata.xml


image


Creating the ASP.NET MVC 4.0 Application


In order to test the demonstration we will need a sample harness.  An easy option to demonstrate this process is to create our own claims enabled application.  To create this application launch visual studio (as an Administrator) and create a new blank basic ASP.NET MVC 4 application.  Add this application to IIS, this makes the process easier.

Please ensure you have added the “Identity and Access Tool” from Tools, Extensions and Updates extension manager.

image

In the project options ensure your application is using IIS.  This process does work under IIS Express, this is my personal preference as configuring certificates is easier inside IIS.

image

Once loaded, right click on the project and select the Identity and Access option.

imageOnce clicked, you will need the metadata URL from above, everything else will be configured automatically based on your application URL.  You may desire to change the application realm (configuration tab), this can be done after metadata configuration.

imageOnce complete your web.config will be modified.  The modifications provide the details of the identity provider and changes the application authentication settings and paths to allow for claims authentication.  This is a fairly self-explanatory configuration consisting of the audience (your application root URL), The public certificate thumbnail of the issuing identity provider, and the redirection address to the identity provider for authentication (issuer).  Realm is the relying party (service-provider) key (name) given to the identity provider to identify your application.

  <system.identityModel>
    <identityConfiguration>
      <audienceUris>
        <add value="http://localhost/Claims.Test/" />
      </audienceUris>
      <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <trustedIssuers>
          <add thumbprint="THUMBNAIL OF CERT" name="http://IdServ/adfs/services/trust" />
        </trustedIssuers>
      </issuerNameRegistry>
    </identityConfiguration>
  </system.identityModel>
  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false" />
      <wsFederation passiveRedirectEnabled="true" issuer="https://IdServ/adfs/ls/" realm="http://localhost/Claims.Test/" requireHttps="false" />
    </federationConfiguration>
  </system.identityModel.services>



The identity and access tool also adds the following settings to your application settings section.

    <add key="ida:FederationMetadataLocation" value="https://idserv/FederationMetadata/2007-06/FederationMetadata.xml" />
    <add key="ida:Issuer" value="https://Idserv/adfs/ls/" />
    <add key="ida:ProviderSelection" value="productionSTS" />



With the above complete, when you run the application you should be presented with the default ADFS login authentication homepage as below.  At this point the login process will fail as you have not configured the “relying party trust” in ADFS 2.0.  ADFS does not know whether the user has access to the relying application.  As articulated in my previous post, relying party is a MS linguistic, service-provider is more environment agnostic.image

imageNow your application is configured you need to configure the relying party trust in ADFS 2.0.  On your ADFS server, browse to the ADFS 2.0 MMC and select Relying Party Trusts, Add Relying Party Trust.  This will launch the relying party configuration wizard.

image

Screen 1, enter data manually

image

Screen 2, Give your application a meaning full name and description. image

Screen 3, Select ADFS profileimageScreen 4, Click next.  This screen is used to configure the public key provided by your application to encrypt the token send from the identity provider.  For the purposes of this post we will not be encrypting tokens.

imageScreen 5, provide the endpoint URL for your relying application.  This is the home URL as WIF utilises the ASP.NET authentication module architecture to intercept and validate tokens.  For this demo I am working from a host called Windows 8.

imageScreen 6, add the trust identifier (this is the realm as configured above).  The realm is send in the federation url to determine the relying party configuration to utilise at the IDP.

 imageScreen 7, configure the users to access the relying party (service-provider).  Permit all users initially, this can be changed by utilising authorisation rules in ADFS.

imageScreen 8, Verify your settings and save the Trust, ensuring you open the claim Edit claim rules dialog.

You will now be able to login to your application, although at this point no claims have been configured so it is rather useless.  The next dialog provides you the ability to configure and forward claims to the relying application. Without any claims your application will see no authentication properties.  Below I configure the Name claim to be sent to the ASP.NET application, this is then presented in the ASP.NET Thread.CurrentPrincipal.Name property.

image

Add Rule (Opens Rule Template Wizard)

image

Pass Through or Filter Claim Selection.

image

Call the rule “Send Name” and select the Name claim type.  Click Finish

With this now configured your application will be able to login and you should be able to obtain the claim name presented within ASP.NET.  If you used the blank ASP.NET MVC 4 template, add a new home controller and copy the code below into the Home View.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @System.Threading.Thread.CurrentPrincipal.Identity.Name
</p>

<p>
@User.Identity.AuthenticationType
</p>



Once launched and logged in, you have completed the ADFS 2.0 application configuration process.  Well Done!

image

image

Part 2, takes this to another level by modifying the ADFS 2.0 FormsSignIn.aspx to delegate authentication to Dominick Baiers (@leastprivilege) Identity Server v2, enabling custom credential stores.

Thursday, 21 July 2016

Setting Up an Angular 2 Environment Using Typescript, Npm and Webpack

This Angular 2 tutorial serves for anyone looking to get up and running with Angular 2 and TypeScript fast.
Angular 2 Beta
Last week I’ve read the great Angular 2 book from Ninja Squad. Therefore, I figured it was time to put pen to paper and start building Angular 2 applications using TypeScript. That’s why in this tutorial, we’ll learn how to start an Angular 2 project from scratch and go further by building a development environment with Webpack and more.

Getting Started

1. Developing and Building a TypeScript App
Let’s start by building our first Angular 2 application using Typescript. First, make sure you have Node.js and npm installed. You can refer to the official website for more information about the installation procedure.  Then, install Typescript globally via npm by running the following command in your terminal :
Once it is installed, we’ll setup our Typescript project by creating a tsconfig.json file in which we specify the compilation options to use for compiling our project. The typescript NPM module we just installed comes with a compiler, named tsc, that we are going to use for initializing a fresh Typescript project :
Running tsc --init create the tsconfig.json in our project directory, which looks like this :
Along with the --init parameter, we passed the following options to the compiler :
  • --target es5 : specify that we want our code to transpile to ECMASCRIPT 5. Thus, it could be run in every browser.
  • --sourceMap : generate source maps files. It helps when debugging ES5 code with the original Typescript code in the chrome devtools.
  • --experimentalDecorators and --emitDecoratorMetadata : allow to use Typescript with decorators.
Also notice that options such as module, outDir or rootDir have been added by default. Feel free to read the documentation for more compiler options.
Okay, so now that we are all setup with Typescript, we need to include the Angular 2 framework. We’ll use npm to install it locally.
So hit npm init in your terminal, and fill in some answers (you can accept the default for all the prompts). Then, install angular2 by running the following command :
You should now have a package.json file that looks like the following:
As you can see, angular2 comes with the following dependencies :
  • reflect-metadata : used to enable dependency injection through decorators
  • es6-shim and es6-promise : librairies for ES6 compatabilities and support for ES6 Promise
  • rxjs : a set of librairies for reactive programming
  • zone.js : used to implement zones for Javascript, inspired from Dart. Angular 2 uses it to efficiently detect changes
The fundamentals settings are now in place. Let’s create our first Angular 2 application.
2. Creating our First Component
The first step is to create a Typescript file at the root folder, and name it app.component.ts.
Our application itself will be a component. To do so, we’ll use the @Component decorator by importing it from ‘angular2/core‘. That’s all we need to create our Angular 2 component.
By prefixing the class by this decorator, it tells Angular that this class is an Angular component. In Angular 2, components are a fundamental concept. It is the way we define views and control the logic on the page. Here’s how to do it :
We passed in a configuration object to the component decorator. This object has two properties : selector and template. The selector is the HTML element that Angular will looking for. Every times it founds one, Angular will instantiate a new instance of our AppComponent class, and place our template.
As you may also notice we export our class at the end. This is our first class so we’ll keep it empty for simplicity.
3. Bootstrapping the App
Finally, we need to launch our application. For this, we only need two things : the Angular’s browser bootstrap method, and the application root component that we just wrote. To separate the concerns, create a new file, bootstrap.ts, and import the dependencies :
As you can see, we call the bootstrap method, passing in our component, AppComponent.
Moreover, as stated in the CHANGELOG since 2.0.0-beta.6 (2016-02-11) we may need to add the <reference ... /> line at the top of our bootstrap.ts file when using --target=es5. Feel free to check the CHANGELOG for more details.
Last but not least, we need to create an index.html file to host our Angular application. Start by pasting the following lines :
For now, it’s a very basic HTML file in which we’ve put the selector <app> that corresponds to our application root component.
But we need to add 2 more things in order to launch our application. Indeed, we need to rely on a tool to load application and library modules. For now, we’ll use SystemJS as the module loader. We’ll see later in this tutorial how to install and configure Webpack for our Angular 2 project. And finally, we need to include script dependencies in our HTML file. Let’s do it together step by step.
First, start by installing SystemJS :
Then, load it statically in the index.html just after angular2-polyfills. angular2-polyfills is essentially a mashup of zone.js and reflect-metadata.
Finally, we need to tell SystemJS where is our bootstrap module and where to find the dependencies used in our application (angular2 and rxjs) :
OK! We’re done with the settings and we can now compile and run our application.
In order to handle common tasks, include the following npm scripts in the package.json file :
The watch script runs the TypeScript compiler in watch mode. It watches TypeScript files and triggers recompilation on changes.
The serve script runs an HTTP server to serve our application, and refresh the browser on changes. I’ve used lite-server for that purpose. Install it via npm :
And, the start run the previous 2 scripts concurrently using the concurrently npm package :
So, run npm start and open your browser to http://localhost:8080. You should now briefly see “Loading…”, and then “Hello, Angular2” should appear.
Congratulations! We’ve have just finished the first part of this tutorial. Keep going to see how to set a build system using Webpack for working with TypeScript.

Creating a useful project structure and toolchain

1. Project Structure
As far, we’ve built a basic Angular 2 application with the minimum required dependencies and tools. In this section, we’ll refactor our project structure to ease the development of more complex Angular 2 applications.
By the end of this section, you will be able to build your own starter kit to get up and running with Angular 2 and TypeScript fast. More importantly, you will understand how to structure your project and what each tool is responsible for. Sounds great, isn’t it? Let’s do it!
The first step is to revamp the file structure of our project. Here’s how it will look :
There are some new files, but don’t worry we will dive into each one of them through this section. What’s important for now, it’s to understand that we’ll use the component approach in our application project. This is a great way to ensure maintainable code by encapsulation of our behavior logic. Hence, each component will live in a single folder with each concern as a file: style, template, specs, e2e, and component class.
Before going further let’s reorganize our files as follow :
You should also update the path in bootstrap.ts :
Great! Now it’s time to dive in into Webpack.
2. Installing and Configuring Webpack
Webpack will replace SystemJS that we have used until now, as a module loader. If you need an explanation on what is Webpack for, I highly recommand you to take a look at the official documentation. In short, webpack is a module bundler. “It takes modules with dependencies and generates static assets representing those modules“.
Start with installing webpack, webpack-dev-server, and the webpack plugins locally, and save them as project dependencies :
Now, let’s configure Webpack for our development workflow. For this purpose we’ll create a webpack.config.js. Add the following settings in your config file :
  • The entry specifies the entry files of our Angular application. It will be use by Webpack as the starting point for the bundling process. As you may notice we specify our bootstrap file, but also a new file named polyfills.ts. It will contain all the dependencies needed to run our Angular2 application. Before that, we’ve put those deps directly inside our index.html. They now live in a separate file :
  • The output tells Webpack what to do after completing the bundling process. In our case, the dist/ directory will be use to output the bundled files namedapp.bundle.js and polyfills.bundle.js with th following source-map files.
  • The ts-loader is used to transpile our Typescript files that match the defined test regex. In our case it will process all files with a .ts or .tsx extension.
  • The raw-loader is used to support html files as raw text. Hence, we could write our component views in separate files and include them afterward in our components. You need to install them using npm :
  • The CopyWebpackPlugin is used to copy the static assets into the build folder.
  • Finally, the metadata are used by the HtmlWebpackplugin to generate our index.html file. In the index.html, we use the host and port data to run the webpack dev server in development environment. See how this file has been simplified :
Feel free to add you own stylesheets files under /src/assets/css as I did with my styles.css file.
You should now have a project structured like so :
We need one more thing to be all set up. As mentionned before, we will write the views in separated file. So, create an app.html file and refer to it in your app.components.ts.
Finally, we have to install the node typings definition to be able to require file inside our component as we did for the view. Hence, to do so run the following commands, and complete the tsconfig.json to exclude some files :
As you can notice in my tsconfig.json file below, there are some extra options that are Atom IDE specific features. Feel free to read the documentation about it: atom-typescript/tsconfig.json.
If you want to know more about typings read the following pages on Github : Microsoft/TypeScript and typings/typings.
Ok! Now it’s time to build and run our application using Webpack. Let’s create some npm scripts to handle those operations.
3. Using npm as a Task Runner
We will simply use npm to define and run our tasks : one for the build process, and one for running the development server.
We can now run npm start and visit http://localhost:8080 to see our app running.

Going further

In today’s tutorial, we setup an Angular 2 environment on which you can now build you entire application. We showcased how to structure our project and how Webpack can be used to gain productivity while developping Angular 2 application with Typescript.
If you have been following along with the source or building from scratch, you should now be able to build your own Angular 2 development environment. Else, fork the Github repo and have fun!
Stay tuned, in the next tutorials we will see how to include unit testing with Karma and Jasmine, and we’ll also use Protactor for end-to-end story.

The best ways to connect to the server using Angular CLI

Everybody who has used  Angular CLI  knows that it is a powerful tool which can take a front-end development job to a completely dif...