使用 .net 核心应用程序的基本身份验证

Basic Authentication using .netcore application

我正在使用外部 api 进行通信,需要基本身份验证 username and password。我开发了一个中间件,它与 .netcore 中的外部 api 通信,询问 username and password 以发送响应。但我想开发一个程序,用 username and password 访问外部 api 并且不询问用户。我尝试了以下代码来做到这一点。但是仍然没有成功,作为一个新的.netcore开发者。

appsettings.json

{
  "BasicAuth": {
    "UserName": "user",
    "Password": "abcDef123"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
}

startup.cs

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
            services.AddMvc(
                options =>
                {
                    options.Filters.Add<JsonExceptionFilter>();
                }
                )
                .AddJsonOptions(options => {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    //******** For Pagination *************
                    options.SerializerSettings.ContractResolver =
                            new CamelCasePropertyNamesContractResolver();
                    //******** End Pagination *************
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            //Adding HttpClient Service For Search Engine Apache Solr
            services.AddHttpClient("MyClient", client => {
                client.BaseAddress = new Uri("http://xx.xx.xx.xxx:8000/slr/n/query/");
                client.DefaultRequestHeaders.Add("username", "user");
                client.DefaultRequestHeaders.Add("password", "abcDef123");
            });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //Using Middleware
            app.UseMiddleware<BasicAuthMiddleware>("http://xx.xx.xx.xxx:8000/slr/n/query/");
}

BasicAuthMiddleware

 public class BasicAuthMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly string _realm;
        private readonly IConfiguration _configuration;

        public BasicAuthMiddleware(RequestDelegate next, string realm, IConfiguration configuration)
        {
            _next = next;
            _realm = realm;
            _configuration = configuration;
        }

        public async Task Invoke(HttpContext context)
        {
            string authHeader = context.Request.Headers["Authorization"];
            if (authHeader != null && authHeader.StartsWith("Basic "))
            {
                // Get the encoded username and password
                var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();
                // Decode from Base64 to string
                var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
                // Split username and password
                var username = decodedUsernamePassword.Split(':', 2)[0];
                var password = decodedUsernamePassword.Split(':', 2)[1];
                // Check if login is correct
                if (IsAuthorized(username, password))
                {
                    await _next.Invoke(context);
                    return;
                }
            }
            // Return authentication type (causes browser to show login dialog)
            context.Response.Headers["WWW-Authenticate"] = "Basic";
            // Add realm if it is not null
            if (!string.IsNullOrWhiteSpace(_realm))
            {
                context.Response.Headers["WWW-Authenticate"] += $" realm=\"{_realm}\"";
            }
            // Return unauthorized
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        }

        // Make your own implementation of this
        public bool IsAuthorized(string username, string password)
        {
            //IConfiguration config = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json", true, true)
            //    .Build();

            //IConfiguration config = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json")
            //    .Build();
            var basicAuthUserName = _configuration["BasicAuth:UserName"];
            var basicAuthPassword = _configuration["BasicAuth:Password"];
            // Check that username and password are correct
            return username.Equals(basicAuthUserName, StringComparison.InvariantCultureIgnoreCase)
                   && password.Equals(basicAuthPassword);
        }
    }

解决方案是在 app.useMvcWithDefaultRoute(); 之后使用 app.UseMiddleware<>();

startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvcWithDefaultRoute();
   //Using Middleware
            app.UseMiddleware<BasicAuthMiddleware>("http://xx.xx.xx.xxx:8000/slr/n/query/");
}

它适用于所有东西..