Office 365 API授权码(OAuth 2.0授权码)是用于获取访问令牌的临时凭证,它允许应用程序代表用户访问Office 365资源而无需直接处理用户凭据。
Office 365 API使用OAuth 2.0授权码授权流程,这是最安全的授权方式之一,特别适合Web应用程序。
首先需要在Azure门户中注册应用程序:
为应用程序添加所需的API权限(如Microsoft Graph权限)。
授权码通过用户重定向到Microsoft登录页面后获取。以下是构建授权请求URL的示例:
const clientId = '你的应用程序ID';
const redirectUri = encodeURIComponent('你的重定向URI');
const scopes = encodeURIComponent('openid profile email User.Read');
const authUrl = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=${clientId}
&response_type=code
&redirect_uri=${redirectUri}
&response_mode=query
&scope=${scopes}
&state=12345`;
将用户重定向到上述URL,用户登录并同意权限后,将被重定向回你的应用程序,URL查询参数中将包含授权码。
当用户被重定向回你的应用程序时,从URL中提取授权码:
// 假设重定向URI是 https://your-app.com/auth/callback?code=xxxx&state=12345
const urlParams = new URLSearchParams(window.location.search);
const authorizationCode = urlParams.get('code');
const state = urlParams.get('state');
// 验证state参数是否匹配你最初设置的值
if (state !== '12345') {
console.error('State mismatch, possible CSRF attack');
return;
}
if (authorizationCode) {
console.log('获取到的授权码:', authorizationCode);
// 现在可以使用这个授权码获取访问令牌
}
获取到授权码后,你可以用它来请求访问令牌:
async function getAccessToken(authorizationCode) {
const tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
const params = new URLSearchParams();
params.append('client_id', '你的应用程序ID');
params.append('scope', 'User.Read');
params.append('code', authorizationCode);
params.append('redirect_uri', '你的重定向URI');
params.append('grant_type', 'authorization_code');
params.append('client_secret', '你的客户端密钥'); // 仅适用于Web应用程序
try {
const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const tokenData = await response.json();
console.log('访问令牌:', tokenData.access_token);
return tokenData;
} catch (error) {
console.error('获取访问令牌失败:', error);
}
}
问题1:授权码无效或已过期
问题2:重定向URI不匹配
问题3:权限不足
问题4:state参数不匹配
通过以上步骤,你可以安全地获取Office 365 API的授权码,进而获取访问令牌来调用各种Office 365 API。