Skip to content

Commit

Permalink
Merge pull request #581 from shweaver-MSFT/shweaver/graph-updates-710
Browse files Browse the repository at this point in the history
Updated Graph docs for 7.1.0 release.
  • Loading branch information
michael-hawker authored Oct 28, 2021
2 parents f3243a5 + 3e6ef4b commit 58c55b6
Show file tree
Hide file tree
Showing 14 changed files with 417 additions and 190 deletions.
7 changes: 3 additions & 4 deletions docs/graph/authentication/ProviderManager.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ dev_langs:

The ProviderManager manages access to the globally configured [IProvider](./custom.md) instance and any state change events as users sign in and out.

> Available in the `CommunityToolkit.Authentication` package.
> [!IMPORTANT]
> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages).
Available in the `CommunityToolkit.Authentication` package.

## Properties

| Property | Type | Description |
| -- | -- | -- |
| ClientName | string | (*Static*) Gets the name of the toolkit client to identify self in Graph calls. |
| Instance | ProviderManager | (*Static*) Get or set the instance of the globally configured IProvider. |
| State | ProviderState | Gets the current authentication state of the provider. |

## Events
Expand Down
13 changes: 5 additions & 8 deletions docs/graph/authentication/custom.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
---
title: IProvider
title: Custom authentication providers
author: shweaver-MSFT
description: IProvider interface defines the basic functions of an authentication provider in the Graph toolkit.
keywords: uwp, wpf, netstandard, windows, community, toolkit, graph, login, authentication, provider, providers, identity
dev_langs:
- csharp
---

# Custom provider
# Custom authentication providers

If you have existing authentication code in your application, you can create a custom provider to enable authentication and access to Microsoft Graph for the toolkit's Graph based controls and helpers. To bring your own authentication provider logic, start by extending `IProvider`.

## IProvider

`IProvider` is the base interface for creating authentication providers that work with the various controls and helpers in the toolkit. Handle authenticaiton with one of our premade `IProvider` implementations or create your own.
`IProvider` is the base interface for creating authentication providers that work with the various controls and helpers in the toolkit. Handle authentication with one of our premade `IProvider` implementations or create your own.

> Available in the `CommunityToolkit.Authentication` package.
> [!IMPORTANT]
> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages).
Available in the `CommunityToolkit.Authentication` package.

```csharp
using CommunityToolkit.Authentication;
Expand Down Expand Up @@ -47,7 +44,7 @@ ProviderManager.Instance.GlobalProvider = customProvider;
| Method | Arguments | Returns | Description |
| -- | -- | -- | -- |
| AuthenticateRequestAsync | HttpRequestMessage | Task | Authenticate an outgoing request. |
| GetTokenAsync | bool silentOnly = false, string[] scopes = null | Task<string> | Retrieve a token for the authenticated user. |
| GetTokenAsync | bool silentOnly = false | Task<string> | Retrieve a token for the authenticated user. |
| SignInAsync | | Task | Sign in a user. |
| SignOutAsync | | Task | Sign out the current user. |
| TrySilentSignInAsync | | Task<bool> | Try signing in silently, without prompts. |
5 changes: 1 addition & 4 deletions docs/graph/authentication/msal.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ dev_langs:

The MsalProvider is an [IProvider](./custom.md) implementation built on the official Microsoft Authentication Library (MSAL). It is NetStandard 2.0 so it works in both UWP and WPF apps.

> Available in the `CommunityToolkit.Authentication.Msal` package.
> [!IMPORTANT]
> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages).
Available in the `CommunityToolkit.Authentication.Msal` package.

```csharp
using CommunityToolkit.Authentication;
Expand Down
103 changes: 46 additions & 57 deletions docs/graph/authentication/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@ dev_langs:

# Authentication Providers Overview

> [!IMPORTANT]
> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages).
Authentication is always the first step to working with Microsoft Graph. The toolkit providers enable your application to authenticate with Microsoft Identity and access Microsoft Graph in only few lines of code. Each provider handles user authentication and acquiring access tokens to call Microsoft Graph APIs, so that you don't have to write this code yourself.

You can use the providers on their own, without components, to quickly implement authentication for your app and make calls to Microsoft Graph via the Microsoft Graph .NET SDK.
Expand All @@ -22,9 +19,9 @@ The toolkit includes the following providers:

| Providers | Description |
| -- | -- |
| [Msal](./msal.md) | Uses MSAL for .NET to sign in users and acquire tokens to use with Microsoft Graph in a NetStandard 2.0 application. |
| [Windows](./windows.md) | Uses native WebAccountManager (WAM) APIs to sign in users and acquire tokens to use with Microsoft Graph in a UWP application. |
| [Custom](./custom.md)Custom | Create a custom provider to enable authentication and access to Microsoft Graph with your application's existing authentication code. |
| [Msal](./msal.md) | Uses MSAL for .NET to sign in users and acquire tokens to use with Microsoft Graph in NetStandard 2.0 applications. |
| [Windows](./windows.md) | Uses native WebAccountManager (WAM) APIs to sign in users and acquire tokens to use with Microsoft Graph in UWP applications. |
| [Custom](./custom.md) | Create a custom provider to enable authentication and access to Microsoft Graph with your application's existing authentication code. |

