Thursday, August 27, 2009

How to get the current user from a Silverlight application

First, when I say current user, I am assuming that you are using NTLM / Windows Authentication / Active Directory. In a ASP.NET website, you would use something like User.Identity.Name. However, in Silverlight there is no such thing. So, the short answer appears to be that you can’t. At least not directly from Silverlight.

The trick is in what other tools do we have that we can use. One option ASP.NET and Javascript combination to get the value from ASP.NET, pass it to the Silverlight control as an initparam, and use it in the Silverlight app. This is is a HUGE security hole. I can’t believe people actual accept this as an option. All someone would have to do is create a .html page that has the Silverlight application object on it, and set the username to some admin user, and there is full access, no password needed. For the code, click here.

Needless to say, I don’t think the above technique is an option. The best option by far is to create a web service and get the value from it. While it is still possible to fake the response from the web server, would be a bit more difficult and would require faking a network route or something similar.

The best option if you can help it is to never need it from Silverlight. Always use this value from the web service that your Silverlight app uses already. That way there is nothing to fake, etc. It is all server-side then. If you have to have the username in the actual Silverlight application, then I recommend don’t use it for security purposes without doing server-side validation also. Think of Silverlight as a first line of defense, and the server-side (web service) being made more robust.

In case, you don’t know what the web service method would look like, below is an example.

public string GetCurrentUsername()
{
return User.Identity.Name;
}

2 comments:

Anonymous said...

Hi , I have encountered the same issue , have you fixed it.

Brent V said...

Anonymous,

Sorry, I don't understand your question. The best option I know of is to call the web service since it knows the credentials.

I hope that helps.

Brent