In part 1 (RIA security 101: Logins, web services, usernames and passwords), I discuss the importance of security in RIAs (Rich Internet Applications) and set the ground rules for allowing web services to authenticate calls from the client. In this article, I will show you how using the built in ASP.NET session object.
When the user logs into your service, validate their login and save something that uniquely identifies them (their username or user ID typically) in the session object.
<OperationContract()> _
Public Function Login(ByVal Username As String, ByVal Password As String) As Boolean
If DatabaseWrapper.IsLoginValid(Username, Password) Then
HttpContext.Current.Session(“Username”) = Username
Return True
Else
HttpContext.Current.Session.Abandon()
Return False
End If
End Function
The next time the user calls a method on your service that requires authentication, check for the existance of a user ID or username in the session object and if it’s there, you’ll know they are a valid user since only successfully logged in users will have their information added to the session object.
<OperationContract()> _
Public Function IsLoggedin() As Boolean
Return HttpContext.Current.Session(“LoggedIn”) IsNot Nothing
End Function
<OperationContract()> _
Public Sub UpdateSomething(ByVal Something As String)
If IsLoggedin() Then
DatabaseWrapper.SetDataForUser(DirectCast(HttpContext.Current.Session(“Username”), String), Something)
Else
Throw New Exception(“Session has expired”)
End If
End Sub
ASP.NET handles all the heavly lifting for you by:
- Associating your session data with a unique session ID (aka token)
- Passing that session ID down to the client in the form of a cookie
- Storing your session data between calls to the server (in memory, state server, or a database depending on how you have it configured)
- Retrieving that session data when you need it by looking up the session ID stored in their cookie.
- Making sure that session expires eventually so it’s not vulnerable to hackers.
Check out the source code to see a fully functioning Silverlight client and WCF web service working together to securely manage login data between service calls. Login through an HTML based login (Homepage.htm) or the Silverlight client itself (hosted within Default.aspx).