c# - Outlook Exchange 办公室 365 : How to get email address from access token?

标签 c# outlook oauth-2.0 office365 access-token

目前,我正在关注这篇文章https://dev.outlook.com/restapi/tutorial/dotnet .一切正常,但我无法从访问 token 中检索用户的电子邮件地址。

 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 为空。 enter image description here

最佳答案

这是一个很好的收获!

您需要包含“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 中查找有关权限范围的更多信息

关于c# - Outlook Exchange 办公室 365 : How to get email address from access token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267705/

相关文章:

c# - 如何正确使用锁具

c# - 如何在 C# 中自动化后关闭 Outlook

node.js - SPA+API OAuth流程,用什么?

c# - 保存位图时发生 GDI+ 异常中的一般错误

c# - 将结构值分配给此关键字

c# - XAML TextBox isReadOnly 绑定(bind)

c# - DocumentItem.SaveAs 导致文件损坏

vba - 将已读项目从文件夹移回收件箱

python - 使用lepture/authlib获取refresh_token

android - 谷歌播放服务 sdk : Requesting for offline access during auth