Deep Dive on Azure Active Directory for...

Preview:

Citation preview

Deep Dive on

Azure Active Directory

for Developers Jelle Druyts | Premier Field Engineer | Microsoft Services

Agenda

Azure Active Directory for developers

Developing for Azure Active Directory

Azure Active Directory

for Developers

Browser

Native app

Server app

Web application

Web API

Web API

Web API

Today’s Applications

Clients using wide variety of devices/languages/platforms

Server applications using wide variety of platforms/languages

JavaScript

Standard-based, HTTP-based protocols for maximum platform reach

Browser

Native app

Server app

Web application

Web API

Web API

Web API

WS-Federation SAML 2.0

OpenID Connect

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

Authentication Protocols

JavaScript

OAuth 2.0

What Is Azure Active Directory?

Azure Active Directory

• Cloud-scale identity service

• Supports modern authorization & authentication scenarios

• REST-based Graph API

Reduces or removes custom security implementation

• Authenticating users

• Detecting suspicious activity

• Authorizing users via Groups or Roles (RBAC)

• B2C will allow social and “application local” accounts

Azure Active Directory for Developers

Tokens in Azure AD

Access tokens have a lifetime of 1 hour

• Allows quick revocation of access

Refresh tokens allow silent renewal of the access token

• User does not have to sign in again (as long as access wasn’t revoked)

Refresh token lifetime

• Azure AD accounts: 14 days, sliding up to maximum 90 days

• External accounts (e.g. Microsoft Account): 12 hours

• Can be invalidated, e.g. when user’s password changes

Multi-Resource Refresh Token

• Can be used to get access token to a different service if delegation exists

OAuth 2.0 Access and Refresh Tokens

JSON Web Token (JWT) Base64 URL encoded JSON with optional signature

{ "typ": "JWT", "alg": "RS256" "x5t": "7dD-gec…" }

{ "iss": "http://sts.contoso.com/", "aud": "http://api.contoso.com/", "client": "http://www.contoso.com/", "iat": "1432235632", "exp": "1432239532", "name": "John Doe" "scope": ["read", "write"] }

eyJ0eXAiOiJKV1QiLCJhbGciO.eyJpc3MiOiJodHRwOi8vc3RzbnRc28uY29tI.ZT8zzX6vg9I5HvTm4f8f

Header Claims Signature <dot> <dot>

Token Signing Key

Tokens for all tenants are signed by same key

• Keys published via metadata

• https://login.microsoftonline.com/common/.well-known/openid-configuration

• Keys roll on periodic basis

Applications must handle

• Periodically refreshing keys from metadata

• Handling multiple keys

• Microsoft samples and libraries do this automatically

Ensuring the tokens really come from Azure Active Directory

Registering Applications

Register your application via

• Azure Management Portal

• Visual Studio

• Azure AD REST API’s

Non-admins may register applications by default

• Can be disabled

The management portal only shows a subset of functionality

• Advanced features available via application manifest

• OAuth 2.0 permissions, application roles, group claims, certificates, …

Azure AD must know about your app before it will issue tokens

Application Configuration

All applications

• Name: shown when authenticating/authorizing

• Client ID: GUID of the application in Azure AD

Native client applications (public clients)

• Redirect URI’s: signaling the end of the flow

Web applications and/or Web API’s (confidential clients)

• Sign-On URL: where to send users from the application access portal

• Single- or Multi-Tenant

• Keys

• App ID URI: unique identifier that clients request access to

• Reply URL’s: where to allow tokens to be sent

What Azure AD needs to know about your app

Permissions To Other Applications

Application Permissions

• Access another application as the calling application

Delegated Permissions

• Access another application on behalf of the user

Declaring access to other applications

Consent

Consent can be granted by user or by organization admin

• Stored in Azure AD for web applications

• Stored in the Refresh Token for native applications

Granting permissions to an application

Multi-Tenant Applications

Single tenant application

• App for users in a single organization

• Admin or user registers app in directory tenant

• Sign in at https://login.microsoftonline.com/contoso.com/<protocol>

Multi-tenant application

• App for users in multiple organizations

• Admin or user registers app in developer’s directory tenant

• Admin configures application to be multi-tenant

• Sign in at https://login.microsoftonline.com/common/<protocol>

• User prompted to consent based on permissions required by application

• Consent registers application in user’s tenant

Targeting other organizations

Groups & Roles

Groups (defined in Azure or synchronized from on-premise AD)

• Token contains “groups” claims (must opt-in)

• When there are too many groups, “overage” claim points towards Graph API

• Not all flows support group claims (e.g. not over URL query parameters)

Application Roles

• Application can declare application-specific roles

• Administrator can assign users or groups to roles

• Token then contains “roles” claims

Authorization features for applications

Developing for

Azure Active Directory

Developing For Azure AD

Register your application in Azure AD

• Retrieve Client ID & (optional) Keys

• Configure Redirect URL

• Configure API permissions

Add code to your application for sign in

• Web: WS-Federation, SAML 2.0, OpenID Connect

• Other (native, desktop, server): OAuth 2.0

Add code to your Web API for OAuth 2.0 Bearer Token authorization

And mostly equivalent when using Windows Server 2016 on-premise

Browser

Native app

Server app

Web application

Web API

Web API

Web API

WS-Federation SAML 2.0

OpenID Connect

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

Microsoft Security Libraries

JavaScript

OAuth 2.0

OIC-MW

ADAL.JS

ADAL

BT-MW BT-MW

BT-MW

ADAL

ADAL

ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Active Directory Authentication Library

ADAL

• Consistent API across platforms for acquiring tokens

• Pluggable cache for token persistence

• Automatic refresh of Access Tokens using Refresh Tokens

• Works against Azure AD as well as Windows Server

ADAL.JS

• Sign in and bearer token support for JavaScript

• Provides current user info

• Secure Web API invocation via JavaScript/CORS

Acquiring, refreshing & caching tokens

WS-Federation SAML 2.0

OpenID Connect

Native app

Server app

Web API

Web API

Web API

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

JavaScript

OAuth 2.0

ADAL.JS

ADAL

BT-MW BT-MW

BT-MW

ADAL

ADAL

ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Browser Web

application

OIC-MW

Adding Sign-In To ASP.NET

Adding Sign-In To ASP.NET

Use OpenID Connect OWIN Middleware

• “Microsoft.Owin.Security.OpenIdConnect” NuGet package

app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = "187ff6ec-eae0-4376-807d-5ffa3d28645b", Authority = "https://login.microsoftonline.com/contoso.com", } );

[Authorize] public class HomeController : Controller { ... }

OpenID Connect

Native app

Server app

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

JavaScript

OAuth 2.0

ADAL.JS

ADAL ADAL

ADAL

ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Browser Web

application

WS-Federation SAML 2.0

OpenID Connect

OIC-MW

Protecting Web API’s

Web API

Web API BT-MW

BT-MW

Web API BT-MW

Protecting Web API’s

Use Bearer Token OWIN Middleware

• “Microsoft.Owin.Security.ActiveDirectory” NuGet Package

• Automatically acquires signing keys and issuer values

app.UseCors( ... ); // For SPA clients app.UseWindowsAzureActiveDirectoryBearerAuthentication new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { ValidAudience = "http://example.org/mywebapi" }, Tenant = "contoso.com" } );

[Authorize] public class ProductController : ApiController { ... }

OAuth 2.0 Bearer Token Authorization

Calling Web API’s

Use Active Directory Authentication Library (ADAL)

• “Microsoft.IdentityModel.Clients.ActiveDirectory” NuGet Package

Retrieve an access token and send it on the “Authorization” HTTP header

var context = new AuthenticationContext( "https://login.microsoftonline.com/contoso.com"); var result = context.AcquireToken( ... ); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

General pattern

Native app

Server app

Web API

Web API

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

JavaScript

OAuth 2.0

ADAL.JS

BT-MW

BT-MW

ADAL

ADAL

ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Browser

WS-Federation SAML 2.0

OpenID Connect

OIC-MW

Calling Web API’s – Web App

Web API

ADAL

BT-MW

Web application

Calling Web API’s – Web App

At OpenID Connect sign-in

• Receive an ID Token + Authorization Code

• Use ADAL to redeem the Authorization Code for an Access + Refresh Token

• Save the tokens in a persistent per-user cache

When you need to access a resource

• Initialize ADAL with the same cache you used earlier

• Ask for the token you need via AcquireTokenSilent

• Upon failure, trigger re-authentication

OpenID Connect (user identity)

new OpenIdConnectAuthenticationOptions { Notifications = new OpenIdConnectAuthenticationNotifications() { AuthorizationCodeReceived = async (context) => { var userTokenCache = GetTokenCacheForUser(context.AuthenticationTicket.Identity); var context = new AuthenticationContext(authority, userTokenCache); var result = await context.AcquireTokenByAuthorizationCodeAsync( ... ); } } }

Calling Web API’s – Web App

Call a Web API using the client identity

• Access a resource on behalf of the client application itself

• Not in the context of a particular user

No user interaction required, only client id + secret (“key”)

OAuth 2.0 Client Credentials Grant (client identity)

var context = new AuthenticationContext(aadAuthority); var credential = new ClientCredential(clientId, clientSecret); var authenticationResult = await context.AcquireTokenAsync(resourceId, credential);

Server app

Web API

Web API

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

JavaScript

OAuth 2.0

ADAL.JS

BT-MW

BT-MW

ADAL

ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Browser

WS-Federation SAML 2.0

OpenID Connect

OIC-MW

ADAL

Web application

Native app ADAL

Calling Web API’s – Native Client

Web API BT-MW

Calling Web API’s – Native Client

Native clients (phone, tablet, desktop, …)

• Also registered as an application in Azure AD

• Has a Client ID but cannot have its own credentials

Authentication typically pops up a browser window

• Server-driven sign-in experience (same as web application sign-in)

• Allows consent, MFA, … independently configured of the application

OAuth 2.0 Authorization Code Grant, Public Client

Web API

Web API

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

JavaScript

OAuth 2.0

ADAL.JS

BT-MW

BT-MW ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Browser

WS-Federation SAML 2.0

OpenID Connect

OIC-MW

ADAL

Web application

Native app ADAL

Server app ADAL

Calling Web API’s – Daemon

Web API BT-MW

Calling Web API’s – Daemon

Same as Web App to Web API using client identity

Non-interactive methods depending on the platform

• Kerberos

• Name + Secret (Client ID + Key)

• X509 Certificate

OAuth 2.0 Client Credentials Grant

# Azure PowerShell – Assign a certificate to an Azure AD application service principal $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certificate.Import("MyDaemonCertificate.cer") $certificateData = [System.Convert]::ToBase64String($certificate.GetRawCertData()); New-MsolServicePrincipalCredential -AppPrincipalId "e1055105-33b1-46e4-96a8-16d811aceb87" # AAD Application Client ID -Type asymmetric -Usage Verify -Value $certificateData -StartDate $certificate.NotBefore -EndDate $certificate.NotAfter

Web API

Web API

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0 BT-MW

BT-MW ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

ADAL

Browser

WS-Federation SAML 2.0

OpenID Connect

OIC-MW

ADAL

Web application

Native app ADAL

Server app ADAL

JavaScript ADAL.JS

Calling Web API’s – SPA

Web API BT-MW

Calling Web API’s – SPA

Enable “oauth2AllowImplicitFlow” in Azure AD Application Manifest

Use Active Directory Authentication Library for JavaScript (ADAL.JS)

• Even easier when using AngularJS

// ADAL configuration adalProvider.init( { instance: "https://login.microsoftonline.com/", tenant: "contoso.com", clientId: "187ff6ec-eae0-4376-807d-5ffa3d28645b" }, $httpProvider); // Route registration $routeProvider.when("/Home", { controller: "homeCtrl", templateUrl: "views/Home.html", requireADLogin: true });

OAuth 2.0 Implicit Flow

Web API

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

OAuth 2.0

BT-MW ADAL

ADAL: Active Directory Authentication

Library

OIC-MW: OpenID Connect

Middleware

BT-MW: Bearer Token Middleware

Browser

WS-Federation SAML 2.0

OpenID Connect

OIC-MW

ADAL

Web application

Native app ADAL

Server app ADAL

JavaScript ADAL.JS

BT-MW Web API

BT-MW ADAL

Calling Web API’s – Web API

Web API

Calling Web API’s – Web API

Acquire a token based on the current authorization token

• Save sign-in token in the bootstrap context

• Acquire token based on user assertion

var context = new AuthenticationContext(authority, userTokenCache); var credential = new ClientCredential(clientId, clientSecret); var userIdentity = (ClaimsIdentity)ClaimsPrincipal.Current.Identity; var bootstrapContext = (BootstrapContext)userIdentity.BootstrapContext; var userAssertion = new UserAssertion(bootstrapContext.Token); var result = await authContext.AcquireTokenAsync( resourceId, credential, userAssertion);

OAuth 2.0 On-Behalf-Of Flow (user identity)

Configuring Tokens

Update the Azure AD Application Manifest

• Update “groupMembershipClaims” to emit group claims

• Add “appRoles” to declare application-specific roles

"groupMembershipClaims": "SecurityGroup"

"appRoles": [ { "allowedMemberTypes": [ "User" ], "description": "Administrators can manage the application", "displayName": "Administrator", "id": "6f7a2ff9-5741-41f6-9476-39286dfbcf8d", "isEnabled": true, "value": "administrator" }, ... ]

Adding groups and roles to claims

Declaring Permissions

Update the Azure AD Application Manifest

• Add permission to “oauth2Permissions”

• Make sure to generate a new GUID for the id

{ "adminConsentDescription": "Allow the application to create todo's on behalf of the signed-in user.", "adminConsentDisplayName": "Create todo's", "id": "5f54c597-8838-4eaf-853c-91cf5b487d1e", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to create todo's on your behalf.", "userConsentDisplayName": "Create todo's", "value": "todo_write" }

Allowing clients to request access to only subsets (scopes) of functionality

Requesting Permissions

Update the Azure AD Application Manifest (or use the portal)

• Find the target application id (“resourceAppId”)

• Add the permission id to “requiredResourceAccess”

• The “scope” claim will now contain the permission’s defined “value”

"requiredResourceAccess": [ { "resourceAppId": "93fc871a-3e18-4f2c-b7a5-dcc65efd6384", "resourceAccess": [ { "id": "5f54c597-8838-4eaf-853c-91cf5b487d1d", "type": "Scope" } ] } ]

Getting access to scoped resources

Azure AD Graph API

Use REST API directly or use a client library

• “Microsoft.Azure.ActiveDirectory.GraphClient” NuGet Package

• Optionally use ADAL to get an access token

var client = new ActiveDirectoryClient( new Uri("https://graph.windows.net/contoso.com"), async () => { var context = new AuthenticationContext( ... ); var result = await context.AcquireTokenAsync( ... ); return result.AccessToken; } ); var groups = await client.Groups.Where( ... ).ExecuteAsync();

Interacting with Azure Active Directory

Wrapping Up...

Summary

Develop for a modern cloud-scale identity service

• Serves millions of users/organizations

• Supports most common identity features and protocols

• Security hardened out of the box

• Social and “application local” identities coming in B2C

Develop using open source libraries for all scenarios

• OAuth 2.0 for authorization

• OpenID Connect for authentication

Developing for Azure Active Directory

Resources

Documentation & News

• http://aka.ms/aaddev

• http://aka.ms/aadauthprotocols

• http://blogs.technet.com/b/ad/

Open Source Tools & Samples

• https://github.com/azuread

• https://github.com/azureadsamples

• https://github.com/jelledruyts/identitysamples

What’s next?

Your feedback is important!

Scan the QR Code and let us know via the TechDays App.

Laat ons weten wat u van de sessie vindt via de TechDays App!

Scan de QR Code.

Bent u al lid van de Microsot Virtual Academy?! Op MVA kunt u altijd iets nieuws leren over de laatste technologie van Microsoft. Meld u vandaag aan op de MVA Stand. MVA biedt 7/24 gratis online training on-demand voor IT-Professionals en Ontwikkelaars.

Recommended