Repository navigation
User Authorization with JWT
The app uses JWT tokens to identify logged in users, this works as follows:
- A user logs in with their username/password via the frontend
- The backend generates a "JWT" (JSON Web Token) for the user, this contains "Claims" (e.g. "This token belongs to user x") and is digitally signed by the backend, so it can be validated later.
- The frontend stores the JWT.
- Whenever the frontend needs to make an authenticated request (e.g. "Get flat payments"), the JWT is included in the
headerfield of the request. - The backend can decode the JWT in the requests (automatically done by .NET core). It can validate the JWT is authentic (real and issued by the backend) and then read the claims.
- The backend uses the claims encoded in the JWT to find the appropriate user in the database, and serve appropriate content (e.g. the payments for the flat that user belongs to).
To login, a request with a username and password needs to be made to the api/user/login endpoint. On successful login, an object containing a jwt token is returned.
If the username/password combination does not match an existing user, a Not Found or a Forbidden error is returned
On subsequent requests that require authorization, this token needs to be passed in the request headers to the server. This has the following format:
header: { Authorization: "Bearer <jwt-token-here>" }
If you're writing a backend controller, you may want to get a User object for the current User making that request.
Here's a simple example of that:
-
Extract the claims from the HttpContext (note: Make sure the controller is a subclass of Controller)
-
Get the user Id claim
-
Get the corresponding user from the database (note: You'll need a DB context object)
```[HttpGet("whoami")] [Authorize] public ActionResult<string> WhoAmI() { var identity = HttpContext.User.Identity as ClaimsIdentity; var userID = Int32.Parse(identity.FindFirst(ClaimTypes.NameIdentifier).Value); var user = _database.User.First(user => user.Id == userID); return user.Email; }```
Notes: You need the [Authorize] tag before the method which tells .NET Core that requests have to have an appropriate Authorization: header with a valid JWT token.
- Home
- Data Model
- Architecture
- API Documentation
- Front End Documentation
- Testing
- Prototyping
- Other
- Contributing Guidelines and Etiquitte
- Labels
- License
- Admin