Skip to main content

Add Authentication to Angular 7 App using ASP.NET Core 3

.NET Core 3.0 Preview 3 was released last month, and it includes a bunch of new updates to ASP.NET Core. There are a couple of updates related to Angular. In this new update, the default Angular template is updated to Angular 7 and the option to add authentication while creating an Angular or React application. In this post, we’ll see how to create an Angular 7 app with Visual Studio 2019 and add authentication to Angular 7 App using ASP.NET Core 3.

Add Authentication to Angular 7 App using ASP.NET Core 3

Before we create the application, first we need to install Visual Studio 2019 and .NET Core 3.0.

Install .NET Core 3.0

To download .NET Core 3.0 preview 3, visit this link. Based on your platform, download the appropriate installer. This will not impact your existing .NET Core version installation.

Install Visual Studio 2019 Preview

To install Visual Studio 2019 preview, download the installer from this location. Don’t worry. Visual Studio and Visual Studio “Preview” can be installed side-by-side on the same device. It will have no impact on your current stable VS installation.

At the time of writing this post, you can’t set the Authentication while creating the angular based SPA application with Visual Studio 2019. The option to change the authentication is disabled.

Add Authentication to Angular 7 App using ASP.NET Core 3

However, using the .NET CLI you can create the project via the following command.

dotnet new angular --auth Individual

This command creates a new ASP.NET Core application with a hosted client Angular application. The application uses an Identity Server instance already configured so that your Angular application can authenticate users and send HTTP requests against the protected resources in the ASP.NET Core application.

Once the project is created successfully, you can run the application via the following command.

dotnet run

Open the application in the browser via the URL mentioned in the .NET CLI window and you should see the following. As you can see here, the Register and Login links are available. If you are familiar with the default Angular template, you might be knowing that the Fetch Data link fetches the list of weather from ASP.NET Core WEB API via Angular and displays them in a table structure. But with authentication enabled, you are required to login to get the list of weather.

Add Authentication to Angular 7 App using ASP.NET Core 3

Clicking on the Register will open the default Identity UI to register users. However, while registering the following error comes (see below GIF).

An unhandled exception occurred while processing the request.
MissingMethodException: Method not found: ‘Microsoft.EntityFrameworkCore.Metadata.Builders.IndexBuilder Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasIndex(System.Linq.Expressions.Expression`1>)’.

Add Authentication to Angular 7 App using ASP.NET Core 3

This is a known issue in preview 3 release and the fix will be available in preview 4 release. But for now, to fix this, let’s open the project in Visual Studio 2019. The project structure looks like this,

Angular 7 App with Authentication using ASP.NET Core 3 Solution Structure

This project uses Identity Server 4 which is the newest version of Identity Server, the popular OpenID Connect, and OAuth Framework for .NET, updated and redesigned for ASP.NET Core and .NET Core. Identity Server has an Entity Framework (EF) Core package that can be used to implement client, scope and persisted grant stores using any EF Core relational database provider.

The Identity Server Entity Framework Core package supports the In-Memory, SQLite (in-memory) and SQL Server database providers. The default implementation is using SQLite database. The app.db SQLite database file present in the root. You can open this file with any SQLite database browser or online to view the schema and the data.

Angular 7 App with Authentication using ASP.NET Core 3 Identity Db

The Startup.cs also confirms it.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<ApplicationUser>()
        .AddDefaultUI(UIFramework.Bootstrap4)
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

    services.AddAuthentication()
        .AddIdentityServerJwt();
    services.AddMvc()
        .AddNewtonsoftJson();

    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
}

The Angular Client App also has the required implementation of authentication. You can expand the ClientApp folder to see the components and their implementation.

Add Authentication to Angular 7 App using ASP.NET Core 3 Client App Solution Structure

Now, let’s fix the MissingMethodException: Method not found issue. To fix it, open the .csproj file and replace the following package references.

<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview3-19153-02" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0-preview3.19153.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-preview3.19153.1" />

With these references.

<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview-18579-0056" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0-preview.19080.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-preview.19080.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0-preview.19080.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview.19080.1" />

And also add the following snippet to your csproj file:

<PropertyGroup>
   <NoWarn>$(NoWarn);NU1605</NoWarn>
</PropertyGroup>

Once done, execute dotnet run command to start the application. This time you should be able to register yourself. After registering as a new user, you will get redirected back to the application where you can see that you are successfully authenticated.

Successfully Added Authentication to Angular 7 App using ASP.NET Core 3

If you want to learn all of Angular 7, I want to personally recommend ng-book as the single-best resource out there. You can get a copy here.

Summary

With the preview 3 release, the angular default template is updated to Angular 7. Though adding authentication to Angular apps not as smooth as it should be. There are some issues like the EF issue while registering and Visual Studio 2019 not supporting authentication while creating the project. I’m sure by preview 4 the experience will be even better.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *