NServiceBus 4.4.0
你好 !
我将消息变异器用于模拟目的。基本上,我在传出的 mutator 中将 ClaimsPrincipal.Identity 序列化为 JWT 令牌,并在传入的 mutator 中对其进行反序列化,以将其添加到 NServiceBus 主机应用程序的主体中。(基于这篇文章:http ://beingabstract.com/2014/10/serializing-the-claimsidentity/ )。问题是当我们在传出的 mutator (IMutateOutgoingTransportMessages) 中时,ClaimsPrincipal.Identity 并不包含所有的声明。只有名字。但如果我正在查看“Bus.Send”命令之前,我有正确的声明(组、权限等)。
传出消息修改器位于一个外部类中,我的主项目引用了该类。这是传出 mutator 的代码:
public class OutgoingAccessMutator : IMutateOutgoingTransportMessages, INeedInitialization
{
public IBus Bus { get; set; }
public void Init()
{
Configure.Instance.Configurer.ConfigureComponent<OutgoingAccessMutator>(DependencyLifecycle.InstancePerCall);
}
public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
{
if (!transportMessage.Headers.ContainsKey(Common.Constants.Securite.AuthenticationTokenID))
{
transportMessage.Headers[Common.Constants.Securite.AuthenticationTokenID] =
TokenHelper.GenerateToken(ClaimsPrincipal.Current.IdentitePrincipale() as ClaimsIdentity);
}
}
}
GenerateToken 位于 mutator dll 的静态助手类中:
public static string GenerateToken(ClaimsIdentity identity)
{
var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();
var securityKey = System.Text.Encoding.Unicode.GetBytes(Common.Constants.Securite.NServiceBusMessageTokenSymetricKey);
var inMemorySymmetricSecurityKey = new InMemorySymmetricSecurityKey(securityKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = identity,
TokenIssuerName = Common.Constants.Securite.NServiceBusMessageTokenIssuer,
AppliesToAddress = Common.Constants.Securite.NServiceBusMessageTokenScope,
Lifetime = new Lifetime(now, now.AddMinutes(5)),
SigningCredentials = new SigningCredentials(inMemorySymmetricSecurityKey, Common.Constants.Securite.SignatureAlgorithm, Common.Constants.Securite.DigestAlgorithm)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
然后在位于另一个进程(Windows 服务可执行主机)中的传入消息变异器中,我对其进行反序列化:
public class IncomingAccessTokenMutator : IMutateIncomingTransportMessages, INeedInitialization
{
public IBus Bus { get; set; }
public void Init()
{
Configure.Instance.Configurer.ConfigureComponent<IncomingAccessTokenMutator>(DependencyLifecycle.InstancePerCall);
}
public void MutateIncoming(TransportMessage transportMessage)
{
if (transportMessage.Headers.ContainsKey(Common.Constants.Securite.AuthenticationTokenID))
{
try
{
var token = transportMessage.Headers[Common.Constants.Securite.AuthenticationTokenID];
var identity = TokenHelper.ReadToken(token);
if (identity != null)
{
identity.Label = Common.Constants.Securite.NomIdentitePrincipale;
ClaimsPrincipal.Current.AddIdentity(identity);
}
}
catch (Exception)
{
Bus.DoNotContinueDispatchingCurrentMessageToHandlers();
throw;
}
}
}
}
有谁知道为什么 mutator 和发送消息的服务中的身份上下文不一样?