I am trying to call the weather forecast endpoint after authenticating via MSAL. (Enabling user authentication in Swagger using Microsoft Identity)
As per this article.
I have created a default Identity linked API with VS2022. I have configured my client on Azure. The difference in my code is the following
s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri("https://login.microsoftonline.com/common/oauth2/v2.0/authorize"),
TokenUrl = new Uri("https://login.microsoftonline.com/common/common/v2.0/token"),
Scopes = new Dictionary<string, string>() {
{ "user.read", "Access App Graph" },
{ "api://29867508-2243-4ae2-9e04-c740dfe793a2/access_as_user","Access my Api stuff on my Client"}
}
}
}
});
I manage to Authorise via Microsoft Api, and swagger says I am Authorised. But when I try to call the weather forecast api - I am still getting a 401.
Any assistance would be amazing. I am at a loss on what to try next.
Edit. I tried to remove the scope for MS Graph (user.read) and just call the API for my client, I get a 403 error.
But the api is definitely there
I am expecting to see the data and a 200 returned when calling the weather forecast endpoint.
I trust the decoded token can explain the error message, the token had "scp": "User.Read profile openid email"
while the correct scope for your api should be "scp": "api://29867508-2243-4ae2-9e04-c740dfe793a2/access_as_user"
.
The reason for it is, you both set graph api permission(User.Read) and your custom api permission at the same time. They have different audience so the token can only generate for one of the api permission. I'm afraid if you write like below will work(just adjust the order, because when have 2 kinds of api permissions, it will generate token for the first kind of api permission).
Scopes = new Dictionary<string, string>() {
{ "api://29867508-2243-4ae2-9e04-c740dfe793a2/access_as_user","Access my Api stuff on my Client"}
{ "user.read", "Access App Graph" },
},
By the way, I had a test long time ago which had the same requirement.