如何在控制台/Excel中实现类似az login的浏览器认证流程?
实现本地应用发起企业SSO认证(授权码流)
核心原理
本质是授权码流的桌面端适配:本地应用启动临时HTTP服务器监听指定本地端口,构造授权URL引导用户在浏览器完成企业SSO认证;IdM认证完成后会将授权码重定向到本地监听端口,应用拿到授权码后调用IdM的token端点换取access_token和refresh_token;后续access_token过期时,直接用refresh_token刷新,无需重复打开浏览器。
一、控制台应用实现(以C#为例)
1. 前置IdM配置
- 在企业IdM控制台创建公共客户端应用(桌面/控制台应用无客户端密钥)
- 设置重定向URI为
http://localhost:8400(可自定义未占用端口) - 为应用授予目标API的访问权限(如
api://your-api-id/ReadData)
2. 代码实现流程
using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Threading.Tasks; class SSOAuthClient { static async Task Main(string[] args) { // 配置参数,替换为你的实际值 var clientId = "your-client-id"; var redirectUri = "http://localhost:8400"; var authEndpoint = "https://your-idm-domain/oauth2/authorize"; var tokenEndpoint = "https://your-idm-domain/oauth2/token"; var scope = "api://your-api-id/ReadData offline_access"; // offline_access用于获取refresh_token // 启动临时HTTP监听 var listener = new HttpListener(); listener.Prefixes.Add($"{redirectUri}/"); listener.Start(); Console.WriteLine("请在弹出的浏览器中完成认证..."); // 构造授权URL并打开浏览器 var authUrl = $"{authEndpoint}?client_id={clientId}&redirect_uri={Uri.EscapeDataString(redirectUri)}&response_type=code&scope={Uri.EscapeDataString(scope)}&state={Guid.NewGuid()}"; Process.Start(new ProcessStartInfo(authUrl) { UseShellExecute = true }); // 接收回调并提取授权码 var context = await listener.GetContextAsync(); var code = context.Request.QueryString["code"]; listener.Stop(); // 换取Token using var httpClient = new HttpClient(); var formData = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "authorization_code"), new KeyValuePair<string, string>("client_id", clientId), new KeyValuePair<string, string>("code", code), new KeyValuePair<string, string>("redirect_uri", redirectUri) }); var tokenResp = await httpClient.PostAsync(tokenEndpoint, formData); var tokenJson = await tokenResp.Content.ReadAsStringAsync(); Console.WriteLine("获取到Token:\n" + tokenJson); // 后续可保存refresh_token,过期时自动刷新 // 调用API时在Authorization头中携带Bearer {access_token} } }
二、Excel VBA实现
1. 前置准备
- 启用Excel开发工具,添加引用:
Microsoft XML, v6.0和Microsoft WinHTTP Services, version 5.1 - 确保本地安装PowerShell(用于临时监听端口)
2. 代码实现
Sub SSOAuth_Excel() ' 替换为你的实际配置 Dim clientId As String, redirectUri As String Dim authEndpoint As String, tokenEndpoint As String, scope As String clientId = "your-client-id" redirectUri = "http://localhost:8400" authEndpoint = "https://your-idm-domain/oauth2/authorize" tokenEndpoint = "https://your-idm-domain/oauth2/token" scope = "api://your-api-id/ReadData offline_access" ' 用PowerShell启动临时端口监听,获取授权码 Dim psScript As String, code As String psScript = "$listener = New-Object System.Net.HttpListener; $listener.Prefixes.Add('" & redirectUri & "/'); $listener.Start(); $context = $listener.GetContext(); $code = $context.Request.QueryString['code']; $listener.Stop(); Write-Output $code" code = CreateObject("WScript.Shell").Exec("powershell -Command """ & psScript & """").StdOut.ReadAll() code = Trim(code) ' 调用Token端点换取凭证 Dim http As Object, formData As String, tokenJson As String Set http = CreateObject("WinHttp.WinHttpRequest.5.1") http.Open "POST", tokenEndpoint, False http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" formData = "grant_type=authorization_code&client_id=" & clientId & "&code=" & code & "&redirect_uri=" & redirectUri http.Send formData tokenJson = http.ResponseText ' 将Token保存到单元格(可加密存储) ThisWorkbook.Sheets("Sheet1").Range("A1").Value = tokenJson End Sub ' 调用API示例 Sub CallProtectedAPI() Dim accessToken As String, apiUrl As String accessToken = Split(Split(ThisWorkbook.Sheets("Sheet1").Range("A1").Value, """access_token"":""")(1), """")(0) apiUrl = "https://your-api-domain/api/data" Dim http As Object Set http = CreateObject("WinHttp.WinHttpRequest.5.1") http.Open "GET", apiUrl, False http.SetRequestHeader "Authorization", "Bearer " & accessToken http.Send ' 将API返回数据写入单元格 ThisWorkbook.Sheets("Sheet1").Range("B1").Value = http.ResponseText End Sub
三、关键注意事项
- 端口冲突:选择不常用的本地端口(如8080、8400),避免被其他程序占用
- Refresh Token:必须在scope中添加
offline_access,才能获取可用于刷新的refresh token - 安全存储:控制台应用可使用系统凭据管理器存储token,Excel可加密保存token所在工作表
- IdM适配:不同企业IdM(如ADFS、Azure AD)的授权/token端点格式略有差异,需参考对应官方文档调整参数
内容的提问来源于stack exchange,提问作者eXavier
相关产品推荐
相关产品推荐

