Securing Silverlight Application and WCF Service using ASP.NET Authentication Techniques

Security is an issue that experts are discussing since the birth of Silverlight. A typical enterprise Silverlight application will consist of one or more Silverlight pages communicating with one or more WCF services. There are three major security concerns here:

  1. Silverlight 2 supports communication with a WCF service in simple text (the basicHttpBinding), so anyone can use a packet sniffer (e.g. Fiddler) to read our data.
  2. Anyone can access our WCF service, call its methods and get our data.
  3. Anyone can download our Silverlight application (the .xap file), open it (since it is simple a zip file), extract the DLLs and use Reflector to read all our code.

The first problem can be solved by securing the transmission via transport security (using https protocol). More on this can be found at MSDN here. In this post, I will try to address the last two issues.

The good thing is that the Silverlight application and WCF service is hosted inside an ASP.NET website and luckily ASP.NET provides good tools around authentication so we can apply ASP.NET authentication techniques to secure those. The approach I like is to secure the entire ASP.NET web application using either Windows or Forms authentication and deny all anonymous users. This can be done by configuring the web.config as:

  <authentication mode="Windows"/> <!-- or Forms -->
    <deny users="?"/>

This way, if anyone tries to access the WCF service, or download the Silverlight .xap file, or view a page inside the ASP.NET website, the ASP.NET engine authenticates the request and only authorized users are able to view the application or use the service.

So now, if our application is configured to use Windows authentication, the ASP.NET engine authenticates the request via integrated windows authentication. If it succeeds, users are automatically redirected to the Silverlight application; otherwise they get a HTTP 401.1 – Unauthorized message.

And, if our application is configured to use Forms authentication, the ASP.NET engine takes the user to an aspx login page. Once the user is validated (we can use either ASP.NET built-in authentication or any custom implementation to authenticate the user), he/she is redirected to the Silverlight application.

To observe this, you can download this application (Be sure to first rename the file to zip; this is a WordPress requirement) and toggle its authentication technique between Windows and Forms using web.config.

Note that the application also demonstrates how to get the logged in user in Silverlight using a WCF service call. The key is that we can use System.Web.HttpContext.Current.User to get the current user principal if the WCF service is running in ASP.NET compatibility mode.

Screenshot of demo application

At this point, we have made sure that our application and WCF service is only accessible to authorized users. But the problem still exists to a small extent, although narrowed down to authorized users instead of general public. To further secure our application, we need to use some .NET obfuscater. This will ensure that no one, including authorized users, will be able to decompile our code using .NET reflector. And, to further enhance our WCF service security, we need to implement declarative or imperative security checks for our service methods. As with typical ASP.NET applications, we may need a custom implementation of IPrincipal and IIdentity for securing the WCF service using declarive security attributes.

That’s all. Let me know what you do think in the comments section below.


