ASP.NET Core 2.2 REST API #12 — User specific content with JWT claims
Up Next: What is a Refresh Token and why your REST API needs it
We are going to use the authentic contents of the JWTs we issue, in order to create data. More specifically, we are going to create posts by using the creator’s user id.
The first step is to add 2 properties to our Post
domain object.
string UserId
[ForeignKey(nameof(UserId)) IdentityUser User
This way, EF knows about the presence of the foreign key and is going to automatically create all the constraints and the indexes for us.
We’ve already embed a id
claim in our JWT tokens. We can use that in subsequent requests.
.NET provides the HttpContext
— a bunch of properties for the current request and our application in general. There’s an easy way to get the id, by using a simple extension method:
On our post creation endpoint we can just add UserId = HttpContext.GetUserId()
to the newly created post object.
Protecting resources
We have not limited our Update and Delete operations to only take place when the user is the owner of the post.
We are going to create a new method in our post service called UserOwnsPostAsync
having the postId
and a userId
which we are going to call in our controller and return proper responses with regards to the returned value.
The implementation of this is very simple:
We can use this method on our PUT and DELETE methods as well, to make sure that only the creator of each post is able to update or delete it.
Migrations
The last part is to update our database’s schema by making and applying a new migration:
dotnet ef migrations add "Added_UserId_InPosts"
dotnet ef database update
That’s all. Feel free to test all the possible combinations of the CRUD operations, they work as expected.
That’s how you should personalise content. The server knows that the token is authentic and the user can’t fake another user’s id.
Up Next: What is a Refresh Token and why your REST API needs it
Code is available on Github and the instructional videos are located on YouTube.
Keep Coding