。netcore应用程序的基本身份验证

问题描述 投票:0回答:1

我正在使用外部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);
        }
    }
asp.net-core .net-core asp.net-core-mvc basic-authentication
1个回答
0
投票

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

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/");
}

并且所有内容都可以正常使用。.

© www.soinside.com 2019 - 2024. All rights reserved.