Skip to content

Commit 96c0b77

Browse files
Tiago Brenckjmprieur
authored andcommitted
Phase 1.5 (B2C) in the tutorial (#116)
* Added B2C basic login functionality * - Added comments - Updated README - Added StartupB2CHelpers on library project * Fixed README * Addressing PR suggestion * Minor edits and fixes * Added a few missing items * IOptions configuration missing * Removed custom AuthController and manual B2C Auth setup. * Updated README
1 parent cbbb92d commit 96c0b77

File tree

13 files changed

+250
-46
lines changed

13 files changed

+250
-46
lines changed

1-WebApp-OIDC/1-5-B2C/Controllers/HomeController.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ namespace WebApp_OpenIDConnect_DotNet.Controllers
77
{
88
public class HomeController : Controller
99
{
10-
public HomeController()
10+
public IActionResult Index()
1111
{
12+
return View();
1213
}
1314

14-
public IActionResult Index()
15+
[Authorize]
16+
public IActionResult Claims()
1517
{
1618
return View();
1719
}

1-WebApp-OIDC/1-5-B2C/README.md

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
---
2+
services: active-directory
3+
platforms: dotnet
4+
author: TiagoBrenck
5+
level: 100
6+
client: ASP.NET Core Web App
7+
endpoint: AAD v2.0
8+
---
9+
# An ASP.NET Core Web app signing-in users with the Microsoft identity platform in Azure AD B2C
10+
11+
[![Build status](https://identitydivision.visualstudio.com/IDDP/_apis/build/status/AAD%20Samples/.NET%20client%20samples/ASP.NET%20Core%20Web%20App%20tutorial)](https://identitydivision.visualstudio.com/IDDP/_build/latest?definitionId=819)
12+
13+
## Scenario
14+
15+
This sample shows how to build a .NET Core 2.2 MVC Web app that uses OpenID Connect to sign in users in **Azure AD B2C**. It assumes you have some familiarity with **Azure AD B2C**. If you'd like to learn all that B2C has to offer, start with our documentation at https://aka.ms/aadb2c.
16+
17+
![Sign in with Azure AD](ReadmeFiles/sign-in.png)
18+
19+
## How to run this sample
20+
21+
To run this sample:
22+
23+
> Pre-requisites: Install .NET Core 2.2 or later (for example for Windows) by following the instructions at [.NET and C# - Get Started in 10 Minutes](https://www.microsoft.com/net/core). In addition to developing on Windows, you can develop on [Linux](https://www.microsoft.com/net/core#linuxredhat), [Mac](https://www.microsoft.com/net/core#macos), or [Docker](https://www.microsoft.com/net/core#dockercmd).
24+
25+
### Step 1: Clone or download this repository
26+
27+
From your shell or command line:
28+
29+
```powershell
30+
git clone https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2.git
31+
```
32+
33+
> Given that the name of the sample is very long, and so are the names of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.
34+
35+
Navigate to the `"1-5-B2C"` folder
36+
37+
```Sh
38+
cd "1-5-B2C"
39+
```
40+
41+
### Step 2: Get your own Azure AD B2C tenant
42+
43+
If you don't have an Azure AD B2C tenant yet, you'll need to create an Azure AD B2C tenant by following the [Tutorial: Create an Azure Active Directory B2C tenant](https://azure.microsoft.com/documentation/articles/active-directory-b2c-get-started).
44+
45+
### Step 3: Create your own user flow (policy)
46+
47+
This sample uses a unified sign-up/sign-in user flow (policy). Create this policy by following [these instructions on creating an AAD B2C tenant](https://azure.microsoft.com/documentation/articles/active-directory-b2c-reference-policies). You may choose to include as many or as few identity providers as you wish, but make sure **DisplayName** is checked in `User attributes` and `Application claims`.
48+
49+
If you already have an existing unified sign-up/sign-in user flow (policy) in your Azure AD B2C tenant, feel free to re-use it. The is no need to create a new one just for this sample.
50+
51+
Copy this policy name, so you can use it in step 5.
52+
53+
### Step 4: Create your own Web app
54+
55+
Now you need to [register your web app in your B2C tenant](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-app-registration#register-a-web-application), so that it has its own Application ID.
56+
57+
Your web application registration should include the following information:
58+
59+
- Enable the **Web App/Web API** setting for your application.
60+
- Set the **Reply URL** to `https://localhost:44321/signin/B2C_1_sign_up_in` and `https://localhost:44321/signout/B2C_1_sign_up_in`.
61+
- Copy the Application ID generated for your application, so you can use it in the next step.
62+
63+
### Step 5: Configure the sample with your app coordinates
64+
65+
1. Open the solution in Visual Studio.
66+
1. Open the `appsettings.json` file.
67+
1. Find the assignment for `Instance` and replace the value with your tenant name. For example, `https://fabrikam.b2clogin.com`
68+
1. Find the assignment for `Domain` and replace the value with your Azure AD B2C domain name. For example, `https://fabrikam.onmicrosoft.com`
69+
1. Find the assignment for `ClientID` and replace the value with the Application ID from Step 4.
70+
1. Find the assignment for `SignUpSignInPolicyId` and replace with the name of the `Sign up and sign in` policy you created in Step 3.
71+
72+
```json
73+
{
74+
"AzureAdB2C": {
75+
"Instance": "https://<your-tenant-name>.b2clogin.com",
76+
"ClientId": "<web-app-application-id>",
77+
"Domain": "<your-b2c-domain>",
78+
"CallbackPath": "/signin/B2C_1_sign_up_in",
79+
"SignedOutCallbackPath": "/signout/B2C_1_sign_up_in",
80+
"SignUpSignInPolicyId": "<your-sign-up-in-policy>"
81+
}
82+
}
83+
```
84+
85+
### Step 5: Run the sample
86+
87+
1. Build the solution and run it.
88+
1. Open your web browser and make a request to the app. Accept the IIS Express SSL certificate if needed. Click on **SignIn/Up** button.
89+
1. If you don't have an account registered on the **Azure AD B2C** used in this sample, follow the sign up process. Otherwise, input the email and password for your account and click on **Sign in**.
90+
91+
## Troubleshooting
92+
93+
### known issue on iOS 12
94+
95+
ASP.NET core applications create session cookies that represent the identity of the caller. Some Safari users using iOS 12 had issues which are described in [ASP.NET Core #4467](https://github.com/aspnet/AspNetCore/issues/4647) and the Web kit bugs database [Bug 188165 - iOS 12 Safari breaks ASP.NET Core 2.1 OIDC authentication](https://bugs.webkit.org/show_bug.cgi?id=188165).
96+
97+
If your web site needs to be accessed from users using iOS 12, you probably want to disable the SameSite protection, but also ensure that state changes are protected with CSRF anti-forgery mechanism. See the how to fix section of [Microsoft Security Advisory: iOS12 breaks social, WSFed and OIDC logins #4647](https://github.com/aspnet/AspNetCore/issues/4647)
98+
99+
> Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the [GitHub Issues](../../../../issues) page.
100+
101+
## About The code
102+
103+
The `AccountController.cs` used in this sample is part of the built-in .NET Core authentication controllers found in the NuGet package `Microsoft.AspNetCore.Authentication.AzureADB2C.UI`, and you can find its implementation [here](https://github.com/aspnet/AspNetCore/blob/master/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/Areas/AzureADB2C/Controllers/AccountController.cs). If you want to customize the **Sign-in**, **Sign-up** or **Sign-out** actions, you are encouraged to create your own controller.
104+
105+
This sample shows how to use the OpenID Connect ASP.NET Core middleware to sign in users from a single Azure AD B2C tenant. The middleware is initialized in the `Startup.cs` file by passing the default authentication scheme and `AzureADB2COptions.cs` options. The options are read from the `appsettings.json` file. The middleware takes care of:
106+
107+
- Requesting OpenID Connect sign-in using the policy from the `appsettings.json` file.
108+
- Processing OpenID Connect sign-in responses by validating the signature and issuer in an incoming JWT, extracting the user's claims, and putting the claims in `ClaimsPrincipal.Current`.
109+
- Integrating with the session cookie ASP.NET Core middleware to establish a session for the user.
110+
111+
You can trigger the middleware to send an OpenID Connect sign-in request by decorating a class or method with the `[Authorize]` attribute or by issuing a challenge (see the [AccountController.cs](https://github.com/aspnet/AspNetCore/blob/master/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/Areas/AzureADB2C/Controllers/AccountController.cs) file which is part of ASP.NET Core).
112+
113+
Here is the middleware example:
114+
115+
```csharp
116+
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
117+
.AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
118+
```
119+
120+
Important things to notice:
121+
122+
- The method `AddAzureADB2C` will configure the authentication based on the `AzureADB2COptions.cs` options. Feel free to bind more properties on ``AzureAdB2C`` section on ``appsettings.json`` if you need to set more options.
123+
- The urls you set for `CallbackPath` and `SignedOutCallbackPath` should be registered on the **Reply Urls** of your application, in [Azure Portal](https://portal.azure.com).
124+
125+
## Next steps
126+
127+
Learn how to:
128+
129+
- Enable your [Web App to call a Web API on behalf of the signed-in user](../../2-WebApp-graph-user)
130+
131+
## Learn more
132+
133+
To understand more about Azure AD B2C see:
134+
135+
- [Azure AD B2C documentation](https://docs.microsoft.com/en-us/azure/active-directory-b2c/)
136+
- [Azure AD B2C sign-in/sign-up user flow](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-policies)
137+
138+
To understand more about token validation, see:
139+
140+
- [Validating tokens](https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/wiki/ValidatingTokens)
141+
142+
To understand more about app registration, see:
143+
144+
- [Quickstart: Register an application with the Microsoft identity platform (Preview)](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app)
145+
- [Quickstart: Configure a client application to access web APIs (Preview)](https://docs.microsoft.com/azure/active-directory/develop/quickstart-configure-app-access-web-apis)

1-WebApp-OIDC/1-5-B2C/Startup.cs

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,33 @@
1-
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
2-
using Microsoft.AspNetCore.Authorization;
1+
/************************************************************************************************
2+
The MIT License (MIT)
3+
4+
Copyright (c) 2015 Microsoft Corporation
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
***********************************************************************************************/
24+
25+
using Microsoft.AspNetCore.Authentication;
26+
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
327
using Microsoft.AspNetCore.Builder;
428
using Microsoft.AspNetCore.Hosting;
529
using Microsoft.AspNetCore.Http;
630
using Microsoft.AspNetCore.Mvc;
7-
using Microsoft.AspNetCore.Mvc.Authorization;
831
using Microsoft.Extensions.Configuration;
932
using Microsoft.Extensions.DependencyInjection;
1033
using Microsoft.Identity.Web;
@@ -30,7 +53,15 @@ public void ConfigureServices(IServiceCollection services)
3053
options.MinimumSameSitePolicy = SameSiteMode.None;
3154
});
3255

56+
// Configuration to sign-in users with Azure AD B2C
57+
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
58+
.AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
59+
3360
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
61+
62+
//Configuring appsettings section AzureADB2C, into IOptions
63+
services.AddOptions();
64+
services.Configure<AzureADB2COptions>(Configuration.GetSection("AzureAdB2C"));
3465
}
3566

3667
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -61,4 +92,4 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
6192
});
6293
}
6394
}
64-
}
95+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
@using System.Security.Claims
2+
3+
@{
4+
ViewData["Title"] = "Claims";
5+
}
6+
<h2>@ViewData["Title"].</h2>
7+
8+
<table class="table-hover table-condensed table-striped">
9+
<tr>
10+
<th>Claim Type</th>
11+
<th>Claim Value</th>
12+
</tr>
13+
14+
@foreach (Claim claim in User.Claims)
15+
{
16+
<tr>
17+
<td>@claim.Type</td>
18+
<td>@claim.Value</td>
19+
</tr>
20+
}
21+
</table>

1-WebApp-OIDC/1-5-B2C/Views/Home/Index.cshtml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
}
44

55
<h1>
6-
ASP.NET Core web app signing-in users in your organization
6+
ASP.NET Core web app signing-in users to your Azure AD B2C tenant.
77
</h1>
88
<p>
9-
This sample shows how to build a .NET Core 2.2 MVC Web app that uses OpenID Connect to sign in users in your organization. It leverages the ASP.NET Core OpenID Connect middleware.
9+
This sample shows how to build a .NET Core MVC Web app that uses OpenID Connect to sign in users in an Azure AD B2C tenant. It leverages the ASP.NET Core OpenID Connect middleware.
1010
</p>
11-
<img src="https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/raw/master/1-WebApp-OIDC/1-1-MyOrg/ReadmeFiles/sign-in.png
11+
<img src="https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/raw/master/1-WebApp-OIDC/1-5-B2C/ReadmeFiles/sign-in.png
1212
"/>

1-WebApp-OIDC/1-5-B2C/Views/Home/Privacy.cshtml

Lines changed: 0 additions & 6 deletions
This file was deleted.

1-WebApp-OIDC/1-5-B2C/Views/Shared/_Layout.cshtml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,10 @@
2929
<a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">WebApp_OpenIDConnect_DotNet</a>
3030
</div>
3131
<div class="navbar-collapse collapse">
32-
<ul class="nav navbar-nav">
33-
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
34-
</ul>
32+
<ul class="nav navbar-nav">
33+
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
34+
<li><a asp-area="" asp-controller="Home" asp-action="Claims">Claims</a></li>
35+
</ul>
3536
<partial name="_LoginPartial" />
3637
</div>
3738
</div>
Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
@using System.Security.Principal
22
@if (User.Identity.IsAuthenticated)
33
{
4-
<ul class="nav navbar-nav navbar-right">
5-
<li class="navbar-text">Hello @User.Identity.Name!</li>
6-
<li><a asp-area="AzureAD" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
7-
</ul>
4+
<ul class="nav navbar-nav navbar-right">
5+
<li class="navbar-text">Hello @User.Identity.Name</li>
6+
<li class="navbar-btn">
7+
<form method="get" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignOut">
8+
<button type="submit" class="btn btn-primary">Sign Out</button>
9+
</form>
10+
</li>
11+
</ul>
812
}
913
else
1014
{
11-
<ul class="nav navbar-nav navbar-right">
12-
<li><a asp-area="AzureAD" asp-controller="Account" asp-action="SignIn">Sign in</a></li>
13-
</ul>
15+
<ul class="nav navbar-nav navbar-right">
16+
<li class="navbar-btn">
17+
<form method="get" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignIn">
18+
<button type="submit" class="btn btn-primary">Sign In/Up</button>
19+
</form>
20+
</li>
21+
</ul>
1422
}

1-WebApp-OIDC/1-5-B2C/WebApp-OpenIDConnect-DotNet.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919

2020
<ItemGroup>
2121
<PackageReference Include="Microsoft.AspNetCore.App" />
22-
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="2.2.0" />
22+
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureADB2C.UI" Version="2.2.0" />
23+
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
2324
</ItemGroup>
2425

2526
<ItemGroup>
Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
{
2-
"AzureAd": {
3-
"Instance": "https://login.microsoftonline.com/",
4-
"Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
5-
"TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
6-
"ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
7-
"CallbackPath": "/signin-oidc",
8-
"SignedOutCallbackPath ": "/signout-callback-oidc"
9-
},
10-
"Logging": {
11-
"LogLevel": {
12-
"Default": "Warning"
13-
}
14-
},
15-
"AllowedHosts": "*",
2+
"AzureAdB2C": {
3+
"Instance": "https://<your-tenant-name>.b2clogin.com",
4+
"ClientId": "<web-app-application-id>",
5+
"Domain": "<your-b2c-domain>",
6+
"CallbackPath": "/signin/B2C_1_sign_up_in",
7+
"SignedOutCallbackPath": "/signout/B2C_1_sign_up_in",
8+
"SignUpSignInPolicyId": "<your-sign-up-in-policy>"
9+
},
10+
"Logging": {
11+
"LogLevel": {
12+
"Default": "Warning"
13+
}
14+
},
15+
"AllowedHosts": "*"
1616
}

0 commit comments

Comments
 (0)