Search code examples
asp.net.netform-authentication

How ASP.NET form authentication works: recognising cookies from request


I am reading on form authentication in ASP.NET and cannot understand some moment:

James enters a username-password, they are saved in the db. A cookie from username is created, encrypted and attached to a response. As I understand then, when we get a request we need to recognise that cookie received are from James and so we can show his customised page.

What I would like to understand is how system will retrieve username form cookie and then load his info from db?


Solution

  • Forms Auth is storage agnostic. It doesn't have to use a database, indeed you can use it with usernames and passwords in web.config.

    So what happens is

    1. A user logs in.
    2. The user is authenticated against the membership provider (which can use SQL, Active DIrectory, web.config, Oracle, MySQL, whatever)
    3. A forms authentication token is created for the user, and is placed on the user machine via a cookie.
    4. Each subsequent request reads the forms authentication token, and queries the provider to get the user details.
    5. The user details are used to populate the user identity in the HttpContext and current thread for the request which is then available to your code to use.

    In your code you can check the User property in the Page class (WebForms) or the User property in the controller class (MVC).

    While you can get at it via the current thread, or the current context it's not advised, especially once you start using background tasks, where the identity may not propagate to the thread, or the context may change.

    You'll note that nothing is stored in a database when the user logs in. It's all in the forms authentication token, and the work of retrieving the user from it's store on each request is done for you.