Я использую внешний API для связи, для которого требуется базовая аутентификация username and password
. Я разработал промежуточное программное обеспечение, которое связывается с внешним API в .netcore, запрашивая username and password
для отправки ответа. Но я хочу разработать программу, которая обращается к внешнему API с username and password
и не спрашивает пользователя об этом. Я попробовал следующий кусок кода, чтобы сделать это. Но все еще безуспешно, как новый разработчик .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);
}
}