How to make a NuGet package for class library

by moondaddi on 07 Sep 2019


NuGet

https://www.nuget.org/packages/PasswordHasher.SHA256.ASP.NET.CORE.Identity/

Purpose

This is to show how to pack the external class library into NuGet package and publish it on NuGet.org.

Background

My team decided to build a new indentity api for auth and control roles of each client apis. We chose the IdentityServer4 on ASP.NET Core. But we had to migrate all users information including password which is stored in DB. IdentityServer4 has a default password hasher PBKDF2. Hence, we decided to override this password hasher with custom hasher which is SHA256 and BASE64 encoding. We built the custom password hasher as the external class library and published it to NuGet for later use and maintanence.

Requirements

  • macOS
  • dotnet CLI

Steps

  1. Install the dotnet CLI

https://dotnet.microsoft.com/download

  1. Create the class library
example$ dotnet new classlib -n SHA256.Password.Hasher

This makes a directory SHA256.Password.Hasher and create a template for class library

  1. Build the class library
using System;

namespace SHA256.Password.Hasher
{
    public class CustomPasswordHasher
    {
        // ...
    }
}

Rename the class or file (default filename : Class1.cs)

  1. Add the new class library into .sln file
example$ dotnet new sln

Generate the .sln file if not exists

example$ dotnet sln add SHA256.Password.Hasher/SHA256.Password.Hasher.csproj

Add the SHA256.Password.Hasher into .sln

  1. Add the reference into the main cs project to use the class library
example/IdentityServer4$ dotnet add reference ../SHA256.Password.Hasher/SHA256.Password.Hasher.csproj

example/IdentityServer4$ dotnet restore
  1. Build the class library
example/SHA256.Password.Hasher$ dotnet build
  1. Set the properties for NuGet package information
# SHA256.Password.Hasher.csproj
 
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <PackageId>PasswordHasher.SHA256.ASP.NET.CORE.Identity</PackageId>
    <Version>1.0.1</Version>
    <Authors>moondaddi</Authors>
    <RepositoryUrl>https://github.com/mattdamon108/PasswordHasher.SHA256.ASP.NET.CORE.Identity.git</RepositoryUrl>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0" />
  </ItemGroup>
 
</Project>
  1. Pack the class library to .nupkg file
example/SHA256.Password.Hasher$ dotnet pack

This generate a .nupkg file

  1. Create NuGet.org account and upload the .nupkg file

  2. References