未经授权的Azure AD B2C Graph API 401

时间:2019-12-18 03:51:24

标签: azure oauth-2.0 jwt azure-active-directory azure-ad-b2c

我正在尝试执行Azure AD Graph API REST API调用以获取当前登录的用户信息。但是,对https://graph.windows.net/me?api-version=1.6的HTTP GET调用总是失败,响应为 401 Unauthorized 。我已经在Azure AD中注册了一个应用程序,并配置了以下API权限:

enter image description here

授权端点的呼叫如下所示:

  

HTTP GET https:// {my tenant} .b2clogin.com / {my   租户} .onmicrosoft.com / oauth2 / v2.0 / authorize?p = B2C_1_signinsignup&client_id = {我   应用程式   id}&nonce = defaultNonce&redirect_uri = https://localhost:44351/Login/LoginResponse&scope=https://graph.windows.net/Directory.AccessAsUser.All   https://graph.windows.net/User.Read&response_type=code&prompt=login

对令牌端点的调用如下所示:

  

HTTP POST到URL:https:// {my tenant} .b2clogin.com / {my   租户} .onmicrosoft.com / B2C_1_signinsignup / oauth2 / v2.0 / token内容   类型:application / x-www-form-urlencoded

身体:

  

grant_type = authorization_code&client_id = {我的应用   id}&scope = https://graph.windows.net/Directory.AccessAsUser.All   https://graph.windows.net/User.Read&code= {   授权   端点}&redirect_uri = https://localhost:44351/Login/LoginResponse&client_secret= {来自门户网站的秘密}

到令牌端点的HTTP POST成功。我获得了JWT令牌,并且能够从JWT成功检索访问令牌。但是,当我尝试使用此访问令牌检索用户详细信息时,以下代码每次都会失败,并显示401响应。错误消息是

  

“ odata.error”:{“ code”:“ Authentication_ExpiredToken”,“ message”:{“ lang”:“ en”,“ value”:“您的   访问令牌已过期。请在提交之前续订   请求。“}}}”

string strURL = @"https://graph.windows.net/me?api-version=1.6";
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(strURL);
                httpWebRequest.Headers.Add("Authorization", $"Bearer {jWTToken.access_token}");                
                using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                    {
                        string str = streamReader.ReadToEnd();
                    }
                }

以上代码中使用的JWT令牌是我从Token端点收到的令牌。为什么会失败? jwt.ms对我收到的访问令牌进行解码,如下所示:

{
  "typ": "JWT",
  "alg": "RS256",
  "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}.{
  "iss": "https://{my tenant}.b2clogin.com/fc292353-4def-47bd-af44-b92e40798a60/v2.0/",
  "exp": 1576642155,
  "nbf": 1576638555,
  "aud": "00000002-0000-0000-c000-000000000000",
  "oid": "05c93456-2f02-4601-afb0-d4599b7e6826",
  "sub": "05c93456-2f02-4601-afb0-d4599b7e6826",
  "tfp": "B2C_1_signinsignup",
  "nonce": "defaultNonce",
  "scp": "Directory.AccessAsUser.All User.Read",
  "azp": "{my app ID}",
  "ver": "1.0",
  "iat": 1576638555
}.[Signature]

1 个答案:

答案 0 :(得分:2)

B2C不支持对Graph API的委派访问。 您必须向应用程序注册添加应用程序权限, 并使用客户端凭据身份验证来获取令牌。

查看文档:{​​{3}}

  

在“应用程序权限”下,选择“读取和写入目录数据”。

从基础Azure AD的令牌终结点而不是B2C策略终结点获取令牌。

由于令牌将不包含用户信息,因此您将无法使用/me。 但是您可以改用/users/id

使用401的原因可能是您令牌中的发行者。 Graph API需要正常的AAD发行者,而不是它。