如何通过Jquery AJAX方法生成Azure API的OAuth 2.0访问令牌
通过jQuery AJAX获取Azure OAuth 2.0访问令牌
根据你在Postman中使用的授权类型,下面分两种常见场景给出实现代码:
场景1:客户端凭证授权(Client Credentials Grant)
这种方式适合后端服务调用,无需用户交互,直接用客户端ID和密钥换取令牌。
基础实现代码
$.ajax({ url: "你的访问令牌URL", // 对应Postman中的Access Token URL type: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, data: { grant_type: "client_credentials", // 授权类型为客户端凭证 client_id: "你的客户端ID", // Postman中的Client ID client_secret: "你的客户端密钥", // Postman中的Client Secret scope: "你的作用域" // Postman中的Scope,Azure中通常格式为{资源URL}/.default,比如https://graph.microsoft.com/.default }, success: function(response) { // 拿到令牌后的处理逻辑 console.log("访问令牌:", response.access_token); console.log("令牌有效期(秒):", response.expires_in); }, error: function(xhr, status, error) { console.error("请求失败:", status, error); console.error("错误详情:", xhr.responseText); } });
若Client Authentication设置为Basic Auth
如果Postman中客户端认证方式是Basic Auth,需要把客户端ID和密钥用Base64编码后放在请求头里,此时无需在data中传client_secret:
// 先对客户端ID和密钥进行Base64编码 var authCredentials = btoa("你的客户端ID" + ":" + "你的客户端密钥"); $.ajax({ url: "你的访问令牌URL", type: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic " + authCredentials }, data: { grant_type: "client_credentials", scope: "你的作用域" }, success: function(response) { console.log("访问令牌:", response.access_token); }, error: function(xhr, status, error) { console.error("请求失败:", status, error); } });
场景2:授权码授权(Authorization Code Grant)
这种方式需要用户先跳转至授权页面登录并授权,拿到授权码后再换取令牌,适合前端应用(注意:前端直接暴露客户端密钥存在安全风险,生产环境建议通过后端代理请求)
步骤1:跳转至授权URL获取授权码
先构造授权URL,引导用户跳转至Azure的登录授权页面:
var authParams = { client_id: "你的客户端ID", response_type: "code", redirect_uri: "你的回调URL", // Postman中的Callback URL scope: "你的作用域" }; // 拼接成完整的授权URL var authUrl = "你的授权URL" + "?" + $.param(authParams); // 跳转至授权页面 window.location.href = authUrl;
步骤2:在回调页面用授权码换令牌
用户授权后会跳转到你设置的回调URL,URL参数中会携带code,此时用AJAX请求换取令牌:
// 从URL中提取授权码 var authCode = new URLSearchParams(window.location.search).get("code"); $.ajax({ url: "你的访问令牌URL", type: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, data: { grant_type: "authorization_code", // 授权类型为授权码 client_id: "你的客户端ID", client_secret: "你的客户端密钥", // 注意:前端暴露此密钥不安全,建议后端处理 redirect_uri: "你的回调URL", code: authCode }, success: function(response) { console.log("访问令牌:", response.access_token); console.log("刷新令牌:", response.refresh_token); }, error: function(xhr, status, error) { console.error("换取令牌失败:", status, error); } });
重要提醒
- 生产环境中,前端不要直接存储或传输客户端密钥,建议由后端服务代为处理令牌请求,前端仅负责跳转授权页面和将授权码传给后端。
- Azure AD的标准授权/令牌URL格式:
- 授权URL:
https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/authorize - 令牌URL:
https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token
- 授权URL:
内容的提问来源于stack exchange,提问作者Ravindranath
相关产品推荐
相关产品推荐

