Issue
I have an ASPNET Core Web Site called Web-App-1 and an ASP NET Core Web API called Web-Api-1.
-
There is functionality in Web-Api-1 that I want to secure so that it can only be called by certain users.
-
I also want to know in the Web-App-1 if the current user can call the secure functionality and if not I will not offer them the chance to do so.
I can satify requirement 1 by adding an AppRole to the api’s App Registration in AzureAd and checking the ClaimIdentity for that app role.
if (this.ControllerContext.HttpContext.User.HasClaim(
System.Security.Claims.ClaimsIdentity.DefaultRoleClaimType,
"SecuredApiFunctionality") == false)
{
return new UnauthorizedObjectResult("User does not have SecuredApiFunctionality role");
}
However when I look in the claims for that user within the context of Web-App-1 I cannot see "SecuredApiFunctionality". I assume this is because it is an AppRole belonging to Web-Api-1 and I am in Web-App-1.
I could define a second AppRole in Web-App-1 and setup priviledges to that too but that sounds like duplication to me. Is there a way of securing the API and the Web App using only one role?
Solution
Unfortunately, I don’t there’s other way to achieve what you want other than defining duplicate roles in the App
.
If you look at this sample, it is how it’s done there.
There are also few other resources:
- Github issue for this specific sample
- Stackoverflow post mentioning similar flow (see comments)
Another approach would be to call the API
for the user’s access token and have his roles there.
[Edit]:
To integrate the API call into Authorize
attribute you can use IAuthorizationMiddlewareResultHandler
. You can see simple example in docs or more comprehensive one in this post.
Answered By – Mr Patience
Answer Checked By – David Goodson (BugsFixing Volunteer)