Start learning free

LESSON 93 OF 173 · BACKEND: USERS AND SECURITY

Log Out in C#

Practice

Logging out has to happen on the server. If only the browser forgot the token, anyone who had copied it could still use it. So POST /logout deletes the request's token from the tokens table. After that the shop doesn't know that token, and it gets 401 everywhere.

To delete the token, the route needs the token itself, not just the user: a user who logged in twice has two tokens. So the lines that find it (the header first, then the session) move into a method of their own, CurrentToken(), which both CurrentUser() and the /logout route call.

A DELETE is a command like the others, run with ExecuteNonQuery(). For example, a route that empties a user's cart could run:

var cmd = new SqliteCommand("DELETE FROM cart_items WHERE user_id = $user_id", db);
cmd.Parameters.AddWithValue("$user_id", user["id"]);
cmd.ExecuteNonQuery();

In the tests, Ana logs in twice: first on her phone (token <phone>, sent in the header), then in the browser (token <token>, also kept in the session). Logging out in the browser must not log the phone out:

GET /me  (cookie)  →  200  {"email": "ana@example.com", "id": 2, "role": "customer"}
POST /logout  (cookie)  →  200  {"message": "Logged out"}
GET /me  (cookie)  →  401  {"error": "Login required"}
GET /me  (Bearer <token>)  →  401  {"error": "Login required"}
GET /me  (Bearer <phone>)  →  200  {"email": "ana@example.com", "id": 2, "role": "customer"}
POST /logout  (Bearer <phone>)  →  200  {"message": "Logged out"}
GET /me  (Bearer <phone>)  →  401  {"error": "Login required"}

Your task: move the token-finding lines into string CurrentToken(HttpRequest request), let CurrentUser() use it for $token, and add POST /logout on loggedIn: it deletes this request's token, clears the session and answers {"message": "Logged out"}.


Assignment
Follow the Coding Tutorial to add a /logout route that really logs the user out.


Hint
Delete the token before you call context.Session.Clear(): CurrentToken() reads the session. CurrentToken promises a string, so C# won't compile it until it ends with return token;.


STEP 1 OF 12
    Ctrl + Enter to check

    Auth Logout in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free