In a particular Silverlight application, I felt it would be common for a user to have the application open for long periods, but not necessarily be interacting with it all the time. This meant that there was always a chance the user’s session would time out. Since the application uses the Membership and Role providers, nasty errors were being raised from web service calls depending on data from these providers if the session was not available.
To handle this situation, I tested for a valid session in my services and raised a custom exception if it wasn’t available. Then, using the ideas in my last post I trapped that exception in my Silverlight application and showed a login box to the user so they could log back into the application and re-establish a valid session.
The next piece of this puzzle to solve was how to gain access to the Membership Provider from the Silverlight application to log the user back in. Turns out there are two ways to go and both are equally valid for an Ajax application as well as Silverlight, though one is clearly more suitable for Ajax than Silverlight.
ASP.Net Ajax
The first solution is to use functionality built into the ASP.Net Ajax framework. There is a javascript object in the framework, Sys.Services.AuthenticationService, that provides the needed functionality. So, if you have all the necessary parts of the Ajax framework set up, in JavaScript you can say
var ssa = Sys.Services.AuthenticationService;
ssa.login(username,
password,
isPersistent,
customInfo,
redirectUrl,
onLoginComplete,
onError);
Of course you pass the username and password. IsPersistent is a bool value indicating whether or not the user wants to be “remembered” by the application. CustomInfo can be null as can the redirectUrl. Of course, if you would like the user to be redirected to a certain Url after a successful log in, you’d specify that Url. The last two values are pointers to the methods to call when the login has completed or has errored out. If you’re calling this from a web page it’s straight forward and from Silverlight, you’d need to wrap this code in a JavaScript function, and then call it from Silverlight like this.
Exposing Authentication as Web Service
Brad Abrams has an excellent tutorial on how to expose the needed functionality as a web service, here. This was the approach I ended up using in my Silverlight application because it fit well with how the rest of the application was designed. Once the functionality has been exposed as a web service, you could call this web service the same way you’d call any other from an Ajax application.