Code Bug Fix: No certificate found if run as docker image, while certificate returns when running as IISExpress

Original Source Link

I have a asp.net core 3.1 web app where I am trying to get certificate which is available in current user personal store.

When I am running application with IISExpress, I am able to get the certificate,

 X509Store storex = null;
        try
        {
            storex = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            storex.Open(OpenFlags.ReadOnly);
            var certificates = storex.Certificates.Find(X509FindType.FindByThumbprint,
                "23f642c528f747241bb5bef8cd8ff21116dc5bff", true);

           X509Certificate certificatex = certificates[0];
        }

        catch (Exception e)
        {
            throw e;
        }

        finally
        {
            storex.Close();
        }

I have Dockerfile like this for this web application,

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["DockTest/DockTest.csproj", "DockTest/"]
RUN dotnet restore "DockTest/DockTest.csproj"
COPY . .
WORKDIR "/src/DockTest"
RUN dotnet build "DockTest.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "DockTest.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DockTest.dll"]	

Now When I am trying to run the application as Docker image, then I am NOT getting the certificate.

How to load certificate to the docker image?

I tried to add certificate like below in dockerfile, but it’s not working

 COPY C:/TEMP/Cert/mycert.pfx

please suggest.

Docker is an isolated environment, so it has no access to host machine resources, including certificate stores.
You may want to copy your certificate to Docker image, and load it with

var x509 = new X509Certificate2(File.ReadAllBytes(fileName));

Note however that it will become available to everyone who has access to the image you build.

Tagged : / /

Leave a Reply

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