我正在开发一个 ASP.Net Core Web 应用程序,我需要为另一个(外部)Web 服务创建一种身份验证代理".
I'm developing an ASP.Net Core web application where I need to create a kind of "authentication proxy" to another (external) web service.
我所说的身份验证代理的意思是,我将通过我的 Web 应用程序的特定路径接收请求,并且必须检查这些请求的标头以获取我之前发布的身份验证令牌,然后重定向所有向外部 Web API 发出具有相同请求字符串/内容的请求,我的应用将通过 HTTP Basic auth 对其进行身份验证.
What I mean by authentication proxy is that I will receive requests through a specific path of my web app and will have to check the headers of those requests for an authentication token that I'll have issued earlier, and then redirect all the requests with the same request string / content to an external web API which my app will authenticate with through HTTP Basic auth.
这是整个过程的伪代码
/extapi
并在 HTTP 标头中添加 auth-token/extapi
and adds the auth-token in the HTTP header这就是我现在所拥有的.它似乎工作正常,但我想知道这是否真的应该这样做,或者是否没有更优雅或更好的解决方案?从长远来看,该解决方案是否会为扩展应用程序带来问题?
Here's what I have for now. It seems to be working fine, but I'm wondering if it's really the way this should be done or if there isn't a more elegant or better solution to this? Could that solution create issues in the long run for scaling the application?
[HttpGet]
public async Task GetStatement()
{
//TODO check for token presence and reject if issue
var queryString = Request.QueryString;
var response = await _httpClient.GetAsync(queryString.Value);
var content = await response.Content.ReadAsStringAsync();
Response.StatusCode = (int)response.StatusCode;
Response.ContentType = response.Content.Headers.ContentType.ToString();
Response.ContentLength = response.Content.Headers.ContentLength;
await Response.WriteAsync(content);
}
[HttpPost]
public async Task PostStatement()
{
using (var streamContent = new StreamContent(Request.Body))
{
//TODO check for token presence and reject if issue
var response = await _httpClient.PostAsync(string.Empty, streamContent);
var content = await response.Content.ReadAsStringAsync();
Response.StatusCode = (int)response.StatusCode;
Response.ContentType = response.Content.Headers.ContentType?.ToString();
Response.ContentLength = response.Content.Headers.ContentLength;
await Response.WriteAsync(content);
}
}
_httpClient
是一个在其他地方实例化的 HttpClient
类,并且是一个单例,并且具有 http://someexternalapp 的
BaseAddress
.com/api/
_httpClient
being a HttpClient
class instantiated somewhere else and being a singleton and with a BaseAddress
of http://someexternalapp.com/api/
另外,是否有比手动创建更简单的令牌创建/令牌检查方法?
Also, is there a simpler approach for the token creation / token check than doing it manually?
我最终实现了一个受 a 启发的代理中间件Asp.Net 的 GitHub 中的项目.
I ended up implementing a proxy middleware inspired by a project in Asp.Net's GitHub.
它基本上实现了一个中间件,它读取收到的请求,从中创建一个副本并将其发送回配置的服务,从服务读取响应并将其发送回调用者.
It basically implements a middleware that reads the request received, creates a copy from it and sends it back to a configured service, reads the response from the service and sends it back to the caller.
这篇关于使用 Asp.net 核心创建另一个 Web api 的代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!