Уреди

Делите путем


Tutorial: Add sign in to an application

In the previous tutorial, an ASP.NET Core project was created and configured for authentication. This tutorial will install the required packages and add code that implements authentication to the sign-in and sign-out experience.

In this tutorial:

  • Identify and install the NuGet packages that are needed for authentication
  • Implement authentication in the code
  • Add the sign in and sign out experiences

Prerequisites

Install identity packages

Identity related NuGet packages must be installed in the project for authentication of users to be enabled.

  1. In the top menu of Visual Studio, select Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
  2. With the Browse tab selected, search for and select Microsoft.Identity.Web.UI. Select the Project checkbox, and then select Install.
  3. Repeat this for Microsoft.Identity.Web.Diagnostics and Microsoft.Identity.Web.DownstreamApi.

Implement authentication and acquire tokens

  1. Open Program.cs and replace the entire file contents with the following snippet:

    // <ms_docref_import_types>
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.Identity.Web;
    using Microsoft.Identity.Web.UI;
    // </ms_docref_import_types>
    
    // <ms_docref_add_msal>
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    IEnumerable<string>? initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ');
    
    
    builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
            .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
            .AddInMemoryTokenCaches();
    // </ms_docref_add_msal>
    
    // <ms_docref_add_default_controller_for_sign-in-out>
    builder.Services.AddRazorPages().AddMvcOptions(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                          .RequireAuthenticatedUser()
                          .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        }).AddMicrosoftIdentityUI();
    // </ms_docref_add_default_controller_for_sign-in-out>
    
    // <ms_docref_enable_authz_capabilities>
    WebApplication app = builder.Build();
    
    app.UseAuthentication();
    app.UseAuthorization();
    // </ms_docref_enable_authz_capabilities>
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.MapRazorPages();
    app.MapControllers();
    
    app.Run();
    

Add the sign in and sign out experience

After installing the NuGet packages and adding necessary code for authentication, add the sign-in and sign-out experiences.

Create the _LoginPartial.cshtml file

  1. Expand Pages, right-click Shared, and then select Add > Razor page.
  2. Select Razor Page - Empty, and then select Add.
  3. Enter _LoginPartial.cshtml for the name, and then select Add.

Edit the _LoginPartial.cshtml file

  1. Open _LoginPartial.cshtml and add the following code for adding the sign in and sign out experience:

    @using System.Security.Principal
    
    <ul class="navbar-nav">
    @if (User.Identity?.IsAuthenticated == true)
    {
            <li class="nav-item">
                <span class="navbar-text text-dark">Hello @User.Identity?.Name!</span>
            </li>
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
            </li>
    }
    else
    {
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
            </li>
    }
    </ul>
    
  2. Open _Layout.cshtml and add a reference to _LoginPartial created in the previous step. This single line should be placed between </ul> and </div>:

        </ul>
        <partial name="_LoginPartial" />
    </div>
    

Next steps