protected async Task <string> GetAccessToken(IDialogContext context) { var provider = new MSALAuthProvider(); var authResult = await provider.GetAccessToken(authOptions, context); return(authResult == null ? string.Empty : authResult.AccessToken); }
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item) { var message = await item; Debug.WriteLine("am I here"); // Initialize AuthenticationOptions and forward to AuthDialog for token AuthenticationOptions options = new AuthenticationOptions() { Authority = ConfigurationManager.AppSettings["aad:Authority"], ClientId = ConfigurationManager.AppSettings["aad:ClientId"], ClientSecret = ConfigurationManager.AppSettings["aad:ClientSecret"], Scopes = new string[] { "User.Read" }, RedirectUrl = ConfigurationManager.AppSettings["aad:Callback"] }; var loginMicrosoftOnlineCom = new MSALAuthProvider(); ///await context.Forward(new AuthDialog(new MSALAuthProvider(), options), async (IDialogContext authContext, IAwaitable<AuthResult> authResult) => await context.Forward(new AuthDialog(loginMicrosoftOnlineCom, options), async (IDialogContext authContext, IAwaitable <AuthResult> authResult) => { var result = await authResult; // Use token to call into service var json = await new HttpClient().GetWithAuthAsync(result.AccessToken, "https://graph.microsoft.com/v1.0/me"); await authContext.PostAsync($"Welcome back {json.Value<string>("displayName")} , you've login as {json.Value<string>("userPrincipalName")}. Account/transaction can operate now...."); ///await authContext.PostAsync("Welcome back" + result.UserName + " you've login as " + result.UserUniqueId + " Account/transaction can operate now...."); }, message, CancellationToken.None); //logout await loginMicrosoftOnlineCom.Logout(options, context); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result as Activity; var authProvider = new MSALAuthProvider(); if (context.UserData.TryGetValue($"{authProvider.Name}{MagicNumberValidated}", out string validated)) { if (validated == "true" && message != null) { // Check for spelling message.Text = await CallBingSpellCheckAsync(message.Text); await context.Forward(new PolicyEnquiryDialog(), async (luisContext, obj) => { var res = await obj; // Do Something }, message, CancellationToken.None); } } else { await context.Forward( new AuthDialog( new MSALAuthProvider(), new AuthenticationOptions(GetSetting("aad:Authority"), GetSetting("aad:ClientId"), GetSetting("aad:ClientSecret"), new[] { "User.Read" }, GetSetting("aad:Callback"))), async (authContext, authResult) => { var res = await authResult; // Use token to call into service var json = await new HttpClient().GetWithAuthAsync(res.AccessToken, "https://graph.microsoft.com/v1.0/me"); await authContext.PostAsync($"Hi {json.Value<string>("displayName")}, what can I do for you today?"); }, message, CancellationToken.None); } // TODO: Implement logout in luis dialog if (message?.Text.ToUpperInvariant() == "BYE") { context.UserData.RemoveValue($"{authProvider.Name}{AuthResultKey}"); context.UserData.SetValue($"{authProvider.Name}{MagicNumberValidated}", "false"); context.UserData.RemoveValue($"{authProvider.Name}{MagicNumberKey}"); context.Wait(MessageReceivedAsync); } }
private async Task AfterInitialAuthDialog( IDialogContext authContext, IAwaitable <AuthResult> awaitableAuthResult) { try { SD.Trace.TraceInformation("AppAuthDialog::AfterInitialAuthDialog"); AuthResult authResult = await awaitableAuthResult; Activity activity = authContext.ConversationData.GetValue <Activity>("Activity"); // return our reply to the user for debugging purposes if (displayAuthMessages) { int length = (activity.Text ?? string.Empty).Length; await authContext.PostAsync($"We see you sent {activity.Text} which was {length} characters"); } if (authResult == null) { await authContext.PostAsync("You didn't log in."); authContext.Done(true); return; } else { if (displayAuthMessages) { await authContext.PostAsync($"Token: {authResult.AccessToken}"); } } // Use token to call into service JObject json = await new HttpClient().GetWithAuthAsync( authResult.AccessToken, GraphUrl); // Two items to test // A -- Access Token Expires, do JUST [Part 1] Below // B -- Access Token Expires AND refresh fails, do [Part 1], [Part 2], and [Part 3]. // // To test auth expiration null out json variable (uncomment next line) [Part 1] // json = null; if (json == null) { var authProvider = new MSALAuthProvider(); AuthenticationOptions options = authContext.UserData.GetValue <AuthenticationOptions>( $"{authProvider.Name}{ContextConstants.AuthOptions}"); SD.Trace.TraceInformation("Attempting to refresh with token."); if (displayAuthMessages) { await authContext.PostAsync($"Attempting to refresh with token: {authResult.RefreshToken}"); } // To test auth expiration comment out next line [Part 2] authResult = await authProvider.GetAccessToken(options, authContext); // To test auth expiration uncomment out next two lines [Part 3] // authResult = null; // await authProvider.Logout(options, authContext); if (authResult != null) { SD.Trace.TraceInformation("Token Refresh Succeeded."); if (displayAuthMessages) { await authContext.PostAsync($"Token Refresh Succeeded. New Token: {authResult.AccessToken}"); } json = await new HttpClient().GetWithAuthAsync( authResult.AccessToken, "https://graph.microsoft.com/v1.0/me"); } else { SD.Trace.TraceInformation("Token Refresh Failed. Trying full login."); if (displayAuthMessages) { await authContext.PostAsync("Token Refresh Failed. Trying full login."); } await authContext.Forward( new BotAuth.Dialogs.AuthDialog(new MSALAuthProvider(), options), this.AfterInitialAuthDialog, activity, CancellationToken.None); return; } } SD.Trace.TraceInformation("Getting user data post auth."); string userName = json.Value <string>("displayName"); string userEmail = json.Value <string>("userPrincipalName"); if (displayAuthMessages) { await authContext.PostAsync($"I now know your name is {userName} " + $"and your UPN is {userEmail}"); } MeetingRequestInput meetingData = authContext.ConversationData.GetValue <MeetingRequestInput>(MeetingDataKey); meetingData.OrganizerName = userName; meetingData.OrganizerEmail = userEmail; authContext.ConversationData.SetValue(MeetingDataKey, meetingData); authContext.PrivateConversationData.SetValue(AccessTokenDataKey, authResult.AccessToken); SD.Trace.TraceInformation("Post Auth Hand Off to CreateMeetingRequestDialog."); authContext.Call(new CreateMeetingRequestDialog(), this.ResumeAfterMeetingDialog); } catch (Exception ex) { string fullError = ex.ToString(); SD.Trace.TraceError(fullError); await authContext.PostAsync(fullError); } }
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item) { var message = await item; // Save the message for later context.ConversationData.SetValue <Activity>("OriginalMessage", (Activity)message); // Let the user chose a provider var providers = AuthProviderConfig.GetAuthProviders(); PromptDialog.Choice(context, async(IDialogContext choiceContext, IAwaitable <AuthProviderConfig> choiceResult) => { var providerConfig = await choiceResult; choiceContext.ConversationData.SetValue <AuthProviderConfig>("AuthProvider", providerConfig); IAuthProvider authProvider; if (providerConfig.ProviderName == "Microsoft") { authProvider = new MSALAuthProvider(); } else { authProvider = new GenericOAuth2Provider($"GenericOAuth2Provider{providerConfig.ClientType}"); } await choiceContext.Forward(new AuthDialog(authProvider, providerConfig), async(IDialogContext authContext, IAwaitable <AuthResult> authResult) => { var result = await authResult; // Use token to call into service var prov = authContext.ConversationData.Get <AuthProviderConfig>("AuthProvider"); if (prov.ProviderName == "Microsoft") { var bytes = await new HttpClient().GetStreamWithAuthAsync(result.AccessToken, prov.PictureEndpoint); var pic = "data:image/png;base64," + Convert.ToBase64String(bytes); var m = authContext.MakeMessage(); m.Attachments.Add(new Attachment("image/png", pic)); await authContext.PostAsync(m); } else { var json = await new HttpClient().GetWithAuthAsync(result.AccessToken, prov.PictureEndpoint); var pic = ""; if (prov.ProviderName == "Google") { pic = json.Value <string>("picture"); } else if (prov.ProviderName == "Facebook") { pic = json.SelectToken("picture.data").Value <string>("url"); } else if (prov.ProviderName == "LinkedIn") { pic = json.Value <string>("pictureUrl"); } var m = authContext.MakeMessage(); m.Attachments.Add(new Attachment("image/png", pic)); await authContext.PostAsync(m); } // Wait for another message authContext.Wait(MessageReceivedAsync); }, choiceContext.ConversationData.Get <Activity>("OriginalMessage"), CancellationToken.None); }, providers, "Please select a provider we can use to look-up your information"); }