网关 API
,然后连接到服务。
![enter image description here](https://istack.dev59.com/60tiY.webp)
public class EntityRepository<T>
{
private IGateway _gateway = null;
public EntityRepository(IGateway gateway)
{
this._gateway = gateway;
}
public IEnumerable<T> FindAll()
{
return this._gateway.Get(typeof(T)).Content.ReadAsAsync<IEnumerable<T>>().Result;
}
public T FindById(int id)
{
return this._gateway.Get(typeof(T)).Content.ReadAsAsync<T>().Result;
}
public void Add(T obj)
{
this._gateway.Post(typeof(T), obj);
}
public void Update(T obj)
{
this._gateway.Post(typeof(T), obj);
}
public void Save(T obj)
{
this._gateway.Post(typeof(T), obj);
}
}
//Logic lives elsewhere
public HttpResponseMessage Get(Type type)
{
return Connect().GetAsync(Path(type)).Result;
}
public HttpResponseMessage Post(Type type, dynamic obj)
{
return Connect().PostAsync(Path(type), obj);
}
private string Path(Type type)
{
var className = type.Name;
return "api/service/" + Application.Key + "/" + className;
}
private HttpClient Connect()
{
var client = new HttpClient();
client.BaseAddress = new Uri("X");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
我使用泛型来确定当它到达网关时需要触发哪个服务。因此,如果Type
是Category,它将触发Category服务,从而调用:
public IEnumerable<dynamic> FindAll(string appKey, string cls)
{
var response = ConnectTo.Service(appKey, cls);
return (appKey == Application.Key) ? (response.IsSuccessStatusCode) ? response.Content.ReadAsAsync<IEnumerable<dynamic>>().Result : null : null;
}
网关不包含类型的物理文件/类。
在一些代码之后,我希望有人能给我一个小的演示或者最佳方法来处理当前架构下的安全性/用户认证。
情景1:用户访问Web应用并登录,此时用户的加密电子邮件和密码被发送到Gateway API
,然后传递到User Service
,并决定用户是否经过身份验证。现在,我想获取用户接收的所有消息,但不能在网关中说用户已经通过身份验证,因为这样做无法解决在Gateway API
之外调用Message Service
的问题。
我也不能为每个单独的服务添加身份验证,因为这将需要所有相关服务与User Service
通信,这违背了该模式的目的。
修复方法:只允许网关调用服务。禁止对网关之外的服务进行请求。
我知道安全是一个广泛的话题,但在当前情况下,我希望有人可以指导我采取最佳行动来解决这个问题。
目前,我已经在所有应用程序中硬编码了一个Guid
,这将在应用程序相等时获取数据。