将验证数据存储在MVC中

时间:2017-07-06 09:19:17

标签: asp.net-mvc adal

我创建了一个自定义Authorize属性,我在其中使用Office Graph获取当前用户所属的AAD组,并基于我拒绝或授权用户的那些组。我想保存组,因为对Office Graph的调用需要一些性能。保存这类数据的正确方法是什么?我可以看到有些人将它保存到SQL服务器,但是我需要确保清理等。

此外,我可以在某些线程中看到,由于并发性,会话状态被认为是一个糟糕的选择。所以问题是你有什么选择来存储这类信息?

欢迎所有建议。

1 个答案:

答案 0 :(得分:0)

如果您只使用group_id信息,则无需使用Office Graph并将其存储起来。我们可以通过更改Azure AD的清单来启用Azure AD发布组声明:(参考this code sample

"groupMembershipClaims": "All",

如果您还在使用有关群组的其他信息,则可以将这些信息存储到声明中。以下是一个代码示例,它将组的名称添加到声明中供您参考:

AuthorizationCodeReceived = async context =>
{
    ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
    string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
    AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
    AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
        context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);

    ActiveDirectoryClient graphClient = new ActiveDirectoryClient(new Uri(ConfigHelper.GraphServiceRoot),
  async () => { return await Task.FromResult(result.AccessToken); }
  );

    try
    {
        foreach (var groupClaim in context.AuthenticationTicket.Identity.FindAll("groups"))
        {

            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"https://graph.windows.net/adfei.onmicrosoft.com/groups/{groupClaim.Value}?api-version=1.6"),
                Method = HttpMethod.Get,
            };

            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);

            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage httpResponse = httpClient.SendAsync(request).Result;
                var retJSON = httpResponse.Content.ReadAsStringAsync().Result;

                var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(retJSON);
                ((ClaimsIdentity)context.AuthenticationTicket.Identity).AddClaim(new Claim("groupName", dict["displayName"].ToString()));
            }
        }

    }
    catch (Exception ex)
    {

    }
},

然后我们可以使用以下代码从控制器获取这些信息:

ClaimsPrincipal.Current.FindAll("groupName")