ASP.NET Core Web API Authentication

后端 未结 9 752
深忆病人
深忆病人 2020-12-04 04:58

I\'m struggling with how to set up authentication in my web service. The service is build with the ASP.NET Core web api.

All my clients (WPF applications) should us

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 05:24

    As rightly said by previous posts, one of way is to implement a custom basic authentication middleware. I found the best working code with explanation in this blog: Basic Auth with custom middleware

    I referred the same blog but had to do 2 adaptations:

    1. While adding the middleware in startup file -> Configure function, always add custom middleware before adding app.UseMvc().
    2. While reading the username, password from appsettings.json file, add static read only property in Startup file. Then read from appsettings.json. Finally, read the values from anywhere in the project. Example:

      public class Startup
      {
        public Startup(IConfiguration configuration)
        {
          Configuration = configuration;
        }
      
        public IConfiguration Configuration { get; }
        public static string UserNameFromAppSettings { get; private set; }
        public static string PasswordFromAppSettings { get; private set; }
      
        //set username and password from appsettings.json
        UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
        PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
      }
      

提交回复
热议问题