Christian Schou
  • Casa
  • Blog
    • Programação
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutoriais
    • Nuvem
    • Automação residencial
      • Assistente Doméstico
        • Node-Red
    • Career
  • Serviços
  • Glossário
  • About
No Result
View All Result
Christian Schou
  • Casa
  • Blog
    • Programação
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutoriais
    • Nuvem
    • Automação residencial
      • Assistente Doméstico
        • Node-Red
    • Career
  • Serviços
  • Glossário
  • About
No Result
View All Result
Christian Schou
No Result
View All Result
Home Programação C#
user secrets

What are User Secrets and how to use them in ASP.NET Core

by cristã
domingo, maio 29, 2022
in C#
0

In one of my other posts, I talked about individual developer settings and how to work with environment variables in .NET Core projects. Environment variables are easy to use in scripts and can be made up fast. What if I tell you there is a better approach than the above, named User Secrets?

User secrets are placed inside a settings file quite similar to the one we know already named appsettings.json. By using user secrets you can achieve a structured way of handling settings and that’s what I’m going to show you more about in this article.

Tabela de conteúdos
  1. Configure User Secrets with secrets.json
  2. Configure user secrets using command line
    • List all keys and values in secrets.json
    • Set a new user secret
    • Remove a user secret
  3. Summary

A quick recap from the other article to understand user secrets. I have taken a copy of the appsettings.json I had from earlier for your reference:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "localhost": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  }
}

To override ConnectionStrings:localhost on individual machines, each developer would have to add a user secret using the same name.

Configure User Secrets with secrets.json

The easiest way to open up the secrets.json file is by right-clicking your project and selecting Manage User Secrets in the menu.

Manage User Secrets

This will create a new file named secrets.json for your project. You won’t see the file inside the solution explorer as it’s saved within your roaming data. The exact path for the file is: C:\Users\<username>\AppData\Roaming\Microsoft\UserSecrets\<id> where <username> of course would be your username. <id> is a randomly generated GUID that is used when connecting the file to the project you are working on.

This GUID is stored within your csproj file for your project to reference the right secrets.json file at runtime. The great thing about storing the secrets in your local data is that it’s not submitted to source control and shared with other developers.

If you take a look inside your csproj file, you can see that a bit of markup has been added for the secret:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>bba7929a-b6ac-4e55-9065-1d18d2ddf83c</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>

</Project>

If you are not using Visual Studio for your project, you can generate a random GUID yourself and add the <UserSecretsId> property manually to the csproj file.

In the appsettings.json file above we have the connection string inside the file. Let’s override that with our user secrets. The structure is quite similar to the one we have in appsettings.json.

{
  "ConnectionStrings": {
    "localhost": "Server=myServerAddress;Database=myDataBase;User Id=christian;Password=someRandomPassword;"
  }
}

If you want to simplify it a bit more, you can do the following. What way you choose is up to you, both will work:

{
  "ConnectionStrings:localhost": "Server=myServerAddress;Database=myDataBase;User Id=christian;Password=someRandomPassword;"
}

Personally, I use the second option the most as I don’t really have that many settings I would like to override. Also, I tend to use the command line with dotnet to modify the file and that would collapse our settings anyway.

Configure user secrets using command line

You probably already know about dotnet and how you can install new packages, create migrations and update your database using code first… well it can also be used to configure user secrets – awesome! Below are a few commands to help you:

List all keys and values in secrets.json

This command will show you a complete list of keys and their values from secrets.json inside your current project. If you get an error about MSBuild that could not be found, then specify what project it’s for. using --project.

dotnet user-secrets list

OR

dotnet user-secrets list --project .\<projectName>
list all user secrets with dotnet, user secrets
List all user secrets using dotnet

Set a new user secret

This command will set a new user secret in secrets.json for a new database I just made up.

dotnet user-secrets set "ConnectionStrings:ERP" "Server=myServerAddress;Database=myDataBase;User Id=erp;Password=someRandomERPPassword;"

OR

dotnet user-secrets set "ConnectionStrings:ERP" "Server=myServerAddress;Database=myDataBase;User Id=erp;Password=someRandomERPPassword;" --project .\<projectName>
set new user secret, user secrets
Set new user secret using dotnet

Remove a user secret

This command will (as you probably already guessed) remove a connection string from secrets.json. It can remove anything, but for this demo, it will be a connection string.

dotnet user-secrets remove "ConnectionStrings:localhost"

OR

dotnet user-secrets remove "ConnectionStrings:localhost" --project .\<projectName>
Remove user secrets from secrets.json with dotnet

