[英]Outlook Exchange Office 365: How to get email address from access token?
目前,我正在關注這篇文章https://dev.outlook.com/restapi/tutorial/dotnet 。 一切都很好,期望我無法從訪問令牌中檢索用戶的電子郵件地址。
private string GetEmailFromIdToken(string token) {
// JWT is made of three parts, separated by a '.'
// First part is the header
// Second part is the token
// Third part is the signature
string[] tokenParts = token.Split('.');
if (tokenParts.Length < 3) {
// Invalid token, return empty
}
// Token content is in the second part, in urlsafe base64
string encodedToken = tokenParts[1];
// Convert from urlsafe and add padding if needed
int leftovers = encodedToken.Length % 4;
if (leftovers == 2) {
encodedToken += "==";
} else if (leftovers == 3) {
encodedToken += "=";
}
encodedToken = encodedToken.Replace('-', '+').Replace('_', '/');
// Decode the string
var base64EncodedBytes = System.Convert.FromBase64String(encodedToken);
string decodedToken = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
// Load the decoded JSON into a dynamic object
dynamic jwt = Newtonsoft.Json.JsonConvert.DeserializeObject(decodedToken);
// User's email is in the preferred_username field
return jwt.preferred_username;
}
在一些文章中,人們說添加“openid”
private static string[] scopes = { "openid", "https://outlook.office.com/mail.read",
"https://outlook.office.com/calendars.read" };
在范圍內。 但它仍然無效。 它甚至沒有成功登錄,拋出異常。 當我不添加“openid”時,我獲得了成功登錄,但preferred_username為空。
這是一個很好的抓住!
您需要包含“profile”范圍才能讀取preferred_username,
private static string[] scopes = { "profile",
"https://outlook.office.com/mail.read",
"https://outlook.office.com/calendars.read" };
或者,嘗試使用“contacts.read”范圍
private static string[] scopes = { "https://outlook.office.com/contacts.read",
"https://outlook.office.com/mail.read",
"https://outlook.office.com/calendars.read" };
有關權限范圍的更多信息, 請訪問https://github.com/OfficeDev/microsoft-graph-docs/blob/master/content/authorization/permission_scopes.md
我在某些情況下看到preferred_username
聲明不是SMTP地址,因此它實際上不是獲取用戶電子郵件地址的最佳方式。 我建議不要解析ID令牌,只需對GET /Me
進行API調用,其中應包含EmailAddress
屬性。
我正在重新編寫dev.outlook.com上的教程來完成這項工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.