我正在尝试从appsettings.json
文件中读取一些值以进行基本身份验证。在本地代码可以正常工作,但是我对在实时部署应用程序时如何做感到困惑。
我的appsettings.json
文件看起来像这样
appsettings.json
{
"BasicAuth": {
"UserName": "admin",
"Password": "1234567789"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
我用于中间件的代码如下:
startup.cs
public void ConfigureServices(IServiceCollection
{
services.AddHttpClient("MyClient", client => {
client.BaseAddress = new Uri("http://xx.xx.xx.xxx/1/#/nutch/query");
client.DefaultRequestHeaders.Add("username", "admin");
client.DefaultRequestHeaders.Add("password", "1234567789");
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<BasicAuthMiddleware>("http://xx.xx.xx.xxx/abc/#/1/query/");
}
我的中间件类如下
BasicAuthMiddleware.cs
如您所见,我必须将整个路径发送到appsettings.json
.AddJsonFile
文件中
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace searchEngineTesting.Controllers
{
public class BasicAuthMiddleware
{
private readonly RequestDelegate _next;
private readonly string _realm;
public BasicAuthMiddleware(RequestDelegate next, string realm)
{
_next = next;
_realm = realm;
}
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("C:/programfiles/path/to/appsettings.json")
.Build();
var basicAuthUserName = config["BasicAuth:UserName"];
var basicAuthPassword = config["BasicAuth:Password"];
// Check that username and password are correct
return username.Equals(basicAuthUserName, StringComparison.InvariantCultureIgnoreCase)
&& password.Equals(basicAuthPassword);
}
}
}
我仅通过给名称appsettings.json
而不是整个路径来尝试,但是它不起作用,并且发生异常,找不到appsettings.json文件。我该如何给它一个概括的路径,这样就不必一次又一次地更改它,而且我可以读取这些值。
答案 0 :(得分:0)
您可以在中间件构造函数中注入IConfiguration
。无需使用配置生成器。
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;
}