Skip to content

Commit f9599f4

Browse files
author
Kalyan Krishna
committed
and this is done ..
1 parent 0f7e06b commit f9599f4

File tree

5 files changed

+110
-91
lines changed

5 files changed

+110
-91
lines changed

4-WebApp-your-API/4-1-MyOrg/Client/Startup.cs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
using Microsoft.Identity.Web.UI;
1515
using Microsoft.IdentityModel.Logging;
1616
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
17+
using System.Linq;
18+
using System.Diagnostics;
1719

1820
namespace WebApp_OpenIDConnect_DotNet
1921
{
@@ -42,13 +44,16 @@ public void ConfigureServices(IServiceCollection services)
4244

4345
services.AddOptions();
4446

47+
// The following lines of code adds the ability to authenticate users of this web app.
48+
// Refer to https://github.com/AzureAD/microsoft-identity-web/wiki/web-apps to learn more
4549
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
4650
.EnableTokenAcquisitionToCallDownstreamApi(
4751
Configuration.GetSection("TodoList:TodoListScopes").Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries)
4852
)
4953
.AddInMemoryTokenCaches();
5054

51-
//This is how we configure certificates in startup - https://github.com/AzureAD/microsoft-identity-web/wiki/Certificates
55+
// This is how we configure certificates in startup - see README-use-certificate.md for more details on how to use this section
56+
// Also read more at - https://github.com/AzureAD/microsoft-identity-web/wiki/Certificates
5257
//services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
5358
// .AddMicrosoftIdentityWebApp(microsoftIdentityOptions =>
5459
// {
@@ -104,6 +109,23 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
104109

105110
app.UseRouting();
106111
app.UseAuthentication();
112+
113+
app.Use(async (context, next) => {
114+
if (context.User != null && context.User.Identity.IsAuthenticated)
115+
{
116+
// you can conduct any conditional processing for guest/homes user by inspecting the value of the 'acct' claim
117+
// Read more about the 'acct' claim at aka.ms/optionalclaims
118+
if (context.User.Claims.Any(x => x.Type == "acct"))
119+
{
120+
string claimvalue = context.User.Claims.FirstOrDefault(x => x.Type == "acct").Value;
121+
string userType = claimvalue == "0" ? "Member" : "Guest";
122+
Debug.WriteLine($"The type of the user account from this Azure AD tenant is-{userType}");
123+
}
124+
}
125+
await next();
126+
});
127+
128+
107129
app.UseAuthorization();
108130

