private async Task CheckLogin(IDialogContext context, IMessageActivity msg) { if (context.UserData.TryGetValue(BotUtility.AccessToken, out string token)) { await context.PostAsync("you are already logined."); } else { // 保存這次對話的記錄,登入完畢後要 ResumeAsync 回到原本的對話 var conversationReference = context.Activity.ToConversationReference(); string authUrl = GoogleOAuthHelper.GetGoogleLoginURL(conversationReference, BotUtility.OAuthCallbackURL); var reply = context.MakeMessage(); reply.Text = "Please login in using this card"; reply.Attachments.Add(SigninCard.Create("You need to authorize me", "Login to Google!", authUrl ).ToAttachment()); await context.PostAsync(reply); } context.Wait(MessageReceivedAsync); }
public static async Task LogIn(IDialogContext context) { GitHubClient client = new GitHubClient(new ProductHeaderValue(Constants.ProductHeader)); ConversationReference cr = context.Activity.ToConversationReference(); IMessageActivity reply = context.MakeMessage(); string csrf = Membership.GeneratePassword(24, 1); context.UserData.SetValue(Constants.StateKey, csrf); OauthLoginRequest request = new OauthLoginRequest(ConfigurationManager.AppSettings[Constants.GitHubClientIdKey]) { Scopes = { "repo" }, State = csrf, RedirectUri = GetRedirectUri(cr) }; Uri loginUrl = client.Oauth.GetGitHubLoginUrl(request); reply.Text = "Please login to GitHub using the button below."; SigninCard card = SigninCard.Create("Authorize me to access your GitHub account.", "Login to GitHub", loginUrl.ToString()); reply.Attachments.Add(card.ToAttachment()); await context.PostAsync(reply); }
/// <summary> /// Login the user. /// </summary> /// <param name="context"> The Dialog context.</param> /// <returns> A task that represents the login action.</returns> private async Task LogIn(IDialogContext context) { string token; if (!context.PrivateConversationData.TryGetValue(AuthTokenKey, out token)) { var conversationReference = context.Activity.ToConversationReference(); context.PrivateConversationData.SetValue("persistedCookie", conversationReference); // sending the sigin card with Facebook login url var reply = context.MakeMessage(); var fbLoginUrl = FacebookHelpers.GetFacebookLoginURL(conversationReference, FacebookOauthCallback.ToString()); reply.Text = "Please login in using this card"; reply.Attachments.Add(SigninCard.Create("You need to authorize me", "Login to Facebook!", fbLoginUrl ).ToAttachment()); await context.PostAsync(reply); context.Wait(MessageReceivedAsync); } else { context.Done(token); } }
/// <summary> /// Login the user. /// </summary> /// <param name="context"> The Dialog context.</param> /// <returns> A task that represents the login action.</returns> private async Task LogIn(IDialogContext context) { string token; if (!context.PrivateConversationData.TryGetValue(AuthTokenKey, out token)) { context.PrivateConversationData.SetValue("persistedCookie", ResumptionCookie); // sending the sigin card with Facebook login url var reply = context.MakeMessage(); var fbLoginUrl = FacebookHelpers.GetFacebookLoginURL(ResumptionCookie, FacebookOauthCallback.ToString()); reply.Text = "請選擇以下登入方式"; reply.Attachments.Add(SigninCard.Create("使用第三方進行登入", "用臉書登入", fbLoginUrl ).ToAttachment()); await context.PostAsync(reply); context.Wait(MessageReceivedAsync); } else { context.Done(token); } }
public void SignInCardCreate() { var signInCard = SigninCard.Create("Please sign in", "Sign In", "http://example-signin.com"); Assert.NotNull(signInCard); Assert.IsType <SigninCard>(signInCard); }
/// <summary> /// Prompt the user to authenticate using a sign in card. /// </summary> /// <param name="context">The context for the execution of a dialog's conversational process.</param> /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="context"/> is null. /// </exception> private async Task AuthenticateAsync(IDialogContext context) { IMessageActivity message; Uri redirectUri; string authUrl; string state; try { redirectUri = new Uri($"{HttpContext.Current.Request.Url.Scheme}://{HttpContext.Current.Request.Url.Host}:{HttpContext.Current.Request.Url.Port}/{BotConstants.CallbackPath}"); state = $"&state={GenerateState(context)}"; authUrl = await provider.AccessToken.GetAuthorizationRequestUrlAsync( $"{provider.Configuration.ActiveDirectoryEndpoint}/{BotConstants.AuthorityEndpoint}", provider.Configuration.GraphEndpoint, provider.Configuration.ApplicationId, redirectUri, state).ConfigureAwait(false); message = context.MakeMessage(); message.Attachments.Add(SigninCard.Create( Resources.SigninCardText, Resources.LoginCaptial, authUrl).ToAttachment()); await context.PostAsync(message).ConfigureAwait(false); context.Wait(MessageReceivedAsync); } finally { message = null; } }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; //// calculate something for us to return //int length = (activity.Text ?? string.Empty).Length; //// return our reply to the user //await context.PostAsync($"You sent {activity.Text} which was {length} characters"); if (activity.Text == "login") { // create state (passing data) for OAuth var convRef = context.Activity.ToConversationReference(); var stateCol = System.Web.HttpUtility.ParseQueryString(string.Empty); stateCol["userId"] = convRef.User.Id; stateCol["botId"] = convRef.Bot.Id; stateCol["conversationId"] = convRef.Conversation.Id; stateCol["serviceUrl"] = convRef.ServiceUrl; stateCol["channelId"] = convRef.ChannelId; //var uriBuilder = new UriBuilder(ConfigurationManager.AppSettings["OAuthCallbackUrl"]); //var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query); //query["userId"] = convRef.User.Id; //query["botId"] = convRef.Bot.Id; //query["conversationId"] = convRef.Conversation.Id; //query["serviceUrl"] = convRef.ServiceUrl; //query["channelId"] = convRef.ChannelId; //uriBuilder.Query = query.ToString(); //var redirectUrl = uriBuilder.ToString(); // create Azure AD signin context var authContext = new AuthenticationContext("https://login.microsoftonline.com/common"); var authUri = authContext.GetAuthorizationRequestUrlAsync( "https://outlook.office365.com/", ConfigurationManager.AppSettings["ClientId"], new Uri(ConfigurationManager.AppSettings["OAuthCallbackUrl"]), UserIdentifier.AnyUser, "&state=" + System.Web.HttpUtility.UrlEncode(stateCol.ToString())); // show SignIn card (setting oauth sign-in url to SignIn card) var reply = context.MakeMessage(); reply.Text = "Authentication Required"; reply.Attachments.Add(SigninCard.Create( "Login", "Please login to Office 365", authUri.Result.ToString()).ToAttachment()); await context.PostAsync(reply); } else if (activity.Text == "get mail") { string accessToken = string.Empty; using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity)) { var dataStore = scope.Resolve <IBotDataStore <BotData> >(); var convRef = context.Activity.ToConversationReference(); var address = new Microsoft.Bot.Builder.Dialogs.Address ( botId: convRef.Bot.Id, channelId: convRef.ChannelId, userId: convRef.User.Id, conversationId: convRef.Conversation.Id, serviceUrl: convRef.ServiceUrl ); var userData = await dataStore.LoadAsync( address, BotStoreType.BotUserData, CancellationToken.None); accessToken = userData.GetProperty <string>("AccessToken"); } if (string.IsNullOrEmpty(accessToken)) { await context.PostAsync("Not logging-in (type \"login\")"); } else { // Get recent 10 e-mail from Office 365 HttpClient cl = new HttpClient(); var acceptHeader = new MediaTypeWithQualityHeaderValue("application/json"); cl.DefaultRequestHeaders.Accept.Add(acceptHeader); cl.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage httpRes = await cl.GetAsync("https://outlook.office365.com/api/v1.0/me/messages?$orderby=DateTimeSent%20desc&$top=10&$select=Subject,From"); if (httpRes.IsSuccessStatusCode) { var strRes = httpRes.Content.ReadAsStringAsync().Result; JObject jRes = await httpRes.Content.ReadAsAsync <JObject>(); JArray jValue = (JArray)jRes["value"]; foreach (JObject jItem in jValue) { string sub = $"Subject={((JValue)jItem["Subject"]).Value}"; sub = sub.Replace('<', ' ').Replace('>', ' ').Replace('[', ' ').Replace(']', ' '); await context.PostAsync(sub); } } else { await context.PostAsync("Failed to get e-mail.\n\nPlease type \"login\" before you get e-mail."); } } } else if (activity.Text == "revoke") { await context.PostAsync("Click [here](https://account.activedirectory.windowsazure.com/), login, and remove this app (Bot with Office 365 Authentication Example)."); } else if (activity.Text == "login_succeed") { await context.PostAsync("You logged in !"); } else { await context.PostAsync("# Bot Help\n\nType the following command. (You need your Office 365 Exchange Online subscription.)\n\n**login** -- Login to Office 365\n\n**get mail** -- Get your e-mail from Office 365\n\n**revoke** -- Revoke permissions for accessing your e-mail"); } context.Wait(MessageReceivedAsync); }