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/:
TokenService.CreateToken: a signed token with the claimssubandrole, and the issuer, audience and lifetime from theJwtsettings.AuthController:registerchecks the input, refuses a taken name, and stores the password's hash;loginchecks the password;meanswers who the token belongs to.
Program.cs: turn on JWT bearer authentication, and addUseAuthentication.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/:
Auth:loginsends the credentials and keeps the result in the signal andlocalStorage;logoutforgets it; a saved user is read back when the app starts.Login: the sign-in form, its error message, and going toreturnUrlafterwards.authInterceptor: the token on every/api/request, and signing out on a401.signedInGuard: on theproducts/newroute, sending visitors who aren't signed in to sign in.app.config.ts: switch on input binding and the interceptor.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 atProgram.cs. The test's output shows the exception. 401or403? No token, or a bad one, is401. A good token without the right role is403. The tests check both.- In the client,
auth.isSignedIn()andauth.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:
- Run
Users.sqlin SSMS, and put a key in user secrets. - Import
NorthwindApi.insomnia.jsoninto Insomnia (it becomes theNorthwind API (secured)collection), start the API, and registeradawith request 11. - Start the client with
ng serve.
At http://localhost:4200:
- 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.
- Sign in as
ada. You're back at the add page. Add a product. The developer tools' Network tab shows theAuthorizationheader. - 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. - 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.
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.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 mainPaste 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.