Tom De Vree
Tom De Vree

Reputation: 57

Using MSAL with authentication context in C# WPF desktop app

We would like to use the authentication context feature of Azure AD (https://techcommunity.microsoft.com/t5/azure-active-directory-identity/conditional-access-authentication-context-now-in-public-preview/ba-p/1942484) in our desktop app to trigger conditional access when certain parts of our app are used.

The documentation provides samples of a web api and web app (https://github.com/Azure-Samples/ms-identity-dotnetcore-ca-auth-context-app/blob/main/README.md https://github.com/Azure-Samples/ms-identity-ca-auth-context/blob/main/README.md), but there is no documentation on how to secure parts of a desktop app with this feature.

In the desktop app (c# WPF 4.8) we use the MSAL library (4.35.1), also there we do not find any options / features to use the authentication context inside of the app.

Is it possible or the intention to be able to use authentication context inside a desktop app, or is it targeted at a web scenario?

Upvotes: 1

Views: 2196

Answers (1)

Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22495

You can implement authentication on any platforms. There are no platforms limitations.

Get Token:

For desktp application steps are almost same. You can get token this way:

             authResult = await app.AcquireTokenInteractive(scopes)
                        .WithAccount(firstAccount)
                        .WithParentActivityOrWindow(new WindowInteropHelper(this).Handle) // optional, used to center the browser on the window
                        .WithPrompt(Prompt.SelectAccount)
                        .ExecuteAsync();

Access Resource with Token:

var httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response;
            try
            {
                var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://graph.microsoft.com/v1.0/users");
                //Add the token in Authorization header
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                response = await httpClient.SendAsync(request);
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }

You can download the sample application from here in official docs

Let me know if you require any further assistance.

Upvotes: 1

Related Questions