ADAL - AcquireTokenSilentAsync失败(Azure的Active Directory验证库) [英] ADAL - AcquireTokenSilentAsync fails (Azure Active Directory Authentication Libraries)

查看:1009
本文介绍了ADAL - AcquireTokenSilentAsync失败(Azure的Active Directory验证库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写通过REST API的新应用程序访问办公室数据,所以我想用新的
验证模型(V2.0端点)

I write a new application to access office data through the rest API, therefore i would like to use the new Authentication Model (V2.0 Endpoint)

<一个href=\"https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-compare/#scopes-not-resources\"相对=nofollow>什么是关于不同的V2.0 endpoit

我可以得到一个令牌将呼叫

I can get a token with a call to

private static string[] scopes = { "https://outlook.office.com/mail.read", "https://outlook.office.com/calendars.read" };
    public async Task<ActionResult> SignIn()
    {
     ... SNIP
      Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, clientId, redirectUri, new UserIdentifier("contoso@foo", UserIdentifierType.RequiredDisplayableId), null);        
      return Redirect(authUri.ToString());
    }
authContext.AcquireTokenByAuthorizationCodeAsync(authCode, redirectUri, credential, scopes)

问题是第二个电话

The Problem is the second call to

    public async Task<ActionResult> SignIn()
    {
     ... SNIP
     var authResult = authContext.AcquireTokenSilentAsync(scopes, clientId, new UserIdentifier("contoso@foo.ch", UserIdentifierType.RequiredDisplayableId))
    }

返回的标记确实包含的唯一ID,但这个信息不存储在令牌对象。令牌的的UserInfo总是空。由于此字段为空,该令牌缓存找不到令牌。

The Returned token does contain the UniqueId, but this information is not stored in the Token object. The UserInfo of the Token is always null. Because this field is null, the Token cache cannot find the token.

感谢您的提示和想法

在这里输入的形象描述

返回的标记

   {  
   "aud":"https://outlook.office.com",
   "iss":"https://sts.windows.net/f2ac6f3f-3df0-4068-a677-e4dfdf924b2/",
   "iat":146   dfdf21,
   "nbf":146   dfdf4621,
   "exp":1463   dfdf38521,
   "acr":"1",
   "amr":[  
      "pwd"
   ],
   "appid":"b13dfdf9-0561-4dfdff5-945c-778dfdf0de5cd",
   "appidacr":"1",
   "family_name":"Pan",
   "given_name":"Peter",
   "ipaddr":"12.12.12.17",
   "name":"Peter Pan",
   "oid":"4b83dfdfdb-f6db-433e-b70a-2f9a6dbbeb48",
   "puid":"100dfdfdfF5FBC",
   "scp":"Calendars.Read Mail.Read Mail.ReadWrite",
   "sub":"Z-chdfdsfnWqduUkCGZpsIdp-fdhpMMqqtwcHGs",
   "tid":"f2ac6f3f-3560-4068-a677-e4bfe0c924b2",
   "unique_name":"foo@contoso",
   "upn":"foo@contoso",
   "ver":"1.0"
}

类似的问题:
<一href=\"http://stackoverflow.com/questions/34849612/how-to-set-the-userinfo-of-a-adal-token\">Here

推荐答案

微软已经删除了profile_info,你可以在这里阅读:
<一href=\"https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-$p$pview-oidc-changes/\"相对=nofollow>重要更新ADV2

Microsoft has removed the profile_info as you can read here: Important Updates to ADV2

目前,图书馆有一个错误,因为它仍然检查它,如果它为空,也不会返回userinformations。

At the moment the library has a bug, because it still check it, and if it's null, it won't return the userinformations.

正确的信息在token_id ...

The correct informations are in token_id...

类别:TokenResponse

private AuthenticationResultEx GetResult(string token, string scope, long expiresIn)
{
  DateTimeOffset expiresOn = (DateTimeOffset) (DateTime.UtcNow + TimeSpan.FromSeconds((double) expiresIn));
  AuthenticationResult authenticationResult = new AuthenticationResult(this.TokenType, token, expiresOn);
  ProfileInfo profileInfo = ProfileInfo.Parse(this.ProfileInfoString);
  if (profileInfo != null)
  {
    string tenantId = profileInfo.TenantId;
    string str1 = (string) null;
    string str2 = (string) null;
    if (!string.IsNullOrWhiteSpace(profileInfo.Subject))
      str1 = profileInfo.Subject;
    if (!string.IsNullOrWhiteSpace(profileInfo.PreferredUsername))
      str2 = profileInfo.PreferredUsername;
    authenticationResult.UpdateTenantAndUserInfo(tenantId, this.ProfileInfoString, new UserInfo()
    {
      UniqueId = str1,
      DisplayableId = str2,
      Name = profileInfo.Name,
      Version = profileInfo.Version
    });
  }
  return new AuthenticationResultEx()
  {
    Result = authenticationResult,
    RefreshToken = this.RefreshToken,
    ScopeInResponse = AdalStringHelper.CreateArrayFromSingleString(scope)
  };
}

我希望他们尽快修复它,我还等着: - )

I hope they will fix it soon, I'm also waiting :-)

编辑:

我发现了一些有趣的东西在这里:
开发展望上手

I found something interesting here: Dev Outlook get started

正如我已经说过,存储在token_id所有信息,在上面的链接,你可以阅读:

As I already said, all informations stored in token_id, in the link above you can read:

ADAL V4的$ P $租赁前版本不令牌直接返回的ID,但它是可访问的。这里包括该方法旨在解决这个问题,直到ADAL被更新。

The prerelease version of ADAL v4 doesn't return the ID token directly, but it is accessible. The method included here is intended to work around this issue until ADAL is updated.

他们解释的方式来访问令牌:

They explain a way to access the Token:

  private string GetUserEmail(AuthenticationContext context, string clientId)
{
    // ADAL caches the ID token in its token cache by the client ID
    foreach (TokenCacheItem item in context.TokenCache.ReadItems())
    {
        if (item.Scope.Contains(clientId))
        {
            return GetEmailFromIdToken(item.Token);
        }
    }
    return string.Empty;
}

    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;
}

我没有测试过,但是我会更新这个帖子的时候我已经测试过它,或者其他人会请一个评论,如果他的速度更快: - )

这篇关于ADAL - AcquireTokenSilentAsync失败(Azure的Active Directory验证库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