29 Responses to “Securing Silverlight Application and WCF Service using ASP.NET Authentication Techniques”

  1. Deploying a Silverlight Application and WCF Service to IIS « Mehroz’s Experiments Says:

    […] Deploying a Silverlight Application and WCF Service to IIS While deploying a Silverlight application on IIS today, I learned several new things. Let me express my observations; This post is going to describe the security settings for WCF service in web.config. To start, I assume that you are using either Windows or Forms authentication and denying all the anonymous users as described in a previous post. […]

  2. Gabriel Says:

    Hi, How can I access Data Services securily from within SL2 using auth services?
    Thanks in advance


  3. Syed Mehroz Alam Says:


    Since ADO.Net Data Services, like WCF services, are hosted inside the ASP.NET web application, so things are much similar. Since you are already using ASP.NET authentication services, make sure that you deny all anonymous users. This way, if any unauthenticated user try to access your ADO.NET data service, he will be redirected to the login page.
    Hope that helps.

  4. 15 Excellent And Useful Microsoft Silverlight Tutorials & Resources @ SmashingApps Says:

    […] Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques […]

  5. » Blog Archive » 15 Excellent And Useful Microsoft Silverlight Tutorials & Resources Says:

    […] Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques […]

  6. De Web Times - Share Your Resources » Blog Archive » 15 Useful Microsoft Silverlight Tutorials & Resources Says:

    […] Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques […]

  7. 15 Excellent And Useful Microsoft Silverlight Tutorials & Resources « - Web Resources, Web Design News & Tips, Open Source Says:

    […] Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques […]

  8. Ivan Shikht Says:

    Дякую класний пост.

  9. Some silverlight 2 tutorials « C# lovers Blog Says:

    […] Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques […]

  10. PilotBob Says:

    I am using Forms Auth on an ASP.Net web site that I am adding a Silverlight page to. however, when I call a WCF service from SL the Current principle has a non-authenticated Identity rather than the user that logged into the app.

    Any ideas why?

  11. Syed Mehroz Alam Says:

    Hi PilotBob,

    Can you make sure that you have setup your WCF service under ASP.NET compatibility mode? Also, can you try adding Thread.CurrentPrincipal = HttpContext.Current.User in the WCF service constructor. I believe you should be able to get your CustomPrincipal (as Thread.CurrentPrincipal) inside your WCF service with the above two steps.

    Let me know how it works.

  12. PilotBob Says:

    >try adding Thread.CurrentPrincipal = HttpContext.Current.User

    Yes… that seems to do the trick. Thanks so much. Is there anyway I could put this in some event handler one time so I don’t have to add this to every service.

  13. Syed Mehroz Alam Says:

    PilotBob: Is there anyway I could put this in some event handler one time so I don’t have to add this to every service.

    How about creating a MyServiceBase class, setting Thread.CurrentPrincipal in its constructor and then deriving all your services from that one?

  14. K.Kong Says:

    Hi, almost exactly what I was searching for high and low. Thanks.

    I ran it on my PC and it was fine. I then copied the app to another server (which is part of a domain) and used a server local machine userid, it went into the test page ok but clicking GetLoggedUser gives a “Not Found” error. This is an exception in the method EndGetLoggedUser.

  15. Syed Mehroz Alam Says:

    Hi K.Kong,

    I assume that you have deployed the Silverlight App on the IIS of that remote server. Did you setup an appropriate <transport clientCredentialType=""> and other settings as described in this post?

    Also, Can you try looking deeper into the problem using some HTTP sniffer e.g. Fiddler?

  16. K.Kong Says:

    Yes! That did the trick. Just saw your other article on this. Thanks a lot. Wonder why such a torturous path to something that everyone needs.

  17. Matt Says:

    Anyone know of issues with implementing the same type of application in a MVC 1.0 application? I am also using HTTPS.

    The client receives a ProtocolException apparently because the response is the login page to the website. So it seems that the WCF request is being rerouted to the web login page. I have a breakpoint in the service constuctor and I cannot even get there. I am wondering if I need to register a route for *.svc files or something…?

  18. Matt Says:

    I think the problem occurs because I am using the clientHttp instead of the BrowserHttp stack. Here is the code:

    bool ret = WebRequest.RegisterPrefix(uri.ToString(), WebRequestCreator.ClientHttp);

    I need to use the client http handling because I’m using the polling duplex capabilities in SL3 and there is a bug when aspnet compatability mode is enabled with polling duplex. Any ideas on how to enable the sample app to use ClientHttp?

    Here is the code to repro it in the sample application:

    private WCFServiceClient GetServiceClient()

    Uri uri = new Uri(Application.Current.Host.Source, “../WCFService.svc”);
    Binding binding = new System.ServiceModel.BasicHttpBinding();
    EndpointAddress endpoint = new EndpointAddress(uri);

    bool ret = WebRequest.RegisterPrefix(uri.ToString(), WebRequestCreator.ClientHttp);

    WCFServiceClient svcClient = new WCFServiceClient(binding, endpoint);
    return svcClient;

  19. Leonard Lobel Says:

    Great info, thanks for blogging it. I really love solutions like yours — simple approaches to real-world requirements, where the job can get done with just a few lines of code. You can find the other solutions elsewhere that involve much more complexity (which is great if you need it, but needless additional moving parts if you don’t).

    Question for you: How easy is it to add impersonation? I want a manager to walk over to an employee’s logged in Silverlight session, enter their credentials (without logging off) to be used as an override to the employee’s logged in credentials, either for just the next operation, or until the manager turns turns off their impersonation. At that point, things continue normally under the employee’s logged in credentials. Ideas on how to implement that, using either Windows or Forms -based authentication, would be really helpful.

  20. Syed Mehroz Alam Says:

    Thanks for your comment, Leonard. It was really nice to see an SQL evangelist at my blog. I am glad you like it.

    Impersonation in ASP.NET is typically used for resource access controls and is controlled by IIS according to the setting defined in web.config. Impersonating another user is quite interesting as well as complex scenario. Note that in ASP.NET each request re-establishes its state, hence for such custom impersonation we need to handle it in our code manually (probably all our methods may require an extra userToBeImpersonated parameter).

    However, one approach would be to utilize the ASP.NET session for storing the user to be impersonated. This way we can create and set a custom principal in our WCF service constructor thus allowing all the subsequent method calls to get that custom principal. Here’s some code to illustrate my point:

    public void ImpersonateUser(string username, string encryptedPassword)
      if SecurityManager.Autheticate(username, encryptedPassword)
        Session["UserToImpersonate"] = username;
    public void EndImpersonatation()
      Session["UserToImpersonate"] = null;
    public WCFServiceConstructor()
      if ( Session["UserToImpersonate"] != null )
        //build a custom principal and assign it
        CustomPrincipal principal = .....
        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = principal;
        //now all our method calls in WCF service will get this custom principal
    public void GetUserData()
      //should return appropriate data for current user or user impersonated
      GetSomeUserData( HttpContext.Current.User.UserName ); 

    The code that I wrote in my constructor can also be transferred to global.asax to apply it on entire web application. For some more thoughts on this, see

    These were my initial thoughts around this scenario. What is your opinion?

  21. Anthony Says:


    Man I loved this example, but I have some problems running it. When I run from localhost it I get an exception
    Error message 401.2.: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server. Contact the Web server’s administrator for additional ass

    If I run it from the visual studio web server it works but I get straight to the Silverlight app (dont need to go to the login.aspx first? if I write login.aspx in the url the authentication control works (username=pwd).
    But isnt this the first page that should appear?

    Hope you can help

  22. Anthony Says:

    Nevermind I forgot to change to Forms.
    Man I love this demo. Thank you sooooo much for sharing!!!

  23. Thest Says:

    I have an urgent matter. I have extended your demo and need to change the WCF Service. But when I e.g. add a new method I cant seem to update the service reference in the silverlight project (offcource since access now is restricted).

    But how can I update the service/stubs so that the new method is visible from the Silverlight service reference?

  24. Syed Mehroz Alam Says:


    I think you are using Forms authentication for your web application. If so, then before updating service reference, you need to temporarily change your authentication to Windows. Once you are done, you can change it back to Forms and run your project.

  25. Matt Says:

    Brilliant post – exactly what we’ve been looking for.
    Many Thanks for sharing

  26. Michael Sync Says:

    I think it would not be helpful when you host the services in different domains which is different from the domain that you host Silverlight….

  27. wordpress skins Says:

    Hello there! This post couldn’t be written any better! Reading through this post reminds me of my good old room mate! He always kept chatting about this. I will forward this write-up to him. Pretty sure he will have a good read. Thanks for sharing!

  28. App Engine Endpoints Authentication | Free Documents App Says:

    […] Securing Silverlight Application and WCF Service using ASP … – 7/1/2009 · Securing Silverlight Application and WCF Service using ASP.NET Authentication Techniques January 7, 2009 — Syed Mehroz Alam… […]

  29. CharlesEl Says:

    любопытно выслушать людей,которые уж умеют, нежели мочь удивить транссексуалы Москвы. Я по особенной натуре исследователь. ранее сигал с парашютом, с эстакады на резинке, плавал на лодке по голубой реке. И по отношению ко всему элитные девушки Москвы постоянно не терпится попробовать все в существовании. гляди и навестила меня намерение попробовать таковой тип интим услуги. К чему в сущности надобно оказаться подготовленным? каким образом себя корчить с ними? Проститутки Москвы, с коими мне случалось водиться, ничего о трансах дельного рассказать не в силах. возможно они какое-то свое общество, секретное от чужих взглядов. Я прямо-таки знать не знаю идеже их дозволено повстречать, исключая как не в всемирной паутине.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: