This is my implementation notes when I was setting up forms authentication in a web app project that uses Nancy.
Nancy forms authentication allows user to login with username and password. It then converts this username and password into a token, and then sends the token into user’s browser as a cookie. The next time user sends a request to the Nancy server, the cookie will be included in the request. Nancy can then deduct the user from the token, and allow or deny access to the page.
First step is to nuget Nancy forms authentication:
Install-Package Nancy.Authentication.Forms
Next, implement the Nancy.Security.IUserIdentity interface. Simplest one is like this:
But most likely you need to implement this interface on your already existing user class.
Next, implement the Nancy.Authentication.Forms.IUserMapper interface. This is used to determine the user from a received token. If you don’t yet have a way to determine user from a GUID, you need to create that mechanism before you can implement this interface.
Next, create a custom bootstrapper.
Optional step: override ConfigureRequestContainer to set IUserMapper lifecycle to one instance per HTTP request. This is recommended if your database session lifecycle is also one instance per HTTP request.
Next, override RequestStartup. After the standard RequestStartup, add a call to FormsAuthentication.Enable.
Next, add a route so there’s something in “~/login” (see RedirectUrl in FormsAuthenticationConfiguration above).
Next, add a route to handle user login request. This method is responsible to check whether the password matches the username. If user provides a correct combination, find out the user’s GUID from provided username and password, then call LoginAndRedirect (or LoginWithoutRedirect). LoginAndRedirect will send a cookie to user’s browser.
Next, add a route to handle logout requests. Within the method call LogoutAndRedirect. Then provide links to this in the HTML.
Next, in modules that require authentication, add a call to RequiresAuthentication.