Deep Dive on Azure 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 Today’s Applications

Browser Web Web API JavaScript application

Native app

Web API Web API

Server app

Clients using wide variety of applications using wide devices/languages/platforms variety of platforms/languages Authentication Protocols

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser Web Web API JavaScript application

OAuth 2.0

Native app

OAuth 2.0

OAuth 2.0 Web API Web API

Server app

OAuth 2.0

Standard-based, HTTP-based protocols for maximum platform reach What Is Azure Active Directory? Azure Active Directory for Developers

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 Tokens in Azure AD OAuth 2.0 Access and Refresh Tokens

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

JSON Web Token (JWT) Base64 URL encoded JSON with optional signature eyJ0eXAiOiJKV1QiLCJhbGciO.eyJpc3MiOiJodHRwOi8vc3RzbnRc28uY29tI.ZT8zzX6vg9I5HvTm4f8f

Header Claims Signature

{ { "typ": "JWT", "iss": "http://sts.contoso.com/", "alg": "RS256" "aud": "http://api.contoso.com/", "x5t": "7dD-gec…" "client": "http://www.contoso.com/", } "iat": "1432235632", "exp": "1432239532", "name": "John Doe" "scope": ["read", "write"] } Token Signing Key Ensuring the tokens really come from Azure Active Directory

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 Registering Applications Azure AD must know about your app before it will issue tokens

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, … Application Configuration What Azure AD needs to know about your app

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 Permissions To Other Applications Declaring access to other applications

Application Permissions • Access another application as the calling application

Delegated Permissions • Access another application on behalf of the user Consent Granting permissions to an application

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 Multi-Tenant Applications Targeting other organizations

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/

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/ • User prompted to consent based on permissions required by application • Consent registers application in user’s tenant Groups & Roles Authorization features for applications

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 Developing for Azure Active Directory Developing For Azure AD And mostly equivalent when using Windows Server 2016 on-premise

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 Microsoft Security Libraries

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Active Directory Authentication Library Acquiring, refreshing & caching tokens

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 Adding Sign-In To ASP.NET

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Adding Sign-In To ASP.NET OpenID Connect

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 { ... } Protecting Web API’s

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Protecting Web API’s OAuth 2.0 Bearer Token Authorization

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 { ... } Calling Web API’s General pattern

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); Calling Web API’s – Web App

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Calling Web API’s – Web App OpenID Connect (user identity)

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 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 OAuth 2.0 Client Credentials Grant (client identity)

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”) var context = new AuthenticationContext(aadAuthority); var credential = new ClientCredential(clientId, clientSecret); var authenticationResult = await context.AcquireTokenAsync(resourceId, credential); Calling Web API’s – Native Client

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Calling Web API’s – Native Client OAuth 2.0 Authorization Code Grant, Public 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 Calling Web API’s – Daemon

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Calling Web API’s – Daemon OAuth 2.0 Client Credentials Grant

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 # 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 Calling Web API’s – SPA

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Calling Web API’s – SPA OAuth 2.0 Implicit Flow

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 }); Calling Web API’s – Web API

WS-Federation SAML 2.0 OpenID Connect OAuth 2.0 Browser OIC-MW: OIC-MW Web BT-MW ADAL Web API OpenID Connect JavaScript application Middleware ADAL.JS OAuth 2.0 BT-MW: Native app ADAL ADAL Bearer Token Middleware OAuth 2.0

OAuth 2.0 BT-MW BT-MW ADAL: Web API ADAL Web API Active Directory Authentication Server app ADAL Library

OAuth 2.0 Calling Web API’s – Web API OAuth 2.0 On-Behalf-Of Flow (user identity)

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); Configuring Tokens Adding groups and roles to claims

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" }, ... ] Declaring Permissions Allowing clients to request access to only subsets (scopes) of functionality

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" } Requesting Permissions Getting access to scoped resources

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" } ] } ] Azure AD Graph API Interacting with Azure Active Directory

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(); Wrapping Up... Summary Developing for Azure Active Directory

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 Resources What’s next?

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 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.