Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Phase 1.5 (B2C) in the tutorial #116

Merged
merged 9 commits into from
Jul 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions 1-WebApp-OIDC/1-5-B2C/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ namespace WebApp_OpenIDConnect_DotNet.Controllers
{
public class HomeController : Controller
{
public HomeController()
public IActionResult Index()
{
return View();
}

public IActionResult Index()
[Authorize]
public IActionResult Claims()
{
return View();
}
Expand Down
145 changes: 145 additions & 0 deletions 1-WebApp-OIDC/1-5-B2C/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
---
services: active-directory
platforms: dotnet
author: TiagoBrenck
level: 100
client: ASP.NET Core Web App
endpoint: AAD v2.0
---
# An ASP.NET Core Web app signing-in users with the Microsoft identity platform in Azure AD B2C

[![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)

## Scenario

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.

![Sign in with Azure AD](ReadmeFiles/sign-in.png)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sign-in.png [](start = 37, length = 11)

This needs updating, should show Azure AD B2C instead of Azure AD


## How to run this sample

To run this sample:

> 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).

### Step 1: Clone or download this repository

From your shell or command line:

```powershell
git clone https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2.git
```

> 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.

Navigate to the `"1-5-B2C"` folder

```Sh
cd "1-5-B2C"
```

### Step 2: Get your own Azure AD B2C tenant

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).

### Step 3: Create your own user flow (policy)

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`.

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.

Copy this policy name, so you can use it in step 5.

### Step 4: Create your own Web app

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.

Your web application registration should include the following information:

- Enable the **Web App/Web API** setting for your application.
- Set the **Reply URL** to `https://localhost:44321/signin/B2C_1_sign_up_in` and `https://localhost:44321/signout/B2C_1_sign_up_in`.
- Copy the Application ID generated for your application, so you can use it in the next step.

### Step 5: Configure the sample with your app coordinates

1. Open the solution in Visual Studio.
1. Open the `appsettings.json` file.
1. Find the assignment for `Instance` and replace the value with your tenant name. For example, `https://fabrikam.b2clogin.com`
1. Find the assignment for `Domain` and replace the value with your Azure AD B2C domain name. For example, `https://fabrikam.onmicrosoft.com`
1. Find the assignment for `ClientID` and replace the value with the Application ID from Step 4.
1. Find the assignment for `SignUpSignInPolicyId` and replace with the name of the `Sign up and sign in` policy you created in Step 3.

```json
{
"AzureAdB2C": {
"Instance": "https://<your-tenant-name>.b2clogin.com",
"ClientId": "<web-app-application-id>",
"Domain": "<your-b2c-domain>",
"CallbackPath": "/signin/B2C_1_sign_up_in",
"SignedOutCallbackPath": "/signout/B2C_1_sign_up_in",
"SignUpSignInPolicyId": "<your-sign-up-in-policy>"
}
}
```

### Step 5: Run the sample

1. Build the solution and run it.
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.
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**.

## Troubleshooting

### known issue on iOS 12

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).

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)

> 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.

## About The code

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.

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:

- Requesting OpenID Connect sign-in using the policy from the `appsettings.json` file.
- 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`.
- Integrating with the session cookie ASP.NET Core middleware to establish a session for the user.

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).

Here is the middleware example:

```csharp
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
.AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
```

Important things to notice:

- 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.
- 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).

## Next steps

Learn how to:

- Enable your [Web App to call a Web API on behalf of the signed-in user](../../2-WebApp-graph-user)

## Learn more

To understand more about Azure AD B2C see:

- [Azure AD B2C documentation](https://docs.microsoft.com/en-us/azure/active-directory-b2c/)
- [Azure AD B2C sign-in/sign-up user flow](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-policies)

To understand more about token validation, see:

- [Validating tokens](https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/wiki/ValidatingTokens)

To understand more about app registration, see:

- [Quickstart: Register an application with the Microsoft identity platform (Preview)](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app)
- [Quickstart: Configure a client application to access web APIs (Preview)](https://docs.microsoft.com/azure/active-directory/develop/quickstart-configure-app-access-web-apis)
39 changes: 35 additions & 4 deletions 1-WebApp-OIDC/1-5-B2C/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authorization;
/************************************************************************************************
The MIT License (MIT)

Copyright (c) 2015 Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***********************************************************************************************/

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
using Microsoft.AspNetCore.Builder;
TiagoBrenck marked this conversation as resolved.
Show resolved Hide resolved
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;
Expand All @@ -30,7 +53,15 @@ public void ConfigureServices(IServiceCollection services)
options.MinimumSameSitePolicy = SameSiteMode.None;
});

// Configuration to sign-in users with Azure AD B2C
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
.AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

//Configuring appsettings section AzureADB2C, into IOptions
services.AddOptions();
services.Configure<AzureADB2COptions>(Configuration.GetSection("AzureAdB2C"));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down Expand Up @@ -61,4 +92,4 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
});
}
}
}
}
21 changes: 21 additions & 0 deletions 1-WebApp-OIDC/1-5-B2C/Views/Home/Claims.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
@using System.Security.Claims

@{
ViewData["Title"] = "Claims";
}
<h2>@ViewData["Title"].</h2>

<table class="table-hover table-condensed table-striped">
<tr>
<th>Claim Type</th>
<th>Claim Value</th>
</tr>

@foreach (Claim claim in User.Claims)
{
<tr>
<td>@claim.Type</td>
<td>@claim.Value</td>
</tr>
}
</table>
6 changes: 3 additions & 3 deletions 1-WebApp-OIDC/1-5-B2C/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
}

<h1>
ASP.NET Core web app signing-in users in your organization
ASP.NET Core web app signing-in users to your Azure AD B2C tenant.
</h1>
<p>
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.
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.
</p>
<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
<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
"/>
6 changes: 0 additions & 6 deletions 1-WebApp-OIDC/1-5-B2C/Views/Home/Privacy.cshtml

This file was deleted.

7 changes: 4 additions & 3 deletions 1-WebApp-OIDC/1-5-B2C/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@
<a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">WebApp_OpenIDConnect_DotNet</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
</ul>
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Claims">Claims</a></li>
</ul>
<partial name="_LoginPartial" />
</div>
</div>
Expand Down
22 changes: 15 additions & 7 deletions 1-WebApp-OIDC/1-5-B2C/Views/Shared/_LoginPartial.cshtml
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
@using System.Security.Principal
@if (User.Identity.IsAuthenticated)
{
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">Hello @User.Identity.Name!</li>
<li><a asp-area="AzureAD" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">Hello @User.Identity.Name</li>
<li class="navbar-btn">
<form method="get" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignOut">
<button type="submit" class="btn btn-primary">Sign Out</button>
</form>
</li>
</ul>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="AzureAD" asp-controller="Account" asp-action="SignIn">Sign in</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="navbar-btn">
<form method="get" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignIn">
<button type="submit" class="btn btn-primary">Sign In/Up</button>
</form>
</li>
</ul>
}
3 changes: 2 additions & 1 deletion 1-WebApp-OIDC/1-5-B2C/WebApp-OpenIDConnect-DotNet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureADB2C.UI" Version="2.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
</ItemGroup>

<ItemGroup>
Expand Down
28 changes: 14 additions & 14 deletions 1-WebApp-OIDC/1-5-B2C/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
"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]",
"ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath ": "/signout-callback-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"AzureAdB2C": {
"Instance": "https://<your-tenant-name>.b2clogin.com",
"ClientId": "<web-app-application-id>",
"Domain": "<your-b2c-domain>",
"CallbackPath": "/signin/B2C_1_sign_up_in",
"SignedOutCallbackPath": "/signout/B2C_1_sign_up_in",
"SignUpSignInPolicyId": "<your-sign-up-in-policy>"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
1 change: 1 addition & 0 deletions Microsoft.Identity.Web/Microsoft.Identity.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureADB2C.UI" Version="2.2.0" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.0.0" />
</ItemGroup>
</Project>
6 changes: 3 additions & 3 deletions Microsoft.Identity.Web/StartupHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ public static class StartupHelpers
{
/// <summary>
/// Add authentication with Microsoft identity platform v2.0 (AAD v2.0).
/// This supposes that the configuration files have a section named "AzureAD"
/// This expects the configuration files will have a section named "AzureAD"
/// </summary>
/// <param name="services">Service collection to which to add authentication</param>
/// <param name="configuration">Configuration</param>
/// <param name="services">Service collection to which to add this authentication scheme</param>
/// <param name="configuration">The Configuration object</param>
/// <returns></returns>
public static IServiceCollection AddAzureAdV2Authentication(this IServiceCollection services, IConfiguration configuration)
{
Expand Down
6 changes: 3 additions & 3 deletions Microsoft.Identity.Web/WebApiStartupHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ public static class WebApiStartupHelpers
{
/// <summary>
/// Protects the Web API with Microsoft Identity Platform v2.0 (AAD v2.0)
/// This supposes that the configuration files have a section named "AzureAD"
/// This expects the configuration files will have a section named "AzureAD"
/// </summary>
/// <param name="services">Service collection to which to add authentication</param>
/// <param name="configuration">Configuration</param>
/// <param name="services">Service collection to which to add this authentication scheme</param>
/// <param name="configuration">The Configuration object</param>
/// <returns></returns>
public static IServiceCollection AddProtectWebApiWithMicrosoftIdentityPlatformV2(this IServiceCollection services, IConfiguration configuration)
{
Expand Down