RazorPages中Microsoft Graph API委派权限发邮件遇权限问题
问题:如何正确实现委派权限流发送邮件?
场景说明
我在RazorPages中开发邮件功能,在订单详情页添加按钮,用于向Azure AD中的用户发送邮件。用户通过Duende Identity Server 6登录,该独立应用已连接到目标Azure AD,且管理员不允许使用Application权限。
当前代码实现
页面处理程序代码
public async Task<IActionResult> OnPostSubmitEmail(string emailTo, CancellationToken cancellationToken) { await _exchangeOnlineClient.SendDeniedMail("Subject", User.GetEmail(), emailTo, cancellationToken); return new JsonResult(new { successMessage = "Email verstuurd" }); }
SendDeniedMail方法代码
public async Task SendDeniedMail(string subject, string mailFrom, string mailTo, CancellationToken cancellationToken) { string content = "content"; var authProvider = new CustomTokenCredentialAuthProvider(_exchangeOnlineConfiguration.TenantId, _exchangeOnlineConfiguration.ClientId, _exchangeOnlineConfiguration.ClientSecret); var graphClient = new GraphServiceClient(authProvider); var sendMailPostRequestBody = new SendMailPostRequestBody() { Message = new Message() { Subject = subject, Body = new ItemBody() { Content = content, ContentType = BodyType.Text }, ToRecipients = new List<Recipient>() { new Recipient() { EmailAddress = new EmailAddress() { Address = mailTo } } } }, SaveToSentItems = false }; await graphClient.Users[mailFrom].SendMail.PostAsync(sendMailPostRequestBody); }
自定义令牌提供器代码
public class CustomTokenCredentialAuthProvider : IAuthenticationProvider { private ClientSecretCredential _clientSecretCredential; private IConfidentialClientApplication _confidentialClientApplicationBuilder; public CustomTokenCredentialAuthProvider(string tenantId, string clientId, string clientSecret) { _clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret); var uriBuilder = new UriBuilder("https://login.microsoftonline.com") { Path = "tenantId" }; _confidentialClientApplicationBuilder = ConfidentialClientApplicationBuilder.Create(tenantId).WithClientId(clientId).WithClientSecret(clientSecret).WithAuthority(uriBuilder.Uri).Build(); } public async Task AuthenticateRequestAsync(RequestInformation request, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default) { var result = await _confidentialClientApplicationBuilder.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync(); request.Headers.Add("Authorization", $"Bearer {result.AccessToken}"); } }
遇到的问题
- 调用Graph API发送邮件时出现错误:
Microsoft.Graph.Models.ODataErrors.ODataError: Access is denied. Check credentials and try again.
- 尝试修改作用域为
api://{ID}/.default或api://{ID}/Mail.Send.Delegated时,返回错误:
{"error":"invalid_scope","error_description":"AADSTS1002012: The provided value for scope api://{ID}/Mail.Send.Delegated is not valid. Client credential flows must have a scope value with /.default suffixed
Azure配置截图


解决方案
你当前使用的是客户端凭证流(Application权限),但需求是使用委派权限流,两种流实现逻辑完全不同,以下是正确实现步骤:
1. 调整Azure AD应用配置
- 在Azure AD应用的API权限中添加Microsoft Graph的委派权限:
Mail.Send,并完成管理员同意(按需)。 - 确保应用的身份验证设置中,已添加Duende Identity Server的重定向URI(用于授权码流),或启用客户端凭据以外的流(如授权码流、On-Behalf-Of流)。
2. 切换到On-Behalf-Of(OBO)流
用户通过Duende Identity Server登录,后端需以用户身份调用Graph API,应使用On-Behalf-Of流,流程为:
- 用户登录Duende Identity Server,获取ID Token和Access Token。
- 前端将该Access Token发送到RazorPages后端。
- 后端使用OBO流,用用户的Access Token交换得到Microsoft Graph的Access Token。
- 使用Graph的Access Token调用发送邮件接口。
3. 修改代码实现
替换自定义认证提供器为OBO流实现
public class OboAuthProvider : IAuthenticationProvider { private readonly string _clientId; private readonly string _clientSecret; private readonly string _tenantId; private readonly string _userAccessToken; public OboAuthProvider(string tenantId, string clientId, string clientSecret, string userAccessToken) { _tenantId = tenantId; _clientId = clientId; _clientSecret = clientSecret; _userAccessToken = userAccessToken; } public async Task AuthenticateRequestAsync(RequestInformation request, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default) { var confidentialClient = ConfidentialClientApplicationBuilder .Create(_clientId) .WithClientSecret(_clientSecret) .WithAuthority($"https://login.microsoftonline.com/{_tenantId}/v2.0") .Build(); // OBO流获取Graph的AccessToken var result = await confidentialClient.AcquireTokenOnBehalfOf(new[] { "https://graph.microsoft.com/Mail.Send" }, new UserAssertion(_userAccessToken)) .ExecuteAsync(cancellationToken); request.Headers.Add("Authorization", $"Bearer {result.AccessToken}"); } }
修改SendDeniedMail方法,传入用户的Access Token
// 页面处理程序中获取用户的Access Token(从Claims或请求头中) public async Task<IActionResult> OnPostSubmitEmail(string emailTo, CancellationToken cancellationToken) { // 假设用户的Access Token存储在Claims中,键为"access_token" var userAccessToken = User.FindFirst("access_token")?.Value; if (string.IsNullOrEmpty(userAccessToken)) { return new JsonResult(new { errorMessage = "用户未提供有效令牌" }); } await _exchangeOnlineClient.SendDeniedMail("Subject", User.GetEmail(), emailTo, userAccessToken, cancellationToken); return new JsonResult(new { successMessage = "Email verstuurd" }); } // 更新SendDeniedMail方法 public async Task SendDeniedMail(string subject, string mailFrom, string mailTo, string userAccessToken, CancellationToken cancellationToken) { string content = "content"; var authProvider = new OboAuthProvider(_exchangeOnlineConfiguration.TenantId, _exchangeOnlineConfiguration.ClientId, _exchangeOnlineConfiguration.ClientSecret, userAccessToken); var graphClient = new GraphServiceClient(authProvider); var sendMailPostRequestBody = new SendMailPostRequestBody() { Message = new Message() { Subject = subject, Body = new ItemBody() { Content = content, ContentType = BodyType.Text }, ToRecipients = new List<Recipient>() { new Recipient() { EmailAddress = new EmailAddress() { Address = mailTo } } } }, SaveToSentItems = false }; // 委派权限下,使用Me.SendMail而不是Users[mailFrom].SendMail,因为令牌代表当前用户身份 await graphClient.Me.SendMail.PostAsync(sendMailPostRequestBody, cancellationToken: cancellationToken); }
4. 关键注意事项
- 作用域选择:委派权限流中使用
https://graph.microsoft.com/Mail.Send作为作用域,/.default是应用权限流的用法。 - OBO流要求:Duende Identity Server颁发的令牌必须包含
scp声明(委派权限),且Azure AD应用需被授权访问该令牌的受众。 - API调用方式:委派权限下使用
graphClient.Me.SendMail,而非Users[mailFrom].SendMail,因为令牌代表当前用户身份,Me会自动映射到该用户。
内容的提问来源于stack exchange,提问作者DaanJ
相关产品推荐
相关产品推荐

