会话日志记录结合AAD v1身份验证

时间:2018-05-16 00:35:37

标签: c# botframework

我在将我的AAD1身份验证和自定义对话记录器添加到我的ChatBot时遇到问题。一个或另一个工作正常,但结合这两个,我得到HTTP超时。任何帮助将不胜感激。相关代码如下:

Global.asax.cs

protected void Application_Start()
    {
        // Adding DocumentDB endpoint and primary key
        var docDbServiceEndpoint = new Uri("-----------------------------------");//REMOVED Uri for question, no issue with connection as is
        var docDbKey = "--------------------------------------------"; //REMOVED Key for question, no issue with connection as is

        Conversation.UpdateContainer(builder =>
        {
            builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));

            var store = new DocumentDbBotDataStore(docDbServiceEndpoint, docDbKey); // requires Microsoft.BotBuilder.Azure Nuget package                 

            builder.RegisterType<DebugActivityLogger>().AsImplementedInterfaces().InstancePerDependency();
        });
        //authorization stuff
        AuthSettings.Mode = ConfigurationManager.AppSettings["ActiveDirectory.Mode"];
        AuthSettings.EndpointUrl = ConfigurationManager.AppSettings["ActiveDirectory.endpointUrl"];
        AuthSettings.Tenant = ConfigurationManager.AppSettings["ActiveDirectory.Tenant"];
        AuthSettings.RedirectUrl = ConfigurationManager.AppSettings["ActiveDirectory.RedirectUrl"];
        AuthSettings.ClientId = ConfigurationManager.AppSettings["ActiveDirectory.ClientId"];
        AuthSettings.ClientSecret = ConfigurationManager.AppSettings["ActiveDirectory.ClientSecret"];

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

AuthenticationHelper.cs

[Serializable]
public class AuthenticationHelper : IDialog<string>
{
    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(ProcessMessageAsync);
    }

    public async Task ProcessMessageAsync(IDialogContext context, IAwaitable<IMessageActivity> item)
    {
        var message = await item;
        if (string.IsNullOrEmpty(await context.GetAccessToken("https://graph.microsoft.com/")))
        {
            //NO ACCESS TOKEN, GET IT
            await context.Forward(new AzureAuthDialog("https://graph.microsoft.com"), this.ProcessAuthResultAsync, message, System.Threading.CancellationToken.None);                
        }
        else
        {
            //have token                     
            await context.Forward(new LuisAskQuestionDialog(), this.QuitMessageReceivedAsync, message, System.Threading.CancellationToken.None);
        }
    }

    public async Task ProcessAuthResultAsync(IDialogContext context, IAwaitable<string> result)
    {            
        var message = await result;
        await context.PostAsync(message);

        context.Wait(ProcessMessageAsync);
    }

    protected async Task QuitMessageReceivedAsync(IDialogContext context, IAwaitable<object> item)
    {            
        var message = await item;
        //StartRecordingProcess();
        context.Done(message);
    }        
}

ChatBotLogging.cs

public class DebugActivityLogger : IActivityLogger
{
    private const string EndpointUrl = "------------------------------";
    private const string PrimaryKey = "------------------------------------";
    private DocumentClient client;

    // ADD THIS PART TO YOUR CODE        

    public async Task LogAsync(IActivity activity)
    {
        //Update this information
        //What this needs to have: ConversationID, From, To, Date, Message
        //Get all the texts information ready for upload;
        //Get connection to table
        //upload the inforamtion onto the table
        //disconnect from the table
        // Retrieve the storage account from the connection string.

        //This Task is called to intercept messages
        var fromid = activity.From.Id;
        var toId = activity.Recipient.Id;
        var chatMessage = activity.AsMessageActivity()?.Text;            
        var timeStamp = activity.Timestamp;
        var conversationId = activity.Conversation.Id;
        //timestamp converted to string.
        string strTimeStamp = timeStamp.ToString();

        try
        {
            this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
            await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "botdb" });
            await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("botdb"), new DocumentCollection { Id = "botcollection" });

            ChatLogEntity chatLog1 = new ChatLogEntity
            {
                TimeStamp = strTimeStamp,
                ConversationId = conversationId,
                FromID = fromid,
                ToID = toId,
                ChatMessage = chatMessage                    
            };

            await this.CreateChatDocumentIfNotExists("botdb", "botcollection", chatLog1);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);                
        }            

    }        
//entity class for demo purposes
    // ADD THIS PART TO YOUR CODE
    private async Task CreateChatDocumentIfNotExists(string databaseName, string collectionName, ChatLogEntity chatEntity)
    {
        try
        {
            await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, chatEntity.TimeStamp));

        }
        catch (DocumentClientException de)
        {
            if (de.StatusCode == HttpStatusCode.NotFound)
            {
                await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), chatEntity);                    
            }
            else
            {
                throw;
            }
        }
    }
    public class ChatLogEntity
    {            
        [JsonProperty(PropertyName = "timestamp")]
        public string TimeStamp { get; set; }
        public string ConversationId { get; set; }

        public string ToID { get; set; }
        public string FromID { get; set; }
        public string ChatMessage { get; set; }
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }        
}

1 个答案:

答案 0 :(得分:1)

GetAuthorizationGroups()包已停止使用。如评论中所述,您应该使用AuthBot进行AADv1身份验证。 BotAuth支持状态数据对话支持(因此您也不会获得已弃用的状态客户端警告)。