Home  Dotnet   Authenticat ...

Authentication with ASP.NET Core Identity - Example

Below is an example of how to implement authentication in .NET using ASP.NET Core Identity.

.NET Example: Authentication with ASP.NET Core Identity

ASP.NET Core Identity is a membership system that adds login functionality to your application. It can be used to authenticate users and manage their roles.

Steps to Implement Authentication with ASP.NET Core Identity

  1. Create a New ASP.NET Core Project:
dotnet new mvc -o MyAuthApp
cd MyAuthApp
  1. Add Identity to the Project:

Update the MyAuthApp.csproj file to include the necessary package:

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.0" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
</ItemGroup>
  1. Set Up the Data Context and Identity:

Update Startup.cs to configure Identity and the application DB context:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddControllersWithViews();
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}
  1. Create the Identity Models and Context:

Create a Models directory and add ApplicationDbContext.cs:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
  1. Update the appsettings.json:

Add your connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MyAuthApp;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
  1. Run the Migrations:
dotnet ef migrations add InitialCreate
dotnet ef database update
  1. Add Authentication Pages:

Use scaffolding to add authentication pages:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet aspnet-codegenerator identity -dc ApplicationDbContext
  1. Update the Layout and Routes:

Ensure that your _Layout.cshtml includes links for login and register:

<ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
</ul>
Published on: Jul 08, 2024, 09:25 AM  
 

Comments

Add your comment