Now that we know how to easily configure our user secrets for an application, then it’s time to use them. ASP.NET Core will automatically pick up the configuration of secrets.json. However, if you initialize your application manually, you would have to implement them manually in the builder configuration like below in Program.cs:

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    builder.Configuration.AddUserSecrets<Program>();
}

At line 6 above, we search the assembly that contains the type Program for an instance of Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute, which specifies a user secrets ID.

Please notice that I added this piece of code to only be running if the environment is running in development mode. You should only be using user secrets when developing and not when running in production mode.

Summary

User secrets are a great alternative to environment variables. The structure in secrets.json matches the one we already have in appsettings.json and is in my opinion a great tool to administrate secrets for each developer.

When using a popular IDE like Visual Studio there is already built-in support for JSON file formatting to help you write valid JSON the first time. A user secret is not really that secret even though the name implies it. Your “secret” settings are still located on your computer in clear text and could be read by anyone else with the right privileges on the computer.

I hope this short guide about user secrets has given you a more easy way to handle individual developer settings in a more secret way for your team. If you got any issues, questions, or suggestions, please let me know in the comments. Happy coding! 🙂

Tags: .NET 6.Net CoreASP.NET CoreCLIConfigurationSecretsSettingsUser Secrets
Previous Post

How to configure individual developer settings in .NET Core projects (.NET 6)

Next Post

What is Shared Responsibility when talking about Public Cloud?

cristã

cristã

Hello 👋 My name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Related Posts

watchdog
ASP.NET Core

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

by cristã
sábado, agosto 13, 2022
0

A reader recently asked me for a more modern way to view log files for requests and exceptions in a...

Read more
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

segunda-feira, julho 25, 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

sábado, julho 23, 2022
Dockerize ASP.NET Core

How to Compose an ASP.NET Core Web API (.NET 6) with an MS SQL Server 2022 on Linux in Docker

terça-feira, julho 19, 2022
pattern matching in switch

How to do pattern matching in switch statements – C# version >= 7.0

segunda-feira, julho 11, 2022
Next Post
shared responsibility

What is Shared Responsibility when talking about Public Cloud?

Deixe um comentário Cancelar resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Christian Schou

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website
Career

Top 6 things to add on your personal website to get hired for a tech job

by cristã
domingo, agosto 7, 2022
0

Back in the days before the internet was a thing like it is today, we used to have business cards...

Read more
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

sábado, agosto 13, 2022
get hired for a tech job

5 tips to help you get hired for a tech job

domingo, julho 31, 2022
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

segunda-feira, julho 25, 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

sábado, julho 23, 2022

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website

Top 6 things to add on your personal website to get hired for a tech job

domingo, agosto 7, 2022
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

sábado, agosto 13, 2022
get hired for a tech job

5 tips to help you get hired for a tech job

domingo, julho 31, 2022
  • pt_BRPortuguês do Brasil
    • da_DKDansk
    • en_USEnglish
    • de_DEDeutsch
    • hi_INहिन्दी
  • Contact
  • Política de privacidade
  • Termos de serviço

© 2022 Christian Schou - All rights reserved.

No Result
View All Result
  • Casa
  • Blog
    • Programação
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutoriais
    • Nuvem
    • Automação residencial
      • Assistente Doméstico
    • Career
  • Serviços
  • Glossário
  • About

© 2022 Christian Schou - All rights reserved.

Eu uso cookies no meu site para lhe dar a experiência mais relevante, lembrando suas preferências e visitas repetidas. Ao clicar em “Aceitar”, você concorda com o uso de TODOS os cookies.
Não vender minhas informações pessoais.
Configurações de cookiesACCEPT
Política de Privacidade e Cookies

Visão geral da privacidade

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Sempre ativado
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieDuraçãoDescrição
__gads1 year 24 daysThe __gads cookie, set by Google, is stored under DoubleClick domain and tracks the number of times users see an advert, measures the success of the campaign and calculates its revenue. This cookie can only be read from the domain they are set on and will not track any data while browsing through other sites.
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_0J2F6JVWSD2 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_84232734_11 minuteSet by Google to distinguish users.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
YouTube2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data. I embed YouTube videos in my articles/tutorials - you won't get the full experience of the articles if this is deactivated.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieDuraçãoDescrição
IDE1 year 24 daysGoogle DoubleClick IDE cookies are used to store information about how the user uses the website to present them with relevant ads and according to the user profile.
test_cookie15 minutesThe test_cookie is set by doubleclick.net and is used to determine if the user's browser supports cookies.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SALVAR E ACEITAR
Desenvolvido por CookieYes Logo