Microsoft Graph SDK - Login

2019-02-19 18:10发布

问题:

Is it possible to only log in once using MS Graph? Currently whenever I call the graphServiceClient it will ask me to sign in or to choose the signed in user. Is there any way that the process of choosing the signed in user can be avoided? Thanks in advance.

Currently this is how I initialize the graphService.

    public static GraphServiceClient GetAuthenticatedClient()
    {
        GraphServiceClient graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    string appID = ConfigurationManager.AppSettings["ida:AppId"];

                    PublicClientApplication PublicClientApp = new PublicClientApplication(appID);
                    string[] _scopes = new string[] { "Calendars.read", "Calendars.readwrite" };

                    AuthenticationResult authResult = null;
                    authResult = await PublicClientApp.AcquireTokenAsync(_scopes); //Opens Microsoft Login Screen    

                    // Append the access token to the request.
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                }));
        return graphClient;
    }

Now whenever I use the standard SDK functionality it will ask me to sign in:

await graphClient.Me.Events[testID].Request().UpdateAsync(x);

And then it will ask me again when I use another function:

await graphClient.Me.Events.Request().AddAsync(newEvent);

回答1:

Yes it is possible. AcquireTokenAsync does always trigger logon. Instead, you need to implement a token cache and use AcquireTokenSilentAsync. https://docs.microsoft.com/en-us/outlook/rest/dotnet-tutorial has a web app example.