Exercise: Secure the App

Give the products app users, both halves of it. The API registers and signs users in with JSON Web Tokens, and protects adding, changing and deleting; the Angular client signs in, sends the token, guards the add page and shows each user only what they may do. Twelve API tests and ten client tests check it.

Journeyman · ASP.NET Core · Angular · Updated

Your products API and its Angular client are open to everyone: anyone can delete a product. In this exercise, you secure both halves, as in this chapter's lessons:

Who May
Anyone Read the products
A signed-in user Also add and change products
An admin Also delete products

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-secure-the-app, also linked from the Exercise box beside the lesson. Clone it into your bootcamp folder. In Git Bash:

cd ~/bootcamp
git clone https://github.com/ask-codey/exercise-secure-the-app.git

Git makes a folder, exercise-secure-the-app, with the exercise code inside.

Inside are two folders:

Folder Open it in Run the tests
api/ Visual Studio (NorthwindApi.slnx) Test Explorer, or dotnet test in api/
client/ VS Code npm install once, then npm test, in client/

All the tests fail to start with. They use fakes, so they need no database, no user secrets and no running API.

The README lists every file. The ones you change say what they must do in the comment at their top.

1. The API

In api/:

  1. TokenService.CreateToken: a signed token with the claims sub and role, and the issuer, audience and lifetime from the Jwt settings.
  2. AuthController:
    • register checks the input, refuses a taken name, and stores the password's hash;
    • login checks the password;
    • me answers who the token belongs to.
  3. Program.cs: turn on JWT bearer authentication, and add UseAuthentication.
  4. ProductsController: [Authorize] on adding and changing, and admins only for deleting.

The tests sign in as grace, an admin already in the fake users table, and register ada as an ordinary user.

2. The client

In client/src/app/:

  1. Auth: login sends the credentials and keeps the result in the signal and localStorage; logout forgets it; a saved user is read back when the app starts.
  2. Login: the sign-in form, its error message, and going to returnUrl afterwards.
  3. authInterceptor: the token on every /api/ request, and signing out on a 401.
  4. signedInGuard: on the products/new route, sending visitors who aren't signed in to sign in.
  5. app.config.ts: switch on input binding and the interceptor.
  6. product-list.html: the Add a product link only while someone is signed in, and Delete buttons only for admins.

Hints

  • Every piece has a twin in the lessons: Securing a Web API with JWT Bearer for the API, Login and Register in Angular and Route Guards and HTTP Interceptors for the client.
  • If every API test fails with a 500, the app couldn't start: look at Program.cs. The test's output shows the exception.
  • 401 or 403? No token, or a bad one, is 401. A good token without the right role is 403. The tests check both.
  • In the client, auth.isSignedIn() and auth.isAdmin() are signals, so @if (auth.isAdmin()) updates by itself when someone signs in or out.
  • Read a failing test's message. It says what it expected and what it found.

When you're done

All 22 tests pass. Then try it for real, as the README describes:

  1. Run Users.sql in SSMS, and put a key in user secrets.
  2. Import NorthwindApi.insomnia.json into Insomnia (it becomes the Northwind API (secured) collection), start the API, and register ada with request 11.
  3. Start the client with ng serve.

At http://localhost:4200:

  1. Signed out: the products list shows, with no Add a product link and no Delete buttons. Open http://localhost:4200/products/new: you're sent to sign in.
  2. Sign in as ada. You're back at the add page. Add a product. The developer tools' Network tab shows the Authorization header.
  3. Still no Delete buttons. In SSMS, UPDATE Users SET Role = 'Admin' WHERE UserName = 'ada';, then sign out and in again: now they're there, and deleting works.
  4. In Insomnia, request 16 sends the token from your last run of request 13. If that was before ada became an admin, it answers 403: the role is written into the token, so it changes only when she signs in again. Run 13 again, then 16: 204.

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here.

  1. On GitHub, click +, then New repository. Name it (for example exercise-secure-the-app), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In a terminal in your exercise folder (Git Bash on Windows), send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-secure-the-app.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-secure-the-app, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

You've built the whole loop: passwords stored as hashes, tokens signed by the API, every request checked against roles, and an Angular client that signs in, sends the token, and shows each user only what they may do. Every secured web app you'll work on is a version of this.

Key terms

Related