NServiceBus 4.4.0
嗨!
我使用消息mutators进行模拟。基本上,我在传出mutator中的JWT标记中序列化ClaimsPrincipal.Identity,并在传入的mutator中反序列化它以将其添加到NServiceBus主机应用程序的主体。 (基于这篇文章:http://beingabstract.com/2014/10/serializing-the-claimsidentity/)。问题是,当我们在传出的mutator(IMutateOutgoingTransportMessages)中时,ClaimsPrincipal.Identity不包含所有声明。只有名字。但是,如果我在“Bus.Send”命令之前查看,我有正确的声明(组,权限等)。
传出消息mutator驻留在外部类中,由我的主项目引用。这是来自传出的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服务可执行主机)中的传入消息mutator中,我反序列化它:
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内部和发送消息的服务中身份上下文不一样?