109131
app.UseEndpoints(endpoints =>

4-WebApp-your-API/4-1-MyOrg/README.md

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -281,8 +281,6 @@ To provide a recommendation, visit the following [User Voice page](https://feedb
281281
<details>
282282
<summary>Expand the section</summary>
283283

284-
1. Consider adding [MSAL.NET Logging](https://docs.microsoft.com/azure/active-directory/develop/msal-logging-dotnet) to you project
285-
286284
1. In the `TodoListService` project, which represents the web api, first the package `Microsoft.Identity.Web`is added from NuGet.
287285

288286
1. Starting with the **Startup.cs** file :
@@ -301,7 +299,7 @@ To provide a recommendation, visit the following [User Voice page](https://feedb
301299

302300
* `AddMicrosoftIdentityWebApiAuthentication()` protects the Web API by [validating Access tokens](https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens) sent tho this API. Check out [Protected web API: Code configuration](https://docs.microsoft.com/azure/active-directory/develop/scenario-protected-web-api-app-configuration) which explains the inner workings of this method in more detail.
303301
304-
* There is a bit of code (commented) provided under this method that can be used to used do extended token validation and check for additional claims, such as:
302+
* There is a bit of code (commented) provided under this method that can be used to used do **extended token validation** and do checks based on additional claims, such as:
305303
* check if the client app's appid (azp) is in some sort of an allowed list via the 'azp' claim, in case you wanted to restrict the API to a list of client apps.
306304
* check if the caller's account is homed or guest via the 'acct' optional claim
307305
* check if the caller belongs to right roles or groups via the 'roles' or 'groups' claim, respectively
@@ -367,7 +365,7 @@ To provide a recommendation, visit the following [User Voice page](https://feedb
367365
* The method *IsAppOnlyToken()* is used by controller method to detect presence of an app only token, i.e a token that was issued to an app using the [Client credentials](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow) flow, i.e no users were signed-in by this client app.
368366
369367
```csharp
370-
private bool IsAppOnlyToken()
368+
private bool IsAppOnlyToken()
371369
{
372370
// Add in the optional 'idtyp' claim to check if the access token is coming from an application or user.
373371
//
@@ -376,17 +374,51 @@ To provide a recommendation, visit the following [User Voice page](https://feedb
376374
}
377375
```
378376

379-
### Initial scopes
377+
1. In the `TodoListClient` project, which represents the client app that signs-in a user and makes calls to the web api, first the package `Microsoft.Identity.Web`is added from NuGet.
380378

381-
Client [appsettings.json](../4-1-MyOrg/Client/appsettings.json) file contains `ToDoListScopes` key that is used in [startup.cs](../4-1-MyOrg/Client/Startup.cs#L46) to specify which initial scopes should be requested from Web API when refreshing the token:
379+
* The following lines in *Startup.cs* adds the ability to authenticate a user using Azure AD.
382380

383381
```csharp
384-
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
385-
.EnableTokenAcquisitionToCallDownstreamApi(Configuration.GetSection("TodoList:TodoListScopes")
386-
.Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries))
387-
.AddInMemoryTokenCaches();
382+
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
383+
.EnableTokenAcquisitionToCallDownstreamApi(
384+
Configuration.GetSection("TodoList:TodoListScopes").Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries)
385+
)
386+
.AddInMemoryTokenCaches();
387+
```
388+
389+
* Specifying Initial scopes (delegated permissions)
390+
391+
The ToDoListClient's *appsettings.json* file contains `ToDoListScopes` key that is used in *startup.cs* to specify which initial scopes (delegated permissions) should be requested for the Access Token when a user is being signed-in:
392+
393+
```csharp
394+
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
395+
.EnableTokenAcquisitionToCallDownstreamApi(Configuration.GetSection("TodoList:TodoListScopes")
396+
.Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries))
397+
.AddInMemoryTokenCaches();
388398
```
389399

400+
* Detecting *Guest* users of a tenant signing-in. This section of code in *Startup.cs* shows you how to detect if the user signing-in is a *member* or *guest*.
401+
402+
```CSharp
403+
app.Use(async (context, next) => {
404+
if (context.User != null && context.User.Identity.IsAuthenticated)
405+
{
406+
// you can conduct any conditional processing for guest/homes user by inspecting the value of the 'acct' claim
407+
// Read more about the 'acct' claim at aka.ms/optionalclaims
408+
if (context.User.Claims.Any(x => x.Type == "acct"))
409+
{
410+
string claimvalue = context.User.Claims.FirstOrDefault(x => x.Type == "acct").Value;
411+
string userType = claimvalue == "0" ? "Member" : "Guest";
412+
Debug.WriteLine($"The type of the user account from this Azure AD tenant is-{userType}");
413+
}
414+
}
415+
await next();
416+
});
417+
```
418+
419+
1. There is some commented code in *Startup.cs* that also shows how to user certificates and KeyVault in place, see [README-use-certificate](README-use-certificate.md) for more details on how to use code in this section.
420+
1. Also consider adding [MSAL.NET Logging](https://docs.microsoft.com/azure/active-directory/develop/msal-logging-dotnet) to you project
421+
390422
</details>
391423

392424
## How the code was created
@@ -508,7 +540,8 @@ services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
508540
```
509541

510542
</details>
511-
## How to deploy this sample to Azure
543+
544+
## How to deploy this sample to Azure
512545

513546
### Deploying web API to Azure App Services
514547

4-WebApp-your-API/4-1-MyOrg/ReadmeFiles/ReadmeAboutTheCode.md

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
<details>
44
<summary>Expand the section</summary>
55

6-
1. Consider adding [MSAL.NET Logging](https://docs.microsoft.com/azure/active-directory/develop/msal-logging-dotnet) to you project
7-
86
1. In the `TodoListService` project, which represents the web api, first the package `Microsoft.Identity.Web`is added from NuGet.
97

108
1. Starting with the **Startup.cs** file :
@@ -23,7 +21,7 @@
2321

2422
* `AddMicrosoftIdentityWebApiAuthentication()` protects the Web API by [validating Access tokens](https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens) sent tho this API. Check out [Protected web API: Code configuration](https://docs.microsoft.com/azure/active-directory/develop/scenario-protected-web-api-app-configuration) which explains the inner workings of this method in more detail.
2523
26-
* There is a bit of code (commented) provided under this method that can be used to used do extended token validation and check for additional claims, such as:
24+
* There is a bit of code (commented) provided under this method that can be used to used do **extended token validation** and do checks based on additional claims, such as:
2725
* check if the client app's appid (azp) is in some sort of an allowed list via the 'azp' claim, in case you wanted to restrict the API to a list of client apps.
2826
* check if the caller's account is homed or guest via the 'acct' optional claim
2927
* check if the caller belongs to right roles or groups via the 'roles' or 'groups' claim, respectively
@@ -89,7 +87,7 @@
8987
* The method *IsAppOnlyToken()* is used by controller method to detect presence of an app only token, i.e a token that was issued to an app using the [Client credentials](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow) flow, i.e no users were signed-in by this client app.
9088
9189
```csharp
92-
private bool IsAppOnlyToken()
90+
private bool IsAppOnlyToken()
9391
{
9492
// Add in the optional 'idtyp' claim to check if the access token is coming from an application or user.
9593
//
@@ -98,15 +96,49 @@
9896
}
9997
```
10098

101-
### Initial scopes
99+
1. In the `TodoListClient` project, which represents the client app that signs-in a user and makes calls to the web api, first the package `Microsoft.Identity.Web`is added from NuGet.
100+
101+
* The following lines in *Startup.cs* adds the ability to authenticate a user using Azure AD.
102+
103+
```csharp
104+
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
105+
.EnableTokenAcquisitionToCallDownstreamApi(
106+
Configuration.GetSection("TodoList:TodoListScopes").Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries)
107+
)
108+
.AddInMemoryTokenCaches();
109+
```
110+
111+
* Specifying Initial scopes (delegated permissions)
102112

103-
Client [appsettings.json](../4-1-MyOrg/Client/appsettings.json) file contains `ToDoListScopes` key that is used in [startup.cs](../4-1-MyOrg/Client/Startup.cs#L46) to specify which initial scopes should be requested from Web API when refreshing the token:
113+
The ToDoListClient's *appsettings.json* file contains `ToDoListScopes` key that is used in *startup.cs* to specify which initial scopes (delegated permissions) should be requested for the Access Token when a user is being signed-in:
104114

105115
```csharp
106-
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
107-
.EnableTokenAcquisitionToCallDownstreamApi(Configuration.GetSection("TodoList:TodoListScopes")
108-
.Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries))
109-
.AddInMemoryTokenCaches();
116+
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
117+
.EnableTokenAcquisitionToCallDownstreamApi(Configuration.GetSection("TodoList:TodoListScopes")
118+
.Get<string>().Split(" ", System.StringSplitOptions.RemoveEmptyEntries))
119+
.AddInMemoryTokenCaches();
110120
```
111121

122+
* Detecting *Guest* users of a tenant signing-in. This section of code in *Startup.cs* shows you how to detect if the user signing-in is a *member* or *guest*.
123+
124+
```CSharp
125+
app.Use(async (context, next) => {
126+
if (context.User != null && context.User.Identity.IsAuthenticated)
127+
{
128+
// you can conduct any conditional processing for guest/homes user by inspecting the value of the 'acct' claim
129+
// Read more about the 'acct' claim at aka.ms/optionalclaims
130+
if (context.User.Claims.Any(x => x.Type == "acct"))
131+
{
132+
string claimvalue = context.User.Claims.FirstOrDefault(x => x.Type == "acct").Value;
133+
string userType = claimvalue == "0" ? "Member" : "Guest";
134+
Debug.WriteLine($"The type of the user account from this Azure AD tenant is-{userType}");
135+
}
136+
}
137+
await next();
138+
});
139+
```
140+
141+
1. There is some commented code in *Startup.cs* that also shows how to user certificates and KeyVault in place, see [README-use-certificate](README-use-certificate.md) for more details on how to use code in this section.
142+
1. Also consider adding [MSAL.NET Logging](https://docs.microsoft.com/azure/active-directory/develop/msal-logging-dotnet) to you project
143+
112144
</details>

0 commit comments

Comments
 (0)