在过去的几天里,我一直在玩微服务模式,一切进展顺利,但安全性似乎让我感到困惑.
所以如果我可以问一个问题:如何处理单个服务的用户身份验证?此刻,我将请求传递给Gateway API依次连接到服务的请求.
编辑问题请见下文
请记住,个别服务不应该彼此了解.这Gateway是聚合器.
目前的架构.
一个模拟请求的小代码:
前端 - 客户端应用程序
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;
}
Run Code Online (Sandbox Code Playgroud)
我使用泛型来确定它一旦点击网关就需要触发的位置.因此,如果Type是类别,它将触发类别服务,从而调用:
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;
}
Run Code Online (Sandbox Code Playgroud)
网关不包含类型的物理文件/类.
在一些代码之后,我希望有人可以给我一些演示或最好的方法来处理当前架构的安全/用户身份验证.
案例场景1
用户点击Web应用程序并登录,此时用户加密的电子邮件和密码将被发送到Gateway API然后传递给User Service并确定用户是否经过身份验证 - 一切都很好但现在我想要获取全部来自Message Service用户收到的消息.我不能在网关中真正说出用户是否经过身份验证,获取消息因为这并不能解决调用Message Service外部的问题Gateway API
我也无法为每个单独的服务添加身份验证,因为这需要所有相应的服务与之交谈User Service,这会破坏模式的目的.
修复: 仅允许网关调用服务.应阻止对网关外部服务的请求.
我知道安全是一个广泛的主题,但在目前的背景下,我希望有人可以指导我采取最佳行动来解决问题.
目前我已经Guid在所有应用程序中硬编码了一个,如果应用程序相同,它会依次获取数据.
编辑
这个答案是关于网关<->微服务通信的。当应用程序与网关对话时,用户当然应该得到正确的身份验证
结束编辑
首先,微服务不应该通过互联网访问。它们只能从网关(可以集群)访问。
其次,您确实需要能够识别当前用户。您可以通过将UserId作为 HTTP 标头传递来完成此操作。IPrincipal创建一个 WebApi 过滤器,该过滤器获取该标头并从中创建自定义。
最后,您需要某种方法来确保请求来自网关或另一个微服务。一种简单的方法是对令牌使用 HMAC 身份验证。
web.config将密钥存储在每个服务和网关的密钥中。然后只需在每个请求中发送一个令牌(您可以使用 WebApi 身份验证过滤器进行身份验证)
要生成哈希值,请使用HMACSHA256.NET 中的类:
private static string CreateToken(string message, string secret)
{
secret = secret ?? "";
var keyByte = Encoding.ASCII.GetBytes(secret);
var messageBytes = Encoding.ASCII.GetBytes(message);
using (var hasher = new HMACSHA256(keyByte))
{
var hashmessage = hasher.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
Run Code Online (Sandbox Code Playgroud)
所以在你的MicroServiceClient你会做这样的事情:
var hash = CreateToken(userId.ToString(), mySharedSecret);
var myHttpRequest = HttpRequest.Create("yourUrl");
myHttpRequest.AddHeader("UserId", userId);
myHttpRequest.AddHeader("UserIdToken", hash);
//send request..
Run Code Online (Sandbox Code Playgroud)
在微服务中,您创建一个过滤器,例如:
public class TokenAuthenticationFilterAttribute : Attribute, IAuthenticationFilter
{
protected string SharedSecret
{
get { return ConfigurationManager.AppSettings["SharedSecret"]; }
}
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
await Task.Run(() =>
{
var userId = context.Request.Headers.GetValues("UserId").FirstOrDefault();
if (userId == null)
{
context.ErrorResult = new StatusCodeResult(HttpStatusCode.Forbidden, context.Request);
return;
}
var userIdToken = context.Request.Headers.GetValues("UserIdToken").FirstOrDefault();
if (userIdToken == null)
{
context.ErrorResult = new StatusCodeResult(HttpStatusCode.Forbidden, context.Request);
return;
}
var token = CreateToken(userId, SharedSecret);
if (token != userIdToken)
{
context.ErrorResult = new StatusCodeResult(HttpStatusCode.Forbidden, context.Request);
return;
}
var principal = new GenericPrincipal(new GenericIdentity(userId, "CustomIdentification"),
new[] {"ServiceRole"});
context.Principal = principal;
});
}
public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
}
public bool AllowMultiple
{
get { return false; }
}
private static string CreateToken(string message, string secret)
{
secret = secret ?? "";
var keyByte = Encoding.ASCII.GetBytes(secret);
var messageBytes = Encoding.ASCII.GetBytes(message);
using (var hasher = new HMACSHA256(keyByte))
{
var hashmessage = hasher.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1724 次 |
| 最近记录: |