Search code examples
silverlightwcf-ria-servicesautologin

Silverlight and RIA Services: Persisting login across sessions


I'm currently trying out Silverlight with RIA Services. I'm implementing a simple login form. I'm also using the provided Authentication Domain Service template which generates the following file:

[EnableClientAccess]
public class AuthenticationDomainService : AuthenticationBase<User>
{
    // To enable Forms/Windows Authentication for the Web Application, 
    // edit the appropriate section of web.config file.
}

public class User : UserBase
{
    // NOTE: Profile properties can be added here 
    // To enable profiles, edit the appropriate section of web.config file.

    // public string MyProfileProperty { get; set; }
    public int DefaultRows { get; set; }
}

Now I can login/logout without problem in my application. In the Silverlight app, after logging in, the line:

WebContext.Current.User.IsAuthenticated;

return true.

However, I need to persist this across sessions (i.e. when I reload the page using F5).

Currently, when the page reloads, I have to re-login.

Here is my Login code:

WebContext.Current.Authentication.Login(new LoginParameters(this.UserName, this.Password, true, string.Empty),
                    (LoginOperation loginOperation) =>
                    {
                        if (loginOperation.LoginSuccess)
                        {
                            NotificationMessage Message = new NotificationMessage(this, null, "CLOSE");
                            Messenger.Default.Send<NotificationMessage>(Message);
                        }
                    }, null);

The third parameter of the Login method is the IsPersistent parameter. From the MSDN Docs, I'd think that when setting it to true, the next time I load the page, the user would still be logged in. However, this is not the case.

Do I somehow need to read a cookie which has been set internally and then login in the background with the username/password provided by that cookie? Or is there some other magic at work here?

I hope somehow has already done this.

Thanks in advance


Solution

  • After going through the Silverlight Business Application template, I found this line of code:

    WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null);
    

    A good place to call it is in the Application's Startup event inside App.xaml.cs. This will load the authenticated user from the server.

    I thought I'd post this if anyone happens to stumble across the same problem.