I’m creating a web application in ASP.NET Core 8.0 and I require to use a named HTTP client for updating the signed in user details (e.g. phone number, display name, email..).
I require to use HTTP client since the user itself does not have permissions to make changes on their profile (idea is for the app registration in Azure to do it on behalf of user using app permissions).
App registration was given user.readwrite.all
permissions granted to the whole company.
However, when I attempt to call the HTTP action to update the user I still get a permission error as such:
External_Guest_Web_App.Pages.IndexModel: Error: Error updating user: Forbidden.
Response content:
“code”: “Authorization_RequestDenied”,
“message”:”Insufficient privileges to complete the operation.”,
“innerError”:{“date”:”2024-07-26T13:41:05″,
“request-id”:”d6d35080-3507-44be-a292-d7412460a762″,
“client-request-id”:”d6d35080-3507-44be-a292-d7412460a762″}}}
I’m struggling to understand where the problem on my code is has I’ve been attempting to follow all the steps on the tutorial here (even though this one is for Blazor apps):https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/graph-api?view=aspnetcore-8.0&pivots=named-client-graph-api
The code I have on my side is the following:
Program.cs
:
<code>using BlazorSample;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ?? builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
//Named HttpClient with IHttpClientFactory
builder.Services.AddTransient<GraphAuthorizationMessageHandler>();
builder.Services.AddHttpClient("GraphAPI",
client => client.BaseAddress = new Uri(
builder.Configuration.GetSection("MicrosoftGraph")["BaseUrl"] ??
.AddHttpMessageHandler<GraphAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetService<IHttpClientFactory>().CreateClient("GraphAPI"));
builder.Services.AddAuthorization(options =>
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Error");
app.UseHttpsRedirection();
<code>using BlazorSample;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ?? builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
//Named HttpClient with IHttpClientFactory
builder.Services.AddTransient<GraphAuthorizationMessageHandler>();
builder.Services.AddHttpClient("GraphAPI",
client => client.BaseAddress = new Uri(
builder.Configuration.GetSection("MicrosoftGraph")["BaseUrl"] ??
string.Empty))
.AddHttpMessageHandler<GraphAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetService<IHttpClientFactory>().CreateClient("GraphAPI"));
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();
</code>
using BlazorSample;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ?? builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
//Named HttpClient with IHttpClientFactory
builder.Services.AddTransient<GraphAuthorizationMessageHandler>();
builder.Services.AddHttpClient("GraphAPI",
client => client.BaseAddress = new Uri(
builder.Configuration.GetSection("MicrosoftGraph")["BaseUrl"] ??
string.Empty))
.AddHttpMessageHandler<GraphAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetService<IHttpClientFactory>().CreateClient("GraphAPI"));
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();
appsettings.json
:
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Instance": "https://login.microsoftonline.com/",
"TenantId": "[REDACTED]",
"ClientId": "[REDACTED]",
"ClientSecret": "[REDACTED]",
"CallbackPath": "/signin-oidc",
"Scopes": "User.Readwrite.all"
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "User.ReadWrite.All"
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.readwrite.all"
<code>{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "[REDACTED]",
"TenantId": "[REDACTED]",
"ClientId": "[REDACTED]",
"ClientSecret": "[REDACTED]",
"CallbackPath": "/signin-oidc",
"Scopes": "User.Readwrite.all"
},
"GraphAPI": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "User.ReadWrite.All"
},
"MicrosoftGraph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.readwrite.all"
}
}
</code>
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "[REDACTED]",
"TenantId": "[REDACTED]",
"ClientId": "[REDACTED]",
"ClientSecret": "[REDACTED]",
"CallbackPath": "/signin-oidc",
"Scopes": "User.Readwrite.all"
},
"GraphAPI": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "User.ReadWrite.All"
},
"MicrosoftGraph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.readwrite.all"
}
}
EditProfile.cshtml.cs
:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph.Models;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using System.Net.Http.Json;
using Microsoft.Graph.Models.ExternalConnectors;
using System.Net.Http.Headers;
namespace External_Guest_Web_App.Pages
[AuthorizeForScopes(ScopeKeySection = "MicrosoftGraph:Scopes")]
public class EditProfileModel : PageModel
private readonly GraphServiceClient _graphServiceClient;
private readonly HttpClient _httpClient;
private readonly ILogger<IndexModel> _logger;
private readonly IConfiguration _configuration;
// public User User { get; set; }
public EditProfileModel(ILogger<IndexModel> logger, IConfiguration configuration, GraphServiceClient graphServiceClient, HttpClient httpClient)
_graphServiceClient = graphServiceClient; ;
_httpClient = httpClient; ;
_configuration = configuration;
/*Bind properties to form*/
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public string Job { get; set; }
public IFormFile File { get; set; }
public async Task<IActionResult> OnPostAsync()
var upn = await _graphServiceClient.Me.GetAsync(); ;
var userId = upn.Id; // This should be the GUID of the user you want to update
var user = new Microsoft.Graph.Models.User
// Assume "User.Id" contains the user ID in Azure AD
//await _graphServiceClient.Users[upn.Id].PatchAsync(user);
var jsonContent = new StringContent(
JsonSerializer.Serialize(new
// Get the access token for app permissions
var accessToken = await GetAppAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Send PATCH request to update user details
var response = await _httpClient.PatchAsync($"https://graph.microsoft.com/v1.0/users/{userId}", jsonContent);
if (!response.IsSuccessStatusCode)
var responseContent = await response.Content.ReadAsStringAsync();
_logger.LogError($"Error updating user: {response.ReasonPhrase}. Response content: {responseContent}");
_logger.LogError($"Error updating user: {response.ReasonPhrase}");
ModelState.AddModelError(string.Empty, "Error updating profile. Please try again.");
return RedirectToPage("/Success");
catch (ServiceException ex)
Console.WriteLine($"Error updating user: {ex.Message}");
return RedirectToPage("/Success"); // Redirect to a success page
private async Task<string> GetAppAccessTokenAsync()
var clientId = _configuration["AzureAd:ClientId"];
var clientSecret = _configuration["AzureAd:ClientSecret"];
var tenantId = _configuration["AzureAd:TenantId"];
var scopes = new[] { "https://graph.microsoft.com/.default" };
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
var authResult = await confidentialClientApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using System.Net.Http.Json;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Microsoft.Graph.Models.ExternalConnectors;
using System.Net.Http.Headers;
namespace External_Guest_Web_App.Pages
{
[AuthorizeForScopes(ScopeKeySection = "MicrosoftGraph:Scopes")]
public class EditProfileModel : PageModel
{
private readonly GraphServiceClient _graphServiceClient;
private readonly HttpClient _httpClient;
private readonly ILogger<IndexModel> _logger;
private readonly IConfiguration _configuration;
// [BindProperty]
// public User User { get; set; }
public EditProfileModel(ILogger<IndexModel> logger, IConfiguration configuration, GraphServiceClient graphServiceClient, HttpClient httpClient)
{
_logger = logger;
_graphServiceClient = graphServiceClient; ;
_httpClient = httpClient; ;
_configuration = configuration;
}
/*Bind properties to form*/
[BindProperty]
public string FirstName { get; set; }
[BindProperty]
public string LastName { get; set; }
[BindProperty]
public string Email { get; set; }
[BindProperty]
public string Phone { get; set; }
[BindProperty]
public string Company { get; set; }
[BindProperty]
public string Job { get; set; }
[BindProperty]
public IFormFile File { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var upn = await _graphServiceClient.Me.GetAsync(); ;
var userId = upn.Id; // This should be the GUID of the user you want to update
// create user using v5
var user = new Microsoft.Graph.Models.User
{
GivenName = FirstName,
Surname = LastName,
Mail = Email,
MobilePhone = Phone,
CompanyName = Company,
JobTitle = Job
};
try
{
// Assume "User.Id" contains the user ID in Azure AD
//await _graphServiceClient.Users[upn.Id].PatchAsync(user);
var jsonContent = new StringContent(
JsonSerializer.Serialize(new
{
givenName = FirstName,
surname = LastName,
mail = Email,
mobilePhone = Phone,
companyName = Company,
jobTitle = Job
}),
Encoding.UTF8,
"application/json");
// Get the access token for app permissions
var accessToken = await GetAppAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Send PATCH request to update user details
var response = await _httpClient.PatchAsync($"https://graph.microsoft.com/v1.0/users/{userId}", jsonContent);
if (!response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
_logger.LogError($"Error updating user: {response.ReasonPhrase}. Response content: {responseContent}");
_logger.LogError($"Error updating user: {response.ReasonPhrase}");
ModelState.AddModelError(string.Empty, "Error updating profile. Please try again.");
return Page();
}
return RedirectToPage("/Success");
}
catch (ServiceException ex)
{
// Handle error
Console.WriteLine($"Error updating user: {ex.Message}");
return Page();
}
return RedirectToPage("/Success"); // Redirect to a success page
}
private async Task<string> GetAppAccessTokenAsync()
{
var clientId = _configuration["AzureAd:ClientId"];
var clientSecret = _configuration["AzureAd:ClientSecret"];
var tenantId = _configuration["AzureAd:TenantId"];
var scopes = new[] { "https://graph.microsoft.com/.default" };
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
}
}
}
</code>
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using System.Net.Http.Json;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Microsoft.Graph.Models.ExternalConnectors;
using System.Net.Http.Headers;
namespace External_Guest_Web_App.Pages
{
[AuthorizeForScopes(ScopeKeySection = "MicrosoftGraph:Scopes")]
public class EditProfileModel : PageModel
{
private readonly GraphServiceClient _graphServiceClient;
private readonly HttpClient _httpClient;
private readonly ILogger<IndexModel> _logger;
private readonly IConfiguration _configuration;
// [BindProperty]
// public User User { get; set; }
public EditProfileModel(ILogger<IndexModel> logger, IConfiguration configuration, GraphServiceClient graphServiceClient, HttpClient httpClient)
{
_logger = logger;
_graphServiceClient = graphServiceClient; ;
_httpClient = httpClient; ;
_configuration = configuration;
}
/*Bind properties to form*/
[BindProperty]
public string FirstName { get; set; }
[BindProperty]
public string LastName { get; set; }
[BindProperty]
public string Email { get; set; }
[BindProperty]
public string Phone { get; set; }
[BindProperty]
public string Company { get; set; }
[BindProperty]
public string Job { get; set; }
[BindProperty]
public IFormFile File { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var upn = await _graphServiceClient.Me.GetAsync(); ;
var userId = upn.Id; // This should be the GUID of the user you want to update
// create user using v5
var user = new Microsoft.Graph.Models.User
{
GivenName = FirstName,
Surname = LastName,
Mail = Email,
MobilePhone = Phone,
CompanyName = Company,
JobTitle = Job
};
try
{
// Assume "User.Id" contains the user ID in Azure AD
//await _graphServiceClient.Users[upn.Id].PatchAsync(user);
var jsonContent = new StringContent(
JsonSerializer.Serialize(new
{
givenName = FirstName,
surname = LastName,
mail = Email,
mobilePhone = Phone,
companyName = Company,
jobTitle = Job
}),
Encoding.UTF8,
"application/json");
// Get the access token for app permissions
var accessToken = await GetAppAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Send PATCH request to update user details
var response = await _httpClient.PatchAsync($"https://graph.microsoft.com/v1.0/users/{userId}", jsonContent);
if (!response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
_logger.LogError($"Error updating user: {response.ReasonPhrase}. Response content: {responseContent}");
_logger.LogError($"Error updating user: {response.ReasonPhrase}");
ModelState.AddModelError(string.Empty, "Error updating profile. Please try again.");
return Page();
}
return RedirectToPage("/Success");
}
catch (ServiceException ex)
{
// Handle error
Console.WriteLine($"Error updating user: {ex.Message}");
return Page();
}
return RedirectToPage("/Success"); // Redirect to a success page
}
private async Task<string> GetAppAccessTokenAsync()
{
var clientId = _configuration["AzureAd:ClientId"];
var clientSecret = _configuration["AzureAd:ClientSecret"];
var tenantId = _configuration["AzureAd:TenantId"];
var scopes = new[] { "https://graph.microsoft.com/.default" };
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
}
}
}
I checked on the debugger on this last piece of code, and is where the problem appear when I attempt to patch the user with info from my form. It complains on permissions but the access token generate in the code is valid (I used it on Postman and it works).
<code>var response = await _httpClient.PatchAsync($"https://graph.microsoft.com/v1.0/users/{userId}", jsonContent);
<code>var response = await _httpClient.PatchAsync($"https://graph.microsoft.com/v1.0/users/{userId}", jsonContent);
</code>
var response = await _httpClient.PatchAsync($"https://graph.microsoft.com/v1.0/users/{userId}", jsonContent);
I’m left to assume the problem is on how I’m creating the HTTP call but not sure where I failed. Any sort of help would be appreciated.
Thank you!