This code was on this website https://www.microsoft.com/reallifecode/2017/01/10/creating-a-single-bot-service-to-support-multiple-bot-applications/#comment-148
I am new
Resume:
Create a class and inherit from ICredentialProvider class.
Then, add your Microsoft appId and password into a Dictionary.
Add your method to check if it is a valid app; also get password for your application.
Add custom authentication to your api/messages
controller.
First change your WebApiConfig
:
Should be :
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
Then, your custom authentication class, starting from YourNameSpace:
namespace YourNameSpace {
public class MultiCredentialProvider : ICredentialProvider
{
public Dictionary<string, string> Credentials = new Dictionary<string, string>
{
{ MicrosoftAppID1, MicrosoftAppPassword1},
{ MicrosoftAppID2, MicrosoftAppPassword2}
};
public Task<bool> IsValidAppIdAsync(string appId)
{
return Task.FromResult(this.Credentials.ContainsKey(appId));
}
public Task<string> GetAppPasswordAsync(string appId)
{
return Task.FromResult(this.Credentials.ContainsKey(appId) ? this.Credentials[appId] : null);
}
public Task<bool> IsAuthenticationDisabledAsync()
{
return Task.FromResult(!this.Credentials.Any());
}
}
After that, add your controller (api/messages) with your custom BotAuthentication
, plus your static constructor to update the container to use the right MicorosftAppCredentials
based on identity set by BotAuthentication:
[BotAuthentication(CredentialProviderType = typeof(MultiCredentialProvider))]
public class MessagesController : ApiController
{
static MessagesController()
{
var builder = new ContainerBuilder();
builder.Register(c => ((ClaimsIdentity)HttpContext.Current.User.Identity).GetCredentialsFromClaims())
.AsSelf()
.InstancePerLifetimeScope();
builder.Update(Conversation.Container);
}
You can handle now messages by :
[BotAuthentication(CredentialProviderType = typeof(MultiCredentialProvider))]
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
Activity reply = activity.CreateReply("it Works!");
await connector.Conversations.ReplyToActivityAsync(reply);
}
}
This code is tested and working for my bots.
Hope it helps :)