I am setting up an authentication and authorization for my minimal API (.Net 7) using this tutorial: https://www.telerik.com/blogs/authorization-authentication-minimal-apis
I have never done this before and I am curious if my idea is correct or not. I need to check if the data that should have been received from the database are connected with the authenticated user (basically I want to prevent other users to view data of other users - only "Admin" role can do that). Would this be the right way how to do that or am I missing something (is there some more elegant way than written below)?
In this example: lets say that only when user is logged in (user with nickname "test123) he can receive only his information (data from database about the user "test123") but not about any others (only the logged in user with role "Admin" can do that):
app.MapGet("/users/{nickname}", (string nickname, ClaimsPrincipal user, IUserData userData) =>
{
if (user?.Identity?.Name == nickname ||
user?.IsInRole("Admin") ?? false)
{
try
{
return Results.Ok(await userData.GetUserByNickname());
}
catch(Exception ex)
{
return Results.Problem(ex.Message);
}
}
return Results.Unauthorized();
});