如何使用登录用户的AccessToken实例化Microsoft GraphClient?

时间:2018-01-27 18:16:32

标签: c# asp.net-mvc azure-active-directory microsoft-graph adal

My Startup.Auth.cs如下所示:

public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    public static readonly string Authority = aadInstance + tenantId;

    // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
    string graphResourceId = "https://graph.microsoft.com";

    public void ConfigureAuth(IAppBuilder app)
    {
        ApplicationDbContext db = new ApplicationDbContext();

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                   AuthorizationCodeReceived = (context) => 
                   {
                       var code = context.Code;
                       ClientCredential credential = new ClientCredential(clientId, appKey);
                       string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                       TokenCache userTokenCache = new ADALTokenCache(signedInUserID);

                       AuthenticationContext authContext = new AuthenticationContext(Authority, userTokenCache);
                       AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                       code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                       string token = result.AccessToken;

                       return Task.FromResult(0);
                   }
                }
            });
    }
}

上面的倒数第二行代码(字符串变量“token”)正确包含当前登录用户的AccessToken。稍后,我的Web应用程序项目尝试实例化Microsoft GraphClient对象,如下所示:

GraphServiceClient graphClient = new GraphServiceClient(new AuthenticationController());

当调用上面的代码时,会创建一个新的AuthenticationController,如下所示:

public class AuthenticationController : IAuthenticationProvider
{
    private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
    private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {

        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

        // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
        ClientCredential creds = new ClientCredential(clientId, appKey);

        TokenCache tokenCache = new ADALTokenCache(signedInUserID);
        // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
        AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, tokenCache);
        AuthenticationResult authResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);

        request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
    }
}

我的问题是上面的AuthenticationController代码检索与Web应用程序关联的AccessToken,而不是当前登录的用户。我需要使用当前登录用户的AccessToken而不是Web应用程序来实例化GraphClient。具体来说,我希望最后一行代码中的变量authResult.AccessToken包含当前签名的AccessToken-在用户中。有什么方法可以安全地保存当前登录用户的令牌缓存在Startup.Auth.cs中,然后再将其检索到AuthenticationController类?

1 个答案:

答案 0 :(得分:2)

如果您已经拥有令牌,请致电告诉GraphServiceClient简单地使用该令牌,而不是尝试再次获取一个令牌。这是使用DelegateAuthenticationProvider类完成的:

var graphserviceClient = new GraphServiceClient(
    new DelegateAuthenticationProvider(
        (requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            return Task.FromResult(0);
        }));

存储该令牌的位置取决于应用程序的类型和您的体系结构。对于Web应用程序,您可以将其存储在会话或Cookie中,以用于内存中的本机应用程序。令牌是短暂的,因此任何临时商店通常都是可以接受的。