28 April, 2010

ASP.NET/Silverlight: How to pass credentials to Silverlight control

I have an embedded Silverlight application (SL) in my website. This SL calls some backend WCF services; services which require authentication (usr/pwd) to be used.

I was kind of thinking; that the SL application embedded in my aspx-page did not have a clue that it was running in the context of an aspx-page. That way – I needed to provide some means of “shared token” to be passed from the hosting aspx-page into the SL application upon initialization, to make the SL control call the WCF-services in an authenticated way.


Well – well, it turns out that “someone” has been thinking about this problem beforehand. Here goes:

First of all – my SL application resides on an aspx page that is secured by the <location> tag in the ASP.NET application hosting the SL application. That way – to access the SL application in the first place; you need to login to the ASP.NET application via conventional FORMS login. Now – the really clever thing here is, that every call that goes from the SL application is fed through the network stack of the hosting browser. In this way every call from the SL application is attributed by the browser before it leaves the Clients PC. And this also applies to session tokens.

So the session token obtained when logging into the hosting ASP.NET application, is applied to the SL calls going back to the WCF-service on the backend automatically! Pretty darn clever.

To use this on the server side (WCF-service), you do need to set the AspNetCompatibilityRequirements attribute to gain acccess to the HttpContext in the WCF-service. Otherwise it will not work.

[ServiceContract(Namespace = "something here")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloService
public string SayHello()
string usr = HttpContext.Current.User.Identity.Name;
return string.Format("Hello, {0}", usr);

Notes to consider:
1) You need to have the AspNetCompatibilityRequirements attribute applied to the service
2) The WCF service must reside within the hosting ASP.NET application to use the same session token.

Technorati Tags: ,,


Unknown said...

Please could you help me how to pass the auth token from a html5 mvc4 app in one domain to a Silverlight application in anither


Claus Konrad said...

Well - these credentials you are providing where are they authenticated? And in what form to they arrive (Kerberos, U/P, OpenID...=

MyMindSpeaks said...

It is truly a great and helpful piece of info,Excellent blog,Thanks for sharing. TsoHost Coupons

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...