Skip to content
This repository was archived by the owner on Nov 16, 2023. It is now read-only.

Commit f9da712

Browse files
Dev/agera/msal (#67)
* working msal * updated test newtonsoft * refactored auth * added auth back in * Update README.md * Update README.md * removed whitespace * corrected auth.cs * removed method
1 parent 25b1b88 commit f9da712

File tree

7 files changed

+38
-30
lines changed

7 files changed

+38
-30
lines changed

occupancy-quickstart/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@ Below are some details on how to get up and running. For a more detailed walkth
1010

1111
### Update appSettings.json
1212

13-
`appSettings.json` is used to specify info on which Digital Twins instance to connect to. The three fields you will need to fill in are:
13+
[appSettings.json](./src/appSettings.json) is used to specify info on which Digital Twins instance to connect to. The three fields you will need to fill in are:
1414

1515
- `ClientId`: The **application ID** of a native Azure Active Directory app that has permissions to call the Azure Digital Twins service.
1616
- `Tenant`: The **directory ID** of a your Azure Active Directory.
1717
- `BaseUrl`: The management api url to your Digital Twins instance (see `appSetting.json` for what this should look like).
18+
- `AadRedirectUri`: A valid **Redirect URI** configured for your Azure Active Directory app. We recommend using the default **Redirect URI** `http://www.localhost:8080`. However, you may also choose another port or domain as required.
1819

1920
### Use a shell
2021

occupancy-quickstart/src/appSettings.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,17 @@ public class AppSettings {
1111
// Note: this is a constant because it is the same for every user authorizing
1212
// against the Digital Twins Apis
1313
private static string DigitalTwinsAppId = "0b07f429-9f4b-4714-9392-cc5e8e80c8b0";
14+
private static string[] AadScopes = new string[] { DigitalTwinsAppId + "/Read.Write" };
1415

1516
public string AADInstance { get; set; }
17+
public string AadRedirectUri { get; set; }
1618
public string ClientId { get; set; }
1719
public string ClientSecret { get; set; }
1820
public string Resource { get; set; } = DigitalTwinsAppId;
1921
public string Tenant { get; set; }
2022
public string BaseUrl { get; set; }
2123
public string Authority => AADInstance + Tenant;
24+
public string[] Scopes { get; set; } = AadScopes;
2225

2326
public static AppSettings Load()
2427
{
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
2-
"AADInstance": "https://login.microsoftonline.com/",
3-
"ClientId": "<Azure Active Directory App Id>",
4-
"Tenant": "<Directory Id of your AAD tenant>",
5-
"BaseUrl": "https://<your resource name>.<your resource's location>.azuresmartspaces.net/management/api/v1.0/"
2+
"AADInstance": "https://login.microsoftonline.com/",
3+
"AadRedirectUri": "http://localhost:8080/",
4+
"ClientId": "<Azure Active Directory App Id>",
5+
"Tenant": "<Directory Id of your AAD tenant>",
6+
"BaseUrl": "https://<your resource name>.<your resource's location>.azuresmartspaces.net/management/api/v1.0/"
67
}

occupancy-quickstart/src/auth.cs

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
using System;
55
using System.Threading.Tasks;
66
using Microsoft.Extensions.Logging;
7-
using Microsoft.IdentityModel.Clients.ActiveDirectory;
7+
using Microsoft.Identity.Client;
88
using System.Net.Http;
99

1010
namespace Microsoft.Azure.DigitalTwins.Samples
@@ -14,13 +14,13 @@ internal static class Authentication
1414
// Gets an access token
1515
// First tries (by making a request) using a cached token and if that
1616
// fails we generated a new one using device login and cache it.
17-
internal static async Task<string> GetToken(ILogger logger, AppSettings appSettings)
17+
internal static async Task<string> GetToken(AppSettings appSettings)
1818
{
1919
var accessTokenFilename = ".accesstoken";
2020
var accessToken = ReadAccessTokenFromFile(accessTokenFilename);
2121
if (accessToken == null || !(await TryRequestWithAccessToken(new Uri(appSettings.BaseUrl), accessToken)))
2222
{
23-
accessToken = await Authentication.GetNewToken(logger, appSettings);
23+
accessToken = await Authentication.GetNewToken(appSettings);
2424
System.IO.File.WriteAllText(accessTokenFilename, accessToken);
2525
}
2626

@@ -44,21 +44,24 @@ private static async Task<bool> TryRequestWithAccessToken(Uri baseAddress, strin
4444
private static string ReadAccessTokenFromFile(string filename)
4545
=> System.IO.File.Exists(filename) ? System.IO.File.ReadAllText(filename) : null;
4646

47-
private static async Task<string> GetNewToken(
48-
ILogger logger,
49-
AppSettings appSettings)
47+
// MSAL.NET configuration. Review the product documentation for more information about MSAL.NET authentication options.
48+
// https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/
49+
private static async Task<string> GetNewToken(AppSettings appSettings)
5050
{
51-
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(appSettings.Authority);
52-
return (await GetResultsUsingDeviceCode(authContext, appSettings)).AccessToken;
53-
}
51+
IPublicClientApplication app = PublicClientApplicationBuilder
52+
.Create(appSettings.ClientId)
53+
.WithRedirectUri(appSettings.AadRedirectUri)
54+
.WithAuthority(appSettings.Authority)
55+
.Build();
5456

55-
// This prompts the user to open a browser and input a unique key to authenticate their app
56-
// This allows dotnet core apps to authorize an application through user credentials without displaying UI.
57-
private static async Task<AuthenticationResult> GetResultsUsingDeviceCode(AuthenticationContext authContext, AppSettings appSettings)
58-
{
59-
var codeResult = await authContext.AcquireDeviceCodeAsync(appSettings.Resource, appSettings.ClientId);
60-
Console.WriteLine(codeResult.Message);
61-
return await authContext.AcquireTokenByDeviceCodeAsync(codeResult);
57+
AuthenticationResult result = await app
58+
.AcquireTokenInteractive(appSettings.Scopes)
59+
.ExecuteAsync();
60+
61+
Console.WriteLine("");
62+
Console.WriteLine("MSAL Authentication Token Acquired: {0}", result.AccessToken);
63+
Console.WriteLine("");
64+
return result.AccessToken;
6265
}
6366
}
64-
}
67+
}

occupancy-quickstart/src/occupancyQuickstart.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@
1111
<ItemGroup>
1212
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.1" />
1313
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.1.1" />
14-
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="3.19.3" allowedVersions="[3,4)" />
14+
<PackageReference Include="Microsoft.Identity.Client" Version="4.7.1.0" Culture="neutral" PublicKeyToken="0a613f4dd989e8ae" />
1515
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
1616
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
1717
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.1.1" />
18-
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
18+
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
1919
<PackageReference Include="YamlDotNet" Version="5.0.1" />
2020
<Content Include="appSettings.json">
2121
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>

occupancy-quickstart/src/program.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
using Newtonsoft.Json;
1515
using YamlDotNet.Serialization;
1616
using Microsoft.Extensions.Logging;
17-
using Microsoft.IdentityModel.Clients.ActiveDirectory;
17+
using Microsoft.Identity.Client;
1818

1919
namespace Microsoft.Azure.DigitalTwins.Samples
2020
{
@@ -85,10 +85,10 @@ private static async Task<HttpClient> SetupHttpClient(ILogger logger, AppSetting
8585
{
8686
BaseAddress = new Uri(appSettings.BaseUrl),
8787
};
88-
var accessToken = (await Authentication.GetToken(logger, appSettings));
89-
88+
89+
var accessToken = await Authentication.GetToken(appSettings);
9090
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
9191
return httpClient;
9292
}
9393
}
94-
}
94+
}

occupancy-quickstart/tests/occupancyQuickstart.tests.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.1" />
1010
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
1111
<PackageReference Include="Moq" Version="4.9.0" />
12-
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
12+
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
1313
<PackageReference Include="xunit" Version="2.2.0" />
1414
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
1515
<Content Include="userDefinedFunctions/function1.js">
@@ -24,4 +24,4 @@
2424
<ProjectReference Include="..\src\occupancyQuickstart.csproj" />
2525
</ItemGroup>
2626

27-
</Project>
27+
</Project>

0 commit comments

Comments
 (0)