Marcin Drobik

software journeyman notes

OWIN Authentication with Azure

Here are steps needed to enable authentication with Azure Active Directory inside your Owin app.

Configure the AD

First, you need an Active Directory Domain configured for your app (I'm using the classic Azure Portal).

  1. Create Directory

    ... by going to Azure Portal -> Active Directory -> New -> Directory -> Custom Create
    I used following values:
    Name: mandroauthtest
    Domain Name: mandroauthtest

  2. Add User to Domain

    ... by going Azure Portal -> Active Directory -> mandroauthtest -> Users -> Add User -> "New User in organisation"
    I used following value for User Name: test (

  3. Add application to Domain

    ... by going to Azure Portal -> Active Directory -> mandroauthtest -> Applications -> Add -> "Add Application my organisation is developing"
    I used following values:
    Name: authdemo
    Type: Web Application / Web API
    Login url: http://localhost:27898/
    App ID Uri: http://authtest

  4. Get your Client ID

    ... by going to Azure Portal -> Active Directory -> mandroauthtest -> Applications -> authdemo -> Configure Copy your Client ID (looks like GUID).

We now have everything setup on Azure side.


Let's now create an app that will show some content only to Authenticated users.

  1. Install Owin, i.e: Install-Package Microsoft.Owin.SelfHost
  2. Let's used following boiler plate code:

    using System;
    using Microsoft.Owin.Hosting;
    namespace Owin.AzureAuth.Demo
        class Program
            static void Main(string[] args)
        internal class Startup
            public void Configuration(IAppBuilder app)
    #if DEBUG
  3. Install security packages:

    Install-Package Microsoft.Owin.Security.OpenIdConnect
    Install-Package Microsoft.Owin.Security.Cookies
  4. Add authentication setup code

    app.UseCookieAuthentication(new CookieAuthenticationOptions ());
    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions       
        ClientId = <your Client ID here>,
        Authority = "",
        PostLogoutRedirectUri = "http://localhost:27898/",

    The code above setups both Cookie and OpenId. The open id is the main active authentication middleware. Cookies however are used to store the authentication token.

  5. Following code will force authentication. Place it before middleware you want to secure, i.e. app.UseWelcomePage("/");.

    app.Use(async(context, next) =>
       if (context.Authentication.User == null )
          context.Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
          await next();
  6. Go to browser (http://localhost:27898), you'll be redirected to Microsoft Live login page. You can use the credentials we created in first part (


comments powered by Disqus