We love ServiceStack here at Falafel. If you’re already using it, you know why. If you haven’t used it or even heard of it, read the wiki intro to see what all the love is about.
When it comes time to create a real application with ServiceStack, you may be faced with a situation where you already have a lot of user logins already in existence in the former de-facto authentication system for Microsoft developers: ASP.NET Membership. The good news is that as long as you kept to the defaults when it came to how ASP.NET Membership stored user passwords, it is possible to authenticate users against the aspnet DB tables without needing to call any methods of the Membership class.
This is the game plan: create a custom ServiceStack CredentialsAuthProvider that will test for the existence of the user in the ServiceStack UserAuthRepository, and if it’s not found, import it from the aspnet DB tables. Once that step is complete, continue with attempting to authenticate the user against the UserAuthRepository as normal.
The simplest way to implement a custom credentials provider in ServiceStack is to subclass the one you want to customize and override the TryAuthenticate method. In this case, we want to add some extra logic smack in the middle of the normal flow of logic in TryAuthenticate, so it doesn’t flow well to call the base method and add extra logic before and after. My solution to this was to disassemble the TryAuthenticate method and copy the code into the overridden method, then modify as necessary.
The migration code is fairly straightforward if you’re familiar with the ASP.NET Membership DB tables. The queries are in strings here for simplicity, but you could easily implement them as stored procedures instead. In fact, with a stored procedure, you could return the roles in JSV format (e.g. “[Role1, Role2]”) and ServiceStack will automatically map them to a collection property such as string or List<string>, negating the need for a second query.
The final piece is the actual algorithm to compute the salted hash. Credit for this part goes to Malcom Swaine.
Then all that’s left to do is to plug it into ServiceStack during the AppHost initialization:
I’ve posted the complete file that includes the uninteresting bits as well as a GitHub Gist. I hope you find it useful!
Latest posts by Falafel Posts (see all)
- Matching Complex Query String Rewrite Rule in IIS - March 22, 2017
- Disable Content Filters in Sitefinity - March 8, 2017
- On Sitefinity Custom Widget Caching - February 22, 2017
- Dynamic Content Detail Widget Templates in Sitefinity - February 8, 2017
- Using Google Services in UWP C# Apps – Part 2 - February 7, 2017