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

如何在ASP.NET Framework (WebForms)中集成Microsoft账号登录API

适配WebForm的Microsoft账号登录实现方案(无需Identity框架)

前置准备

  • 完成Azure应用注册,获取客户端ID(Client ID)、客户端密钥(Client Secret)
  • 配置应用的重定向URI为你的回调页面地址,示例为https://你的站点域名/MicrosoftLoginCallback.aspx
  • 勾选令牌发放设置中的「ID令牌」「访问令牌」选项
  • 配置API权限为openid、email、profile,如需多租户访问需完成管理员同意

第一步:安装依赖库

通过NuGet包管理器安装官方MSAL库,完全不依赖ASP.NET Identity框架:
Install-Package Microsoft.Identity.Client

第二步:登录按钮页面实现(示例为Login.aspx)

前端代码

<asp:Button ID="btnMicrosoftLogin" runat="server" Text="使用Microsoft账号登录" OnClick="btnMicrosoftLogin_Click" />

后端点击事件代码(Login.aspx.cs)

using Microsoft.Identity.Client;
using System;

protected void btnMicrosoftLogin_Click(object sender, EventArgs e)
{
    // 替换为你的实际配置参数
    string clientId = "你的Azure应用客户端ID";
    string clientSecret = "你的Azure应用客户端密钥";
    string redirectUri = "https://你的站点域名/MicrosoftLoginCallback.aspx";
    string authority = "https://login.microsoftonline.com/common/v2.0";

    // 构建MSAL客户端实例
    var app = ConfidentialClientApplicationBuilder
        .Create(clientId)
        .WithClientSecret(clientSecret)
        .WithRedirectUri(redirectUri)
        .WithAuthority(authority)
        .Build();

    // 定义权限范围,必须包含email才能获取用户邮箱信息
    string[] scopes = { "openid", "email", "profile" };

    // 生成授权地址跳转至微软登录页
    var authUrl = app.GetAuthorizationRequestUrl(scopes).ExecuteAsync().Result;
    Response.Redirect(authUrl.AbsoluteUri);
}

第三步:回调页面实现(MicrosoftLoginCallback.aspx)

该页面无需前端展示内容,仅用于处理微软登录后的回调逻辑,兑换令牌并提取用户信息:

后端代码(MicrosoftLoginCallback.aspx.cs)

using Microsoft.Identity.Client;
using System;
using System.Security.Claims;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // 配置参数和登录页保持一致
        string clientId = "你的Azure应用客户端ID";
        string clientSecret = "你的Azure应用客户端密钥";
        string redirectUri = "https://你的站点域名/MicrosoftLoginCallback.aspx";
        string authority = "https://login.microsoftonline.com/common/v2.0";

        var app = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithClientSecret(clientSecret)
            .WithRedirectUri(redirectUri)
            .WithAuthority(authority)
            .Build();

        // 从回调请求中获取授权码
        string authCode = Request.QueryString["code"];
        if (!string.IsNullOrEmpty(authCode))
        {
            string[] scopes = { "openid", "email", "profile" };
            // 用授权码兑换访问令牌和ID令牌
            var result = app.AcquireTokenByAuthorizationCode(scopes, authCode).ExecuteAsync().Result;
            
            // 提取需要的业务字段
            string accessToken = result.AccessToken;
            string userEmail = result.ClaimsPrincipal.FindFirst(ClaimTypes.Email)?.Value 
                ?? result.ClaimsPrincipal.FindFirst("preferred_username")?.Value;

            // 可将token和邮箱存入服务端Session、加密Cookie或业务存储供后续使用
            Session["MicrosoftAccessToken"] = accessToken;
            Session["UserEmail"] = userEmail;

            // 登录成功跳转至业务页面
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            // 自定义登录失败逻辑
            Response.Write("登录失败:未获取到授权凭证");
        }
    }
}

注意事项

  • 生产环境不要硬编码客户端ID、密钥等敏感信息,建议存入Web.config的appSettings节点并做加密处理
  • 令牌不要明文存储在前端,建议存入服务端Session或者加密的HttpOnly Cookie中
  • 单租户应用可将authority地址中的common替换为你的租户ID,限制仅企业内部账号登录
  • 如需调用Microsoft Graph接口,在权限范围中添加对应的Graph权限即可

内容的提问来源于stack exchange,提问作者Daniel Ashraf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:07