Outlook Exchange Office 365:如何从访问令牌中获取电子邮件地址?

4

目前,我正在遵循这篇文章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”为空。

enter image description here
2个回答

2

这是一个很好的发现!

为了读取preferred_username,您需要在范围中包含"profile"。

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中查找权限范围的更多信息


谢谢您的快速回复,是的,现在它已经给出了电子邮件地址,但令牌为空。如何同时获取令牌和电子邮件地址。+1.. 再次感谢您的回复。 - Md. Alim Ul Karim
你指的是哪个令牌? - Jackie
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( authCode, onSuccessRedirectUri, credential, scopes); var outlookToken = new OutlookToken(); // 将令牌保存在会话中 outlookToken.Token = authResult.Token; - Md. Alim Ul Karim
我们还可以在作用域中添加“电子邮件”。 - Md. Alim Ul Karim

1
我曾看到一些情况,其中“preferred_username”声明不是SMTP地址,因此这实际上并不是获取用户电子邮件地址的最佳方法。我建议不要解析ID令牌,而是调用API以获取“GET /Me”,其中应包括“EmailAddress”属性。
我正在重新制作dev.outlook.com上的教程以执行此操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接