Start learning free

LESSON 97 OF 173 · BACKEND: USERS AND SECURITY

Secrets Live Outside the Code

Practice

Until now, the shop's secrets were written in its code, like the admin's password "admin-pass-123". But code travels: to the whole team, into old copies, onto GitHub. A secret that everyone who reads the code knows is no secret.

Secrets belong in environment variables: values the server gives the program when it starts, outside the code. In C#, Environment.GetEnvironmentVariable(name) reads one, and gives null when it isn't set. ?? swaps that null for a default:

var DB_FILE = Environment.GetEnvironmentVariable("DB_FILE") ?? "shop.db";

Such values are read when the program runs, so they are vars: a const must be known when the code is compiled. For a secret, the default must be safe: a random value nobody can know, made like the login tokens with Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLower(). If a server forgets to set the admin's password, nobody can log in as admin, which is much safer than everyone who has seen the code being able to. Settings that aren't secret but change from place to place, like the address of the shop's website, come from the environment too.

The grader starts the shop with ADMIN_PASSWORD set to env-admin-pass-456 and SHOP_SITE set to https://shop.example.com. Your code must answer:

POST /login  {"email": "admin@example.com", "password": "admin-pass-123"}      →  401  {"error": "Wrong email or password"}
POST /login  {"email": "admin@example.com", "password": "env-admin-pass-456"}  →  200  {"token": "<admin>"}
GET /me  (the session cookie from that login)  →  200  {"email": "admin@example.com", "id": 1, "role": "admin"}
POST /products  {"name": "Desk", "price": 120}  (admin's token)  →  201  {"id": 9, "name": "Desk", "price": 120}
GET /products/1  Origin: https://shop.example.com  →  200, Access-Control-Allow-Origin: https://shop.example.com
GET /products/1  Origin: http://localhost:3000     →  200, no Access-Control-Allow-Origin

Your task: read ADMIN_PASSWORD from the ADMIN_PASSWORD environment variable, with a random default, and SHOP_SITE from the SHOP_SITE environment variable, with "http://localhost:3000" as its default.


Assignment
Follow the Coding Tutorial to read the admin's password and the shop's website from the environment.


Hint
Each value is one Environment.GetEnvironmentVariable(name) ?? default. The default is what the program uses on your computer and in tests, where nothing is set, so for a secret it must be something nobody can guess.


STEP 1 OF 2
    Ctrl + Enter to check