You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.Net Core MVC中通过邮箱密码获取Office 365认证Bearer Token

在ASP.Net Core MVC中通过邮箱密码获取Office 365 Bearer Token的实现方法

前提说明

Office 365身份认证基于Azure AD,要通过邮箱密码直接获取Bearer Token,需使用Resource Owner Password Credentials (ROPC) 流。但注意:

  • 该流不支持启用MFA的用户
  • 仅适用于Delegated权限(无法调用Application权限的API)
  • 需确保Azure AD租户允许此认证方式

1. 注册并配置Azure AD应用

  • 登录Azure门户,进入Azure Active Directory → 应用注册,创建新应用
  • 在认证页面,启用"允许公共客户端流"(ROPC属于公共客户端流范畴)
  • 切换到API权限页面,添加所需的Delegated权限(例如User.Read、Mail.Read等),并点击"授予管理员同意"
  • 记录应用的租户ID、客户端ID,若为机密客户端,还需生成并记录客户端密码

2. 安装依赖包

在ASP.Net Core MVC项目中安装MSAL库:

Install-Package Microsoft.Identity.Client

3. 配置应用参数

在appsettings.json中添加Azure AD相关配置:

"AzureAd": {
  "TenantId": "你的租户ID",
  "ClientId": "你的客户端ID",
  "ClientSecret": "你的客户端密码(机密客户端需要)",
  "Scopes": "User.Read Mail.Read",
  "Authority": "https://login.microsoftonline.com/{TenantId}"
}

4. 编写Token获取工具类

创建工具类(例如TokenService.cs)封装获取逻辑:

using Microsoft.Identity.Client;
using Microsoft.Extensions.Configuration;

public class TokenService
{
    private readonly IConfiguration _configuration;

    public TokenService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public async Task<string> GetBearerTokenAsync(string username, string password)
    {
        var tenantId = _configuration["AzureAd:TenantId"];
        var clientId = _configuration["AzureAd:ClientId"];
        var clientSecret = _configuration["AzureAd:ClientSecret"];
        var scopes = _configuration["AzureAd:Scopes"].Split(' ');
        var authority = _configuration["AzureAd:Authority"].Replace("{TenantId}", tenantId);

        IConfidentialClientApplication app;

        if (!string.IsNullOrEmpty(clientSecret))
        {
            // 机密客户端模式
            app = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(authority)
                .Build();
        }
        else
        {
            // 公共客户端模式
            app = PublicClientApplicationBuilder
                .Create(clientId)
                .WithAuthority(authority)
                .Build();
        }

        var result = await app.AcquireTokenByUsernamePassword(scopes, username, password)
            .ExecuteAsync();

        return result.AccessToken;
    }
}

5. 在MVC控制器中使用

在控制器中注入TokenService并调用:

public class HomeController : Controller
{
    private readonly TokenService _tokenService;

    public HomeController(TokenService tokenService)
    {
        _tokenService = tokenService;
    }

    public async Task<IActionResult> GetToken()
    {
        string username = "user@yourdomain.onmicrosoft.com";
        string password = "userpassword";
        
        try
        {
            var token = await _tokenService.GetBearerTokenAsync(username, password);
            // 后续可使用token调用Office 365 API
            return Content($"Bearer Token: {token}");
        }
        catch (MsalException ex)
        {
            return Content($"获取Token失败: {ex.Message}");
        }
    }
}

注意事项

  • ROPC流安全性较低,仅在无法使用授权码流等更安全方式时选用
  • 禁止在前端页面暴露邮箱密码,务必在后端处理认证逻辑
  • 若用户启用MFA,此方法直接失效,需改用支持MFA的认证流

内容的提问来源于stack exchange,提问作者Emre Serper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:07:24