in edge-hub/core/src/Microsoft.Azure.Devices.Edge.Hub.Mqtt/DeviceIdentityProvider.cs [42:115]
public async Task<IDeviceIdentity> GetAsync(string clientId, string username, string password, EndPoint clientAddress)
{
try
{
Preconditions.CheckNonWhiteSpace(username, nameof(username));
Preconditions.CheckNonWhiteSpace(clientId, nameof(clientId));
ClientInfo clientInfo = this.usernameParser.Parse(username);
clientInfo.ModelId.ForEach(async m => await this.metadataStore.SetModelId(clientInfo.DeviceId, m));
IClientCredentials deviceCredentials = null;
Option<IClientCredentials> actorCredentials = Option.None<IClientCredentials>();
if (!string.IsNullOrEmpty(password))
{
deviceCredentials = this.clientCredentialsFactory.GetWithSasToken(clientInfo.DeviceId, clientInfo.ModuleId, clientInfo.DeviceClientType, password, false, clientInfo.ModelId, clientInfo.AuthChain);
// For OnBehalfOf connections, we'll get the token for the actor EdgeHub instead
// of the actual leaf/module, so we need to construct the credentials accordingly
Option<string> actorDeviceIdOption = AuthChainHelpers.GetActorDeviceId(clientInfo.AuthChain);
actorCredentials = actorDeviceIdOption.Map(actorDeviceId =>
this.clientCredentialsFactory.GetWithSasToken(
actorDeviceId,
Microsoft.Azure.Devices.Edge.Hub.Core.Constants.EdgeHubModuleId,
clientInfo.DeviceClientType,
password,
false,
clientInfo.ModelId,
clientInfo.AuthChain));
}
else if (this.remoteCertificate.HasValue)
{
if (!this.clientCertAuthAllowed)
{
Events.CertAuthNotEnabled(clientInfo.DeviceId, clientInfo.ModuleId);
return UnauthenticatedDeviceIdentity.Instance;
}
this.remoteCertificate.ForEach(
cert =>
{
deviceCredentials = this.clientCredentialsFactory.GetWithX509Cert(
clientInfo.DeviceId,
clientInfo.ModuleId,
clientInfo.DeviceClientType,
cert,
this.remoteCertificateChain,
clientInfo.ModelId,
Option.None<string>());
});
}
else
{
Events.AuthNotFound(clientInfo.DeviceId, clientInfo.ModuleId);
return UnauthenticatedDeviceIdentity.Instance;
}
if (deviceCredentials == null
|| !clientId.Equals(deviceCredentials.Identity.Id, StringComparison.Ordinal)
|| !await this.authenticator.AuthenticateAsync(actorCredentials.GetOrElse(deviceCredentials)))
{
Events.Error(clientId, username);
return UnauthenticatedDeviceIdentity.Instance;
}
await this.metadataStore.SetMetadata(deviceCredentials.Identity.Id, clientInfo.DeviceClientType, clientInfo.ModelId);
Events.Success(clientId, username);
return new ProtocolGatewayIdentity(deviceCredentials, clientInfo.ModelId);
}
catch (Exception ex)
{
Events.ErrorCreatingIdentity(ex);
throw;
}
}