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.

image

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
{
[OperationContract]
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: ,,

2 comments:

Jose Luis Serrano Fernandez 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

Thanks

Claus Konrad said...

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