Login, sessions and cookies
HTTP forgets who you are between requests. This lesson adds registration and login to a web site: safe passwords, a session cookie that the browser sends back, and a page that only logged-in users can see.
What you will learn#
- why web servers need sessions,
- storing users with salted password hashes,
- creating and checking a session token,
- reading and setting cookies,
- the right status codes:
401,409,400, - security details that matter.
The problem#
Every HTTP request stands alone: the server does not know that the request for /profile comes from the person who logged in a minute ago. The solution is a session:
- the user logs in with a name and password,
- the server creates a long random token and remembers
token → user, - it sends the token to the browser in a cookie (
Set-Cookie), - the browser sends the cookie back with every later request (
Cookie), - the server finds the user by the token.
The program#
# login, sessions and cookies - a web site that knows who you are
load "dotnet.ring"
using {
"System"
"System.Net.Http"
"System.Security.Cryptography"
"System.Text"
"RingDotNet.Web"
"RingDotNet.Data"
}
oServer = ""
oClient = ""
cUrl = ""
oDb = ""
aSessions = [] # [token, user name]: who is logged in
func main
# THE USERS: a table; the password is never stored, only a salted slow hash of it (the tutorial "Hashing and encryption")
oDb = new RingDatabase("Data Source=:memory:",[
["Users",[["Id","int",1],["Name","string",0,[["required",1],["unique",1]]],["Salt","string",0],["Hash","string",0]]]
])
oServer = new WebServer("http://127.0.0.1:0")
oServer.onPost("/register","registerUser")
oServer.onPost("/login","loginUser")
oServer.onGet("/profile","profilePage")
oServer.onPost("/logout","logoutUser")
cUrl = oServer.url()
oClient = new HttpClient()
# A browser would keep the cookie by itself; this test client keeps it in the variable cCookie.
cCookie = ""
aResult = visit("POST","/register","name=ann&password=s3cret",cCookie)
? "register ann -> " + aResult[1] + " " + aResult[2]
aResult = visit("POST","/register","name=ann&password=other",cCookie)
? "register ann again -> " + aResult[1] + " " + aResult[2]
aResult = visit("GET","/profile","",cCookie)
? "profile, not logged in -> " + aResult[1] + " " + aResult[2]
aResult = visit("POST","/login","name=ann&password=wrong",cCookie)
? "login, wrong password -> " + aResult[1] + " " + aResult[2]
aResult = visit("POST","/login","name=ann&password=s3cret",cCookie)
? "login, right password -> " + aResult[1] + " " + aResult[2] + " (a cookie was sent: " + (len(aResult[3]) > 0) + ")"
cCookie = aResult[3]
aResult = visit("GET","/profile","",cCookie)
? "profile, with the cookie -> " + aResult[1] + " " + aResult[2]
aResult = visit("POST","/logout","",cCookie)
? "logout -> " + aResult[1] + " " + aResult[2]
aResult = visit("GET","/profile","",cCookie)
? "profile, old cookie -> " + aResult[1] + " " + aResult[2]
oServer.close()
# ---------------------------------------------------------------- the handlers
func registerUser oRequest
cName = lower(trim(oRequest.form("name")))
cPassword = oRequest.form("password")
if cName = "" or len(cPassword) < 4
return [400,"text/plain","name and a password of 4 or more characters are required"]
ok
cSalt = randomHex(16)
try
oDb.insert("Users",[["Name",cName],["Salt",cSalt],["Hash",hashPassword(cPassword,cSalt)]])
catch
return [409,"text/plain","that name is taken"]
done
return [201,"text/plain","welcome, " + cName]
func loginUser oRequest
cName = lower(trim(oRequest.form("name")))
aUsers = oDb.where("Users","Name = {0}",[cName])
# the same answer for a wrong name and a wrong password: do not tell an attacker which one was wrong
if len(aUsers) = 0 or hashPassword(oRequest.form("password"),dbValue(aUsers[1],"Salt")) != dbValue(aUsers[1],"Hash")
return [401,"text/plain","wrong name or password"]
ok
cToken = randomHex(16)
aSessions + [cToken,cName]
# the cookie: the browser sends it back with every later request. HttpOnly: scripts in the page can not read it.
oRequest.setHeader("Set-Cookie","session=" + cToken + "; HttpOnly; Path=/")
return [200,"text/plain","logged in as " + cName]
func profilePage oRequest
cUser = userOf(oRequest)
if cUser = ""
return [401,"text/plain","please log in"]
ok
return [200,"text/plain","this is the profile of " + cUser]
func logoutUser oRequest
cToken = tokenOf(oRequest)
for nIndex = 1 to len(aSessions)
if aSessions[nIndex][1] = cToken
del(aSessions,nIndex)
exit
ok
next
oRequest.setHeader("Set-Cookie","session=; Max-Age=0; Path=/")
return [200,"text/plain","logged out"]
# ---------------------------------------------------------------- sessions
# the token in the "Cookie" header of the request: "session=abc123; other=1"
func tokenOf oRequest
cHeader = oRequest.header("Cookie")
aParts = str2list(substr(cHeader,";",nl))
for cPart in aParts
cPart = trim(cPart)
if left(cPart,8) = "session="
return substr(cPart,9)
ok
next
return ""
# the user name of a session, or "" when the cookie is missing or unknown
func userOf oRequest
cToken = tokenOf(oRequest)
if cToken = ""
return ""
ok
for aSession in aSessions
if aSession[1] = cToken
return aSession[2]
ok
next
return ""
# ---------------------------------------------------------------- passwords and tokens (see the tutorial "Hashing and encryption")
func randomHex nBytes
return lower(new Convert().ToHexString(new RandomNumberGenerator().GetBytes(nBytes)))
func hashPassword cPassword, cSalt
return lower(new Convert().ToHexString((new Rfc2898DeriveBytes).@New([ :password = cPassword, :salt = cSalt, :iterations = 10000, :hashAlgorithm = new HashAlgorithmName().SHA256 ]).GetBytes(32)))
# ---------------------------------------------------------------- the test client
# send a request (with the cookie when there is one); returns [status, body, the cookie that the server sent, if any]
func visit cMethod, cPath, cForm, cCookie
oMessage = new HttpRequestMessage().@New([ :method = new HttpMethod(cMethod), :requestUri = cUrl + cPath ])
if cForm != ""
oContent = (new StringContent).@New([ :content = cForm, :encoding = new Encoding().UTF8, :mediaType = "application/x-www-form-urlencoded" ])
oMessage.Content = oContent
ok
if cCookie != ""
oMessage.Headers.Add("Cookie",cCookie)
ok
oTask = oClient.SendAsync(oMessage)
for nTry = 1 to 50
if oServer.serveOne(100)
exit
ok
next
oTask.Wait(NULL)
oResponse = oTask.Result
oBody = oResponse.Content.ReadAsStringAsync(NULL)
oBody.Wait(NULL)
# the cookie: the "Set-Cookie" header of the response, up to the first ";"
cNewCookie = ""
aFound = oResponse.Headers.TryGetValues("Set-Cookie")
if aFound[1]
cValue = aFound[2].toList()[1]
cNewCookie = trim(str2list(substr(cValue,";",nl))[1])
ok
return [oResponse.StatusCode,oBody.Result,cNewCookie]register ann -> Created welcome, ann
register ann again -> Conflict that name is taken
profile, not logged in -> Unauthorized please log in
login, wrong password -> Unauthorized wrong name or password
login, right password -> OK logged in as ann (a cookie was sent: 1)
profile, with the cookie -> OK this is the profile of ann
logout -> OK logged out
profile, old cookie -> Unauthorized please log inThis program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Registering#
registerUser reads the form fields. It refuses a missing name or a short password with 400, creates a random salt, and stores the name, the salt and a hash of the password (PBKDF2, the tutorial Hashing and encryption) — never the password itself. The unique option of the name column makes the database refuse a duplicate, which the handler turns into 409 Conflict.
Logging in#
loginUser looks up the name, hashes the typed password with that user's salt and compares it with the stored hash. If the name does not exist or the password is wrong, the answer is the same: 401 wrong name or password. A different message would tell an attacker which user names exist.
When the login is right it creates a 16-byte token from RandomNumberGenerator (never from Random, which is predictable), stores [token, user] and sends the cookie:
oRequest.setHeader("Set-Cookie","session=" + cToken + "; HttpOnly; Path=/")HttpOnly stops scripts in the page from reading the cookie; Path=/ makes the browser send it to every page of the site.
Using the session#
For each later request the browser sends Cookie: session=.... tokenOf reads that header (oRequest.header("Cookie")), splits it on ; and finds the part that starts with session=. userOf looks the token up in the list of sessions. profilePage answers 401 please log in when there is no user, and the profile when there is.
Logging out#
logoutUser removes the session from the list and sends an expired cookie (Max-Age=0) so that the browser forgets it. The old cookie is now worthless: the last line of the output shows Unauthorized for the old token.
The test client#
A browser keeps cookies by itself. The test client does it manually: after a login it reads the Set-Cookie header of the response (Headers.TryGetValues("Set-Cookie")), keeps the part before the first ;, and adds it as a Cookie header to later requests (oMessage.Headers.Add("Cookie",cCookie)).
Security notes#
| Do | Because |
|---|---|
| hash passwords with a salt and many rounds | a stolen database must not reveal passwords |
long random tokens from RandomNumberGenerator | a guessable token is a stolen account |
| the same answer for a wrong name and a wrong password | do not reveal who has an account |
HttpOnly cookies | scripts cannot steal them |
use HTTPS (not shown here) and add Secure to the cookie | on plain HTTP the cookie travels readable |
| expire sessions after some time | a forgotten login should not live forever |
| escape text put into pages (the tutorial A small web site) | otherwise a script can act as the user |
This is a teaching example. For a real site use the full features of ASP.NET Core (HTTPS, anti-forgery tokens, rate limiting of login attempts) and think carefully about threats before you store other people's data.
What you learned#
- sessions turn separate requests into a conversation,
- token → user, token in a cookie,
- store hashes, never passwords,
401/409/400,- the cookie header in both directions.
Exercises#
- Add an expiry time to each session (a date) and refuse expired ones.
- Limit failed logins: after five wrong passwords for a name, answer
429for a minute. - Add a
/change-passwordroute that needs the old password. - Store the sessions in the database so that they survive a restart.