## Initializing the GlobalProvider

Expand Down Expand Up @@ -69,6 +66,8 @@ public enum ProviderState
}
```

## Respond to changes in the GlobalProvider state

In some scenarios, you will want to show certain functionality or perform an action only after a user has successfully signed in. You can access and check the provider state as shown in the following example:

```csharp
Expand All @@ -79,7 +78,7 @@ if (ProviderManager.Instance.GlobalProvider?.State === ProviderState.SignedIn) {
}
```

You can also use the `ProviderUpdated` and `ProviderStateChanged` events to get notified whenever provider is set or changes state.
Use the `ProviderUpdated` and `ProviderStateChanged` events to get notified whenever provider is set or changes state.

```csharp
using CommunityToolkit.Authentication;
Expand All @@ -98,6 +97,43 @@ void OnProviderStateChanged(object sender, ProviderUpdatedEventArgs args)
}
```

### ProviderStateTrigger

To respond to provider state changes from XAML, try out the `ProviderStateTrigger` state trigger.

Available in the `CommunityToolkit.Graph.Uwp` package.

```xml
<VisualStateManager.VisualStateGroups xmlns:uwp="using:CommunityToolkit.Graph.Uwp">
<VisualStateGroup>
<VisualState>
<VisualState.StateTriggers>
<uwp:ProviderStateTrigger State="SignedIn" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="ContentPivot.Visibility" Value="Visible" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>

<Pivot Name="ContentPivot" Visibility="Collapsed">
<!-- The pivot will only be visible when the global provider is in a signed in state, and otherwise collapsed. -->
</Pivot>
```

### FrameworkElement.IsVisibleWhen

The `FrameworkElement.IsVisibleWhen` attached property makes it easy to toggle visibility for any `FrameworkElement`.

Available in the `CommunityToolkit.Graph.Uwp` package.

```xml
<Pivot Name="ContentPivot" uwp:ElementExtensions.IsVisibleWhen="SignedIn">
<!-- The pivot will only be visible when the global provider is in a signed in state, and otherwise collapsed. -->
</Pivot>
```

## Getting an access token

Each provider exposes a function called `getTokenAsync` that can retrieve the current access token or retrieve a new access token for the provided scopes. The following example shows how to get a new access token or the currently signed in user:
Expand All @@ -113,14 +149,14 @@ string token = await provider.GetTokenAsync(silentOnly: false);

## Call Microsoft Graph APIs

Once authenticated, you can now make API calls to Microsoft Graph using the Graph SDK or without.
Once authenticated, you can now make API calls to Microsoft Graph using the Graph SDK or without. See the [Extensions](../helpers/extensions.md) page for an example of how to authenticate an outbound request directly.

### Use the Graph SDK

Access APIs using the Graph SDK through a preconfigured `GraphServiceClient` available through an extension method on `IProvider` called, `GetClient()`.
Access APIs using the Graph SDK through a preconfigured `GraphServiceClient` available through an extension method on `IProvider` called `GetClient()` and `GetBetaClient()`.
See [Microsoft Graph Extensions](../helpers/extensions.md) for more details.

This is the easiest way to get started because all of the Graph types are available and the `GraphServiceClient` offers a convenient way of building requests.
It's possible to authenticate and make all Graph requests manually, without the Graph SDK. This can reduce package size significantly. However, using the Graph SDK is certainly the easiest way to work with Graph in .NET because the `GraphServiceClient` offers a convenient way of building requests and includes all of the object types ready to use.

Available in the `CommunityToolkit.Graph` package.

Expand All @@ -133,50 +169,3 @@ GraphServiceClient graphClient = provider.GetClient();

var me = await graphClient.Me.Request().GetAsync();
```

### Handle Graph requests manually

Access APIs by managing requests to Microsoft Graph yourself. This is helpful for projects with existing systems for managing web requests, or for keeping package sizes minimal by excluding the Graph SDK.

To make Graph API calls manually, use the `IProvider.AuthenticateRequestAsync(HttpRequestMessage)` method to authenticate an outgoing request.

```csharp
using CommunityToolkit.Authentication;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

private async Task<IList<TodoTask>> GetDefaultTaskListAsync()
{
return await GetResponseAsync<List<TodoTask>>("https://graph.microsoft.com/v1.0/me/todo/lists/tasks/tasks");
}

private async Task<T> GetResponseAsync<T>(string requestUri)
{
// Build the request
HttpRequestMessage getRequest = new HttpRequestMessage(HttpMethod.Get, requestUri);

// Authenticate the request
await ProviderManager.Instance.GlobalProvider.AuthenticateRequestAsync(getRequest);

var httpClient = new HttpClient();
using (httpClient)
{
// Send the request
var response = await httpClient.SendAsync(getRequest);

if (response.IsSuccessStatusCode)
{
// Handle the request response
var jsonResponse = await response.Content.ReadAsStringAsync();
var jObject = JObject.Parse(jsonResponse);
if (jObject.ContainsKey("value"))
{
var result = JsonConvert.DeserializeObject<T>(jObject["value"].ToString());
return result;
}
}
}

return default;
}
```
30 changes: 13 additions & 17 deletions docs/graph/authentication/windows.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ dev_langs:
The WindowsProvider is an authentication provider for accessing locally configured accounts on Windows.
It extends [IProvider](./custom.md) and uses the native Windows AccountManager (WAM) APIs and AccountsSettingsPane for sign in.

> Available in the `CommunityToolkit.Authentication.Uwp` package.
> [!IMPORTANT]
> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages).
Available in the `CommunityToolkit.Authentication.Uwp` package.

## Prerequisite Windows Store Association in Visual Studio

Expand All @@ -30,27 +27,25 @@ To get valid tokens and complete sign in, the app will need to be associated wit
> [!NOTE]
> You must have a Windows Developer account to use the WindowsProvider in your UWP app. You can [register a Microsoft developer account](https://developer.microsoft.com/store/register) if you don't already have one.
<!-- Uncomment this when AAD account support becomes available.
## Prerequisite Configure Client Id in Partner Center

If your product integrates with Azure AD and calls APIs that request either application permissions or delegated permissions that require administrator consent, you will also need to enter your Azure AD Client ID in Partner Center:

https://partner.microsoft.com/en-us/dashboard/products/&lt;YOUR-APP-ID&gt;/administrator-consent
`https://partner.microsoft.com/dashboard/products/&lt;YOUR-APP-ID&gt;/administrator-consent`

This lets administrators who acquire the app for their organization grant consent for your product to act on behalf of all users in the tenant.

> [!NOTE]
> You only need to specify the client id if you need admin consent for delegated permissions from your AAD app registration. Simple authentication for public accounts does not require a client id or any additional configuration.
> You only need to specify the client id if you need admin consent for delegated permissions from your AAD app registration, or need to support more advanced authentication scenarios like SSO. Simple authentication for consumer MSA accounts does not require a client id or any additional configuration in Azure for basic access.
> [!IMPORTANT]
> Be sure to Register Client Id in Azure first following the guidance here: <https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app>
> Make sure to Register Client Id in Azure first following the guidance here: [Quickstart: Register an application with the Microsoft identity platform](/azure/active-directory/develop/quickstart-register-app)
>
> After finishing the initial registration page, you will also need to add an additional redirect URI. Click on "Add a Redirect URI" and add the value retrieved from running `WindowsProvider.RedirectUri`.
> After finishing the initial registration page, you will also need to add an additional redirect URI. Click on "Add a Redirect URI" and add the value retrieved from running `WindowsProvider.RedirectUri` at runtime.
>
> You'll also want to set the toggle to true for "Allow public client flows".
> You'll also want to set the toggle to **true** for "Allow public client flows".
>
> Then click "Save".
-->
## Syntax

Expand All @@ -64,9 +59,8 @@ using CommunityToolkit.Authentication;
ProviderManager.Instance.GlobalProvider = new WindowsProvider(new string[] { "User.Read", "Tasks.ReadWrite" });
```

The WindowsProvider can also be configured to disabled auto-signin or show custom content in the `AccountsSettingsPane`.
Additional configuration for account types will be available via the `WebAccountProviderConfig` object in the future.
Currently, only consumer MSA accounts are supported.
The WindowsProvider can also be configured to disable auto-login or show custom content in the `AccountsSettingsPane`.
Configuration for specifying supported account types (such as AAD) is available via the `WebAccountProviderConfig` object.

```CSharp
using CommunityToolkit.Authentication;
Expand All @@ -82,9 +76,11 @@ void OnSettingsCommandInvoked(IUICommand command)
System.Diagnostics.Debug.WriteLine("AccountsSettingsPane command invoked: " + command.Id);
}

// Configure which types accounts should be available to choose from. The default is MSA, but AAD will come in the future.
// ClientId is only required for approving admin level consent in AAD tenants.
var webAccountProviderConfig = new WebAccountProviderConfig(WebAccountProviderType.MSA, "YOUR_CLIENT_ID_HERE");
// Configure which types of accounts should be available to choose from. The default is MSA, but AAD is also supported.
var webAccountProviderConfig = new WebAccountProviderConfig(WebAccountProviderType.Msa);

// ClientId is only required for approving admin level consent in AAD tenants or for supporting advanced authentication scenarios like SSO.
//var webAccountProviderConfig = new WebAccountProviderConfig(WebAccountProviderType.Aad, "YOUR_CLIENT_ID_HERE");
// Configure details to present in the AccountsSettingsPane, such as custom header text and links.
var accountsSettingsPaneConfig = new AccountsSettingsPaneConfig(
Expand Down
Loading

0 comments on commit 58c55b6

Please sign in to comment.