NHibernate TimeoutException with Azure SQL

Recently, I spent nearly three full working days debugging the damndest thing: a simple NHibernate Linq query in an Azure test environment was timing out. Together with the SqlAzure client driver that does transient fault handling by retrying queries this resulted in a situation, where a specific page would never load, causing instead a huge spike in the database resource usage.

Of course, as it tends to be with these things, the same query against a local SQL Server database worked just fine.

Possibly the strangest part was that after obtaining the query through NHProf, I tried running the same query via SQL Server Management studio, and the mean execution time of the query was between 100ms and 200ms. Accordingly, I had a hell of a time believing that the issue was an inefficient query as such.

I even tried creating a raw ADO.NET query that had the same command text and parameter specifications… and it executed in under 200ms.

I was about to give up when I had the idea of running both the slow and the fast query against a local database with the SQL Profiler enabled, because while there was no discernible difference in execution time against the local database, perhaps I’d be able to make out some difference in the way the queries were executed.

At first, it looked like the queries were identical from the server’s perspective, too.

But then, I noticed the difference.

The slow query declared that the single parameter’s size was 4000 whereas the fast version said it was 1.

Realization began to dawn, and I re-ran my raw ADO.NET query against the Azure database, but with the parameter size set to 4000 — and wouldn’t you know it, the timeout manifested itself immediately.

My current hypothesis is that what’s going on underneath it all is that the database is waiting for a value for the parameter and it never shows up, which is what causes the timeout. Another strange factor is that the issue doesn’t reproduce with all Azure SQL servers.

All this is triggered by a change to NHibernate Core where the SqlClientDriver skips setting the parameter size to a meaningful value, and instead sets it to a default of 4000.

Fortunately, the workaround is simple: I extended the client driver code with a very specific special-case workaround that sets the parameter size:

It may eventually turn out that I’ll need to handle more than just the one-character parameter size, but for now, this seems to fix the issue.

Media Services at Global Azure BootCamp Finland

I was at the Global Windows Azure BootCamp in Espoo today, rambling about the coolness of the Microsoft media platform in general and Windows Azure Media Services in particular. The event was hosted at the awesome co-workspaces of AppCampus by Teemu Tapanila and Karl Ots — hats off for organizing the event, it was great fun!

I’m not sure if anyone actually tried them, but I put up some lab exercises on GitHub for playing around with Azure Media Services. If you’re looking for a starting point for working with Azure Media Services, go ahead and take a look. :)

The Anatomy of a Cloud Video Service — My TechDays 2013 talk

So, a few weeks back I was on stage at TechDays 2013 Finland. My topic for the day, titled “The Anatomy of a Cloud Video Service”, was about the Futudent “camera + software + cloud service” solution that I’ve been involved with for quite a while now. I intend to cover the associated technologies in more depth in blog form later, but for now, here’s the video of my presentation.

I spent my hour talking about what the client application does, how we handle video transcoding, what it was like to build the associated video sharing service and all the challenges associated with the entire story.

The talk is in Finnish, so obviously it’s only for a limited audience. Also note that for whatever reason, the video is set to forcibly start at 3:22 and you have to specifically click on “watch the entire video” at the timeline marker in order to get to the first few minutes.

Upcoming breaking changes in Windows Azure Active Directory preview

A moment ago Vittorio Bertocci wrote a post on some upcoming changes to the Developer Preview of WAAD. The changes are of the breaking sort, so if you’re actively using WAAD, this is something you’ll want to react to.

The WAAD MSDN forums have a more detailed announcement about the changes, but at a glance, here are the two key things I picked up on.

The service endpoint names are changing

Your (most likely automatically generated) Web.config settings say something like this now:

      <wsFederation passiveRedirectEnabled="true" 
					issuer="https://accounts.accesscontrol.windows.net/tenant-id/v2/wsfederation" 
					....
					requireHttps="false" />

After the change, that will have to change to:

      <wsFederation passiveRedirectEnabled="true" 
					issuer="https://login.windows.net/tenant-id/wsfed" 
					....
					requireHttps="false" />

The metadata and JWT endpoints are changing too, which may or may not affect you — but if you’re using any of them, you’ll probably know what to do anyway. :-) 

The User Principal Name claim will no longer be included

A while back, the claim that actually names the user principal was changed from EmailAddress to UPN. Now things are changing again, and in the future, the naming claim type will be … name! Which means your web.config settings need to change from

<nameClaimType value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" />

to

<nameClaimType value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" />

That’s pretty much it. And of course, if you can’t get the settings right editing them by hand, you can always run the Visual Studio Wizard again

Hope this helps someone. :-)

Blog move

Just a quick note: I’ve grown tired of Blogger regularly doing a hatchet job with my post markup and the limited options they give me for customizing the look and feel of the site, so I’ve moved to a new host.

I tried my best to not mess with the existing post URLs, but I’m afraid that at least the RSS feed urls will have changed.

Windows Azure Active Directory: Using the Graph API with an Office 365 Tenant

In a previous post I wrote about querying the Graph API for the group memberships of a WAAD user. In yet another post, I detailed setting up a WAAD tenant, but I also noted that you don’t have to do that if you’ve already got an Office 365 subscription, and would prefer to use that instead.

While that statement is technically true, the story is far from complete. As commenter Nick Locke points out, my instructions for using the Graph API don’t work for Office 365 tenants: the code throws an exception while trying to get the authorization token for the request.

After a bit of trial and error, I managed to figure out a fix.

Once again, open up the Microsoft Online Services Module for Windows PowerShell. Run Import-Module MSOnlineExtended -Force to load the module, use Connect-MsolService with admin credentials to establish the connection, and type in:

$adPrincipal = Get-MsolServicePrincipal -AppPrincipalId 00000002-0000-0000-c000-000000000000
$adPrincipal.ServicePrincipalNames

If your Office 365 setup is like ours, the result will look a lot like this:

00000002-0000-0000-c000-000000000000
AzureActiveDirectory/graph.windows.net
AzureActiveDirectory/directory_s5.windows.net
AzureActiveDirectory/directory_s4.windows.net
AzureActiveDirectory/directory_s3.windows.net
AzureActiveDirectory/directory_s2.windows.net
AzureActiveDirectory/directory_s1.windows.net
AzureActiveDirectory/directory.windows.net
AzureActiveDirectory/Directoryapi.microsoftonline.com

Looking at this list, it occurred to me that the problem might be related to the fact that we construct Realm Names for our application using the GUID 00000002-0000-0000-c000-000000000000 and the domain name graph.windows.net — the result looking like: 00000002-0000-0000-c000-000000000000/graph.windows.net@your-app-principal-id. So I figured I’d change my app to use the string AzureActiveDirectory instead of the GUID, and wouldn’t you know it, I got past the authorization token error. Only now I ended up with another error: validating the token didn’t work.

After a bit of head-scratching and web-searching, I thought I had it backwards: it wasn’t my app that was misconfigured, it was the Office 365 tenant. Suppose that the Graph API service actually identifies itself as 00000002-0000-0000-c000-000000000000/graph.windows.net and not AzureActiveDirectory/graph.windows.net, and that’s why things are failing.

I repeated the commands above in a MSOL PowerShell session that was connected to the WAAD domain I created before, and noted that indeed, the Service Principal Names for Microsoft.Azure.ActiveDirectory were otherwise identical, but AzureActiveDirectory was replaced by 00000002-0000-0000-c000-000000000000. So I cooked up this PowerShell bit:

I then ran it against the Office 365 MSOL PowerShell session and tried again. And wouldn’t you know, it worked!

Apparently, we’re not the only ones with this problem, so let’s hope this helps save someone else the trouble!

Windows Azure Active Directory: Using Group Memberships for Authorization

This is the fifth installation in my series on WAAD. So far, we’ve managed to create a WAAD tenant domain, set up an application to use WAAD for Single-Sign On authentication and read the current user’s group memberships using the Active Directory Graph API. Oh, and let’s not forget fixing a problem where the current user’s name is null. Now that we’re here, let’s complete the picture by converting our group memberships to roles and using those roles for authorization.

Staking a claim

One of the interesting changes in .NET 4.5 that hasn’t received much attention is the fact that under the covers, all authentication providers are now claims-based. Of course, Windows Identity Foundation has been claims-based from the start – the real change is that all the common infrastructure supports claims as well. For ASP.NET MVC development, this means that all we need to do to support roles using the [Authorize(Roles = "RoleName")] attribute syntax is get role claims from somewhere. The bad news is that WAAD authentication only gives us an identity claim. The good news is we can make up our own role claims pretty easily. Our enabler is a class called System.Security.Claims.ClaimsAuthenticationManager:

Defines the base implementation for a claims authentication manager. The claims authentication manager provides a place in the claims processing pipeline for applying processing logic (filtering, validation, extension) to the claims collection in the incoming principal before execution reaches your application code.

Let’s put that to use. Create a new class and call it GroupToRoleClaimAuthenticationManager. Paste in this code:


Then configure the application to use the manager by adding this under system.identityModel/identityConfiguration in Web.config:

<claimsAuthenticationManager type="WAADDemo.GroupToRoleClaimAuthenticationManager, WAADDemo" />

Create groups

Log in to the WAAD administration portal, open up “users & groups” and switch to the “security groups” view:

waad-groups

Create a group called “Administrators” and add your WAAD administrator user to that group. Then, create a new user:

waad-create-user-1

You don’t have to specify any additional details if you don’t want to. Click on “next” and you’ll get a page asking about user roles. Notably, you most likely don’t want to specify any roles here, as the roles are fixed and specific to WAAD:

waad-create-user-2

The next page in the wizard will ask about assigning licenses. This is a feature that is specific to Office 365, so you can skip it and click “next”. Finally, the wizard will ask whether you want the generated password for your new user to be sent to someone via email. Whether you do that or not, the password will be displayed to you on the next page, so note the password down somewhere and complete the wizard.

Restricting access

Now we’ve got groups and our groups have members in them. We also have a bunch of code in our application that converts those memberships into role claims. The last thing we need to do is use that to restrict access within our application. Add a new controller action – for example, in the HomeController of the Internet Application app template:

[Authorize(Roles = "Administrators")]
public ActionResult AdminOnly() {
 return View();
}

Create a matching view, and run the application. When the application asks for you to log in, do that with the credentials of the user you just created. Since this is the first time you are logging in, instead of immediately directing you back to the application, WAAD will ask you to change the user’s password:

waad-password-change

Change the password and log in again with the new password. Navigate to https://localhost:44302/Home/AdminOnly (substituting the port and protocol you’re actually using) and you should be greeted with a 401:

iis-express-unauthorized

To verify that administrators can see the admin features, log out of your session by closing the browser session, re-launch the browser and log in again – this time, using your admin credentials – and the application will let you through:

waad-app-with-admin-user

You’ll probably also want to hide links to administrative features from users that don’t have the required privileges – that’s easily done with IPrincipal.IsInRole().

Phew! We’ve covered a lot of ground and come pretty far. I hope you found all this useful. As usual, questions and comments are welcome!

Windows Azure Active Directory Authentication: User Principal Name is Suddenly Null

Last week, after I had already written my guide on setting up your ASP.NET MVC web application to use WAAD authentication, Microsoft changed the configuration of WAAD in a way that broke my demo application: logging in worked, but the user principal had “null” for its name.

After looking into the problem for a moment, I realized that the application was configured to expect an email address claim from the identity provider. The configuration is in web.config:

<add type="System.IdentityModel.Tokens.Saml2SecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
	<samlSecurityTokenRequirement>
		<nameClaimType value="http://schemas.xmlsoap.org/claims/EmailAddress" />
	</samlSecurityTokenRequirement>
</add>

This configuration says that the thing that names our user principal is the email address claim. After the update, we no longer get that claim, so the configuration needs to change to this:

<add type="System.IdentityModel.Tokens.Saml2SecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
	<samlSecurityTokenRequirement>
		<nameClaimType value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" />
	</samlSecurityTokenRequirement>
</add>

This does make more sense: the new claim is a “upn” or “user principal name”, which makes sense because, well… it’s the name of our user principal.

After this change, you’ll also want to add this line somewhere, most likely your Application_Start event handler:

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Upn;

This ensures that your anti-forgery tokens keep functioning.

What sucks about this is that I didn’t receive any kind of notification about the change. I hope this helps someone avoid the headache of debugging through the issue. Smile

Windows Azure Active Directory: Querying the Graph API for group memberships

This is the third part in my series of posts on Windows Azure AD. In this post I go through the steps required to get your application talking to the AD Graph API, and the things that stumped me along the way. The reason we’re interested in the Graph API to begin with is that WAAD Authentication provides us with the user’s identity, but doesn’t tell us anything else about them. If we want more details, such as group memberships, we need to do some extra work.

Dependencies

We begin this part by adding a new Service Reference to the project. For the address of the service, type http://graph.windows.net/offbeatdemo.onmicrosoft.com (replacing offbeatdemo.onmicrosoft.com with your own tenant domain name) and click “Go”. After a moment of waiting, Visual Studio should generate the necessary metadata files. Here you can give your service a namespace – remember, it’s relative to your project’s default namespace, so let’s call it “ActiveDirectoryGraph”.

vs-graph-reference

Once you hit OK, the service reference is generated as per usual. This is where the fun begins. Go to the References node in your project, right-click and select “Manage NuGet Packages…”. Select “Online” from the left, click on the search box and type in “Microsoft.WindowsAzure.ActiveDirectory.Authentication” and you should see a single matching package.

vs-nuget-aal

Click on “Install” to have NuGet fetch the library for you. The library in question is the Windows Azure Authentication Library, or AAL for short. It has all kinds of features, but the reason we need it is to authenticate our application so it can make Graph API requests. Somewhat counterintuitively, AAL depends on System.Windows.Forms of all things, so before your code will compile, you will need to add that as a reference to your project.

Using the API

Create a new class in your project – you can call it what you like, but I’m calling mine “GraphClient”. Paste in the following code – you may have to change some namespaces, but if you’ve added the service reference and the AAL package correctly, it should compile as is:


I’m not going to go through the implementation details of the class now – if you’ve got questions or feedback, leave a comment here or in the gist at GitHub. In order to use this class, what you need to do is find out some details about your tenant domain and Service Principal. It’s not entirely obvious why, but the only place where I’ve found the tenant id so far is the FederationMetadata.xml file (as documented in the article Integrating Multi-Tenant Cloud Applications with Windows Azure Active Directory) – note that the file I linked to is the federation metadata for my demo tenant domain, so you need to change the URL to get your own metadata. Locate the entityId attribute on the EntityDescriptor tag.

federation-metadata-tenantid

The entityId attribute looks like this: spn:00000001-0000-0000-c000-000000000000@a071bf68-ee1d-46aa-ac6d-cfddf3826050 – the emphasized part after the @ sign is the tenant id. Yours will be different from mine of course – copy the id somewhere handy, because you will need it soon. You’re also going to need the app principal id of the service principal you created in the previous installment. Finally, you’ll need to grant your application the right to read the directory, and create a symmetric key known to both WAAD and your application – it’s a key you will use to sign your requests, so WAAD will know it’s you making them. Here’s how you do all that: open the MSOL module for PowerShell and use Connect-MsolService to connect to your WAAD tenant. Run Import-Module MSOnlineExtended –Force to make all the commandlets available, and then run Get-MsolServicePrincipal | select DisplayName,AppPrincipalId to list your service principals.

PS C:\Windows\system32> Get-MsolServicePrincipal | select DisplayName,AppPrincipalId

DisplayName                             AppPrincipalId
-----------                             --------------
Microsoft.Azure.ActiveDirectory         00000002-0000-0000-c000-000000000000
Microsoft.Azure.ActiveDirectoryUX       0000000c-0000-0000-c000-000000000000
WAADDemo App                            e8a3050f-0c61-46bd-9808-ff7dd5dcdb4b

The resulting list will show you the app principal id (in this case, e8a3050f-0c61-46bd-9808-ff7dd5dcdb4b) – copy it somewhere handy. Next, we use that to create a new symmetric key with New-MsolServicePrincipalCredential:

PS C:\Windows\system32> New-MsolServicePrincipalCredential -AppPrincipalId e8a3050f-0c61-46bd-9808-ff7dd5dcdb4b
The following symmetric key was created as one was not supplied JH0QbohY5/+IW25zzukjuwPjr6mpnMhgicgVA4SfF9A=

Save the symmetric key somewhere too. As far as I know, there is no way to restore the value if you lose it – you’ll have to create a new key instead. You’ve got everything your application needs, but there’s still one more thing left to do: granting privileges.

PS C:\Windows\system32> Add-MsolRoleMember -RoleName "Service Support Administrator" `
 -RoleMemberType ServicePrincipal -RoleMemberObjectId 3dc125e6-d518-40d2-9392-87a03dac8f68

The “Service Support Administrator” role grants read-only access to the directory. The RoleMemberType switch is needed to inform WAAD that we’re granting the privilege to an application instead of a user or a group, and the RoleMemberObjectId switch identifies the Service Principal. Note that the Object Id is different from the AppPrincipalId we used earlier – if you don’t have the Object Id written down anywhere, you can use Get-MsolServicePrincipal | select DisplayName,ObjectId to get it. Now, you can use the collected values to create an instance of GraphClient and use it. Add this to a controller action:

var client = new GraphClient("offbeatdemo.onmicrosoft.com""a071bf68-ee1d-46aa-ac6d-cfddf3826050",
 "e8a3050f-0c61-46bd-9808-ff7dd5dcdb4b""JH0QbohY5/+IW25zzukjuwPjr6mpnMhgicgVA4SfF9A=");
 
var groups = client.GetUserGroups(User.Identity.Name);

return View(groups);

Now you should be able to display your user’s group memberships in the view:

waad-app-with-groups

Wrapping up

None of this was particularly difficult to do from a programming perspective – the trick is finding all the information you need! It doesn’t much help that most of the examples out there deal with either SaaS applications that are registered in the Seller Dashboard or applications that use ACS instead of WAAD. The steps are largely the same, but the places where you look for IDs and keys are wildly different. Merely listing the user’s group memberships isn’t very interesting. Now that we’ve got them, we could use them for authorization within the application – which is what we’re doing in the next part of this series.

Windows Azure Active Directory Authentication: Setting up the application

Continuing where we left off in the previous post, we’ve got all the tools, so the next step is setting up the authentication itself. You probably don’t want to make a mess of the working state of your actual application. Or perhaps you don’t yet have an application to test with. For this walkthrough, you can start with a new ASP.NET MVC 4 project from Visual Studio and select Internet Application as the template. The template contains a layout that displays the current logged-in user, which demonstrates that the authentication mechanism integrates nicely with the rest of ASP.NET. After you’ve got your application open in Visual Studio, right-click on the project in Solution Explorer and select Enable Windows Azure Authentication.

vs-enable-waad-auth

Clicking on the menu item opens up a dialog that asks for your tenant domain name.

vs-enable-waad-auth-2

That is, unless it throws you a COMException instead. If that happens, ensure that you’ve got an IIS or IIS Express virtual directory set up for your web application. Visual Studio doesn’t let you misconfigure the virtual directory settings like this, but it might still happen if you’re running your web app as an Azure Web Role in the Compute Emulator.

Once you type in your tenant domain name, you’ll be prompted to log in. Log in with an account that has administrative access (for example, the account you created during the tenant setup process).

vs-enable-waad-auth-3

The prompt uses IE, so if you happen to be logged in an IE session with a Microsoft Online account that doesn’t exist in the tenant domain, you might end up with an error instead. This happens to me quite often, because I use our Office 365 apps with IE.

vs-enable-waad-auth-error

The easiest way to get rid of this error is to cancel the WAAD authentication setup, open up the Visual Studio web browser (View –> Other Windows –> Web Browser) and use it to navigate to the Microsoft Online logout page. Once the logout process is complete, close the Visual Studio web browser and try the WAAD authentication setup again. At this point, if everything went well, you’ll be presented with a happy green check mark.

vs-enable-waad-auth-4

You’ll have a number of changes in your Web.config, mostly under system.identitymodel:

vs-enable-waad-auth-result

The default authentication module for ASP.NET applications is the Forms Authentication module. You can only use a single authentication module for your application, and since the Forms Authentication module is configured at the web server level, it takes precedence. So make sure that your application doesn’t use the Forms Authentication module by adding this under system.webServer/modules:

<remove name="FormsAuthentication" />

A brief interlude on WAAD Single Sign-On

Before we go further, a few words on how SSO actually works. When a request comes in to your web application, the authentication module checks to see if the user is authenticated or not. This is typically done by looking at a cookie that holds some sort of authentication ticket. If the user is authenticated, then it’s all good. However, if the user is not authenticated, a bunch of things have to happen. First, the authentication module redirects the user’s browser to the identity provider. Among the information it passes on is a return address. Since the login process happens in the user’s browser, we can’t really control it. In order for things to work smoothly, we need to tell the identity provider what to do after the user has logged in. A return address tells the provider where the user should be redirected once authentication is completed. After the user logs in, the identity provider uses the return address combined with a login token to redirect back to our application. Our application invokes the authentication module, which takes the login token, verifies its validity and extracts the user’s identity. This is the point where the user is finally authenticated with our application.

browser-app-waad-interaction

I won’t pretend I understand all or even most of the security implications here, but one consideration is definitely this: you can’t let just anyone authenticate users against your directory, even if the only data you’d pass on to them would be the user name. Imagine a rogue third party that created an app that had your company’s branding and used your company’s official authentication mechanism – and then tricked your users into giving them confidential data. That’s no good, so we need to control who we give the login token out to. Which is what we’ll do next.

Configuring the Service Principal

Before your application can use WAAD authentication, it must be registered in WAAD. This registration is called a Service Principal, and a big part of what the Visual Studio wizard did for you involved creating the Service Principal. One of the things configured in the Service Principal settings is the list of accepted after-login return addresses. The wizard creates a Service Principal with a single return address: https://localhost:44302 — the port number is arbitrarily assigned, so yours might not be exactly the same. It also enables SSL for your app, so the return address will work. This is all well and good, unless your web application can’t run in that particular port – such as with Azure Web Roles in the Compute Emulator. That means you won’t get the login token from WAAD unless we add a new return address. Fire up Microsoft Online Services Module for PowerShell again. Call Connect-MsolService to authenticate, type Get-MsolService and hit tab. PowerShell will expand this to Get-MsolServicePrincipal. Hit enter… and boom! “Get-MsolServicePrincipal : The term ‘Get-MsolServicePrincipal’ is not recognized as the name of a cmdlet, function, script file, or operable program.”

msol-powershell-before-import

Wait… what? Yeah. So PowerShell’s autocomplete suggests that there is a commandlet with this name, but then it’s not there when you try to use it. This is a weird artifact of the way the commandlets are packaged. What you now want to do is run Import-Module MSOnlineExtended –Force, and then the command will work. The –Force flag is necessary, because the extended module lives in the same binary file as the regular one, and without it, PowerShell will think it’s already well and properly loaded. In order to configure the return addresses, we need a handle on the service principal created by the Visual Studio Wizard. In the MSOL PowerShell window, type Get-MsolServicePrincipal | select AppPrincipalId,DisplayName

PS C:\Windows\system32> Get-MsolServicePrincipal | select DisplayName,ObjectId

DisplayName                             ObjectId
-----------                             --------
Microsoft.Azure.ActiveDirectory         25294a23-e33f-4b06-9bd4-c0a04f4cc155
Microsoft.Azure.ActiveDirectoryUX       081e23f3-5c2b-44b5-89e7-23cbbe7a13dc
My test app                             3dc125e6-d518-40d2-9392-87a03dac8f68

The last principal in the list is the one the wizard generated for you. Visual Studio always registers your application as “My test app”, regardless of what your app is actually called – for instance, the name of my application is the far more sensible “WAADDemo”. Winking smile In my example, the generated principal’s object id is 3dc125e6-d518-40d2-9392-87a03dac8f68. In order to get a handle on that particular principal, we can run

$principal = Get-MsolServicePrincipal -ObjectId 3dc125e6-d518-40d2-9392-87a03dac8f68

To list the configured reply addresses, we type:

$principal.Addresses | select Address,AddressType

and get a return address listing

PS C:\Windows\system32> $principal.Addresses | select Address,AddressType

Address                                                             AddressType
-------                                                             -----------
https://localhost:44302/                                                  Reply

To add the final deployment and Compute Emulator reply addresses, we modify the address list we just got, then set it back to the principal:

$addresses = $principal.Addresses
$addresses.Add((New-MsolServicePrincipalAddresses -Address http://localhost:81))
$addresses.Add((New-MsolServicePrincipalAddresses -Address http://my-app.example.com))
Set-MsolServicePrincipal –ObjectId 3dc125e6-d518-40d2-9392-87a03dac8f68 -Addresses $addresses `
 -DisplayName "WAADDemo App"

The first line gets the current address list to a new variable. The next two lines create the address objects and add them to the list. The final command associates the updated address list with the principal and changes its name to “WAADDemo App” for good measure.

Finishing up

The last thing you need to do is ensure that you’re sending the correct reply address to WAAD. Edit web.config at system.identityModel.services/federationConfiguration/wsFederation and replace the value of the reply attribute with one of the reply addresses you configured in the previous step:

<wsFederation passiveRedirectEnabled="true" issuer="https://accounts.accesscontrol.windows.net/a071bf68-ee1d-46aa-ac6d-cfddf3826050/v2/wsfederation" realm="spn:e8a3050f-0c61-46bd-9808-ff7dd5dcdb4b@a071bf68-ee1d-46aa-ac6d-cfddf3826050" reply="http://localhost:81/" requireHttps="false" />

By now, when you run the application, you should be automatically redirected to the Windows Azure Authentication portal:

waad-federated-login

When you log in, you’ll be redirected back to your app as an authenticated user:

waad-app-after-login

If you play with the app a bit, you’ll notice that logging out doesn’t actually work. That’s a quirk of Azure federated login – you can visit the logout URL if you like, but it won’t really take effect unless you close the browser session. Phew, that was a lot of stuff to go through! What’s interesting here is that you didn’t have to write a single line of C# code. Now, that in itself is not really a goal worth pursuing, particularly if it results in an ungodly mess of XML configuration. However, what is remarkable and desirable is that once you understand all this, setting up new applications that share the same credentials is actually a breeze. So there is a point to all this, believe it or not. Smile Next up: User details! We’ll be reading group memberships using the Graph API.

1 2 3 14