Monday 9 May 2011

How to get the Windows user identity name in Silverlight.


Silverlight Windows User Identity Name

Introduction

This article explains how to get the Window User Identity Name in Silverlight without using WCF.

Background

I was looking for Windows Authentication for Silverlight on the web. After Binging and Googling for a while, I found most of them use a WCF service to do the Windows authentication, where the primary objective is to just get the current user name. I thought using WCF for just getting the Windows user is kind of overkill, and moreover, you have to configure your basicHttpBinding to incorporate Windows authentication with WCF, which is kind of trivial, but can turn painful if not configured properly.

Below are three quick and easy steps to achieve the objective:

  1. Open the ASPX page that carries the Silverlight XAP file inside the Object tag and add a new param (let's call it Initparams):

<param name="Initparams"
  value="UserAccount=<%=HttpContext.Current.User.Identity.Name%>" />

  1. Open the App.xaml.cs file and declare a global variable:

public static string UserID = string.Empty;

To the application_startup method in App.xaml.cs, assign the param value to the global variable (this should be before the RootVisual statement):

UserID = e.InitParams["UserAccount"];

  1. Declare a variable in your Mainpage.xaml or the navigation page, and assign the global variable value to the local variable, and you have the current logged on Windows user name.

string UserAccount = App.UserID;