asp.net-core - 使用 .netcore 应用程序的基本身份验证
问题描述
我正在使用外部 api 与需要 Basic Authentication 的通信username and password
。我开发了一个与 .netcore 中的外部 api 通信的中间件,询问username and password
发送响应的问题。但是我想开发一个程序来访问外部 apiusername and password
并且不询问用户。我尝试了以下代码来做到这一点。但仍然没有成功,作为一个新的 .netcore 开发人员。
应用设置.json
{
"BasicAuth": {
"UserName": "user",
"Password": "abcDef123"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
启动.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/");
}
BasicAuth中间件
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.UseMiddleware<>();
在app.useMvcWithDefaultRoute();
ie之后使用
启动.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvcWithDefaultRoute();
//Using Middleware
app.UseMiddleware<BasicAuthMiddleware>("http://xx.xx.xx.xxx:8000/slr/n/query/");
}
它适用于一切..
推荐阅读
- ubuntu - 如何在编译 Minotaur 时找出 cmake 错误?
- ios - 仅在 Safari 浏览器中打开 url 而不是默认浏览器
- linear-regression - 标称属性“标签编码为 1、2、3”我可以直接用于没有假人的随机森林算法
- javascript - 将 *.gql 文件中的 2 个查询合并为 1 个查询
- node.js - 使用移动应用程序或二维码进行用户认证/授权
- reactjs - 向 React JS 项目添加动态状态
- mysql - 如何在 MySQL 数据库中获取每日数据
- firebase - ':firebase_core:compileDebugJavaWithJavac'
- android - 如何使用改造发送带有多部分文件的请求参数?
- menu - Typo3 - 将类添加到打字稿 hmenu 中的禁用页面