RIA Services provides a Authentication Domain Service template to use for enabling windows or forms authentication in your Silverlight application. Most of the out-of-the-box setup works fine if your project has everything in a single assembly, but when building larger scale applications that may use a RIA Services Class Library, there are a few extra steps you'll need to take for everything to work correctly.
You'll know there is a problem finding your AuthenticationContext if you get this error:
The DomainContextType is null or invalid and there are no contexts generated from AuthenticationBase<T>
If you are setting up your WebContext (or whatever you may have named your RIA Context that derives from WebContextBase) in App.xaml, the extra code is a bit more intuitive. Simply set the DomainContextType so it points to the assembly where your generated AuthenticationContext is located:
<Application.ApplicationLifetimeObjects>
<svc:WebContext>
<svc:WebContext.Authentication>
<appsvc:FormsAuthentication DomainContextType="My.RIA.Namespace.AuthenticationContext, My.Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<!--<appsvc:WindowsAuthentication/>-->
</svc:WebContext.Authentication>
</svc:WebContext>
</Application.ApplicationLifetimeObjects>
If you are declaring your WebContext in the codebehind of App.xaml.cs, you need to set the DomainContext like this:
using System.ServiceModel.DomainServices.Client.ApplicationServices;
//...
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
// Create a WebContext and add it to the ApplicationLifetimeObjects
// collection. This will then be available as WebContext.Current.
WebContext webContext = new WebContext();
webContext.Authentication = new FormsAuthentication();
//webContext.Authentication = new WindowsAuthentication();
this.ApplicationLifetimeObjects.Add(webContext);
}
private void Application_Startup(object sender, StartupEventArgs e)
{
// AuthenticationContext exists in a separate assembly, reference it here
((WebAuthenticationService)WebContext.Current.Authentication).DomainContext = new My.RIA.Namespace.AuthenticationContext();
// This will enable you to bind controls in XAML files to WebContext.Current
// properties
this.Resources.Add("WebContext", WebContext.Current);
// This will automatically authenticate a user when using windows authentication
// or when the user chose "Keep me signed in" on a previous login attempt
WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null);
// Show some UI to the user while LoadUser is in progress
this.InitializeRootVisual();
}