예제 #1
0
        /// <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);
            }
        }
예제 #2
0
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string userId, [FromUri] string botId, [FromUri] string conversationId, [FromUri] string channelId, [FromUri] string serviceUrl, [FromUri] string code, [FromUri] string state, CancellationToken token)
        {
            // Get the resumption cookie

            var address = new Address
                          (
                // purposefully using named arguments because these all have the same type
                botId: FacebookHelpers.TokenDecoder(botId),
                channelId: channelId,
                userId: FacebookHelpers.TokenDecoder(userId),
                conversationId: FacebookHelpers.TokenDecoder(conversationId),
                serviceUrl: FacebookHelpers.TokenDecoder(serviceUrl)
                          );
            var conversationReference = address.ToConversationReference();

            // Exchange the Facebook Auth code with Access token
            var accessToken = await FacebookHelpers.ExchangeCodeForAccessToken(conversationReference, code, MessagesController.FacebookOauthCallback.ToString());


            // Create the message that is send to conversation to resume the login flow
            var msg = conversationReference.GetPostToBotMessage();

            //msg.Text = $"token:{accessToken.AccessToken}";
            msg.Text = accessToken.AccessToken;
            var valid = await FacebookHelpers.ValidateAccessToken(msg.Text);

            var name = await FacebookHelpers.GetFacebookProfileName(msg.Text);

            //FacebookProfile fp = new FacebookProfile();
            //fp.Id = name;
            //fp.Name = msg.Text;
            MessagesController.userid   = name;
            MessagesController.acctoken = accessToken.AccessToken;
            // Resume the conversation to SimpleFacebookAuthDialog

            //await Conversation.ResumeAsync(conversationReference, msg);

            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, msg))
            {
                var dataBag = scope.Resolve <IBotData>();
                await dataBag.LoadAsync(token);

                //ConversationReference pending;
                //if (dataBag.PrivateConversationData.TryGetValue("persistedCookie", out pending))
                //{
                // remove persisted cookie
                dataBag.PrivateConversationData.RemoveValue("persistedCookie");
                await dataBag.FlushAsync(token);

                return(Request.CreateResponse("You are now logged in! Continue talking to the bot."));
                //}
                //else
                //{
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                //    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException("Cannot resume!"));
                //}
            }
        }
예제 #3
0
        public async Task <IActionResult> OAuthCallback(string userId, string botId, string conversationId,
                                                        string channelId, string serviceUrl, string code, string state,
                                                        CancellationToken token)
        {
            // Get the resumption cookie
            var address = new Address
                          (
                // purposefully using named arguments because these all have the same type
                botId: FacebookHelpers.TokenDecoder(botId),
                channelId: channelId,
                userId: FacebookHelpers.TokenDecoder(userId),
                conversationId: FacebookHelpers.TokenDecoder(conversationId),
                serviceUrl: FacebookHelpers.TokenDecoder(serviceUrl)
                          );
            var conversationReference = address.ToConversationReference();

            // Exchange the Facebook Auth code with Access token
            var accessToken = await FacebookHelpers.ExchangeCodeForAccessToken(conversationReference, code,
                                                                               SimpleFacebookAuthDialog.FacebookOauthCallback.ToString());

            // Create the message that is send to conversation to resume the login flow
            var msg = conversationReference.GetPostToBotMessage();

            msg.Text = $"token:{accessToken.AccessToken}";

            // Resume the conversation to SimpleFacebookAuthDialog
            await Conversation.ResumeAsync(conversationReference, msg);

            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, msg))
            {
                var dataBag = scope.Resolve <IBotData>();
                await dataBag.LoadAsync(token);

                ConversationReference pending;
                if (dataBag.PrivateConversationData.TryGetValue("persistedCookie", out pending))
                {
                    // remove persisted cookie
                    dataBag.PrivateConversationData.RemoveValue("persistedCookie");
                    await dataBag.FlushAsync(token);

                    return(Content("You are now logged in! Continue talking to the bot."));
                }
                else
                {
                    // Callback is called with no pending message as a result the login flow cannot be resumed.
                    return(BadRequest("Cannot resume!"));
                }
            }
        }
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string userId, [FromUri] string conversationId, [FromUri] string code, [FromUri] string state)
        {
            // Check if the bot is running against emulator
            var connectorType = HttpContext.Current.Request.IsLocal ? ConnectorType.Emulator : ConnectorType.Cloud;

            // Exchange the Facebook Auth code with Access toekn
            var token = await FacebookHelpers.ExchangeCodeForAccessToken(userId, conversationId, code, SimpleFacebookAuthDialog.FacebookOauthCallback.ToString());

            // Create the message that is send to conversation to resume the login flow
            var msg = new Message
            {
                Text = $"token:{token.AccessToken}",
                From = new ChannelAccount {
                    Id = userId
                },
                To = new ChannelAccount {
                    Id = botId.Value
                },
                ConversationId = conversationId
            };

            // Resume the conversation to SimpleFacebookAuthDialog
            var reply = await Conversation.ResumeAsync(botId.Value, userId, conversationId, msg, connectorType : connectorType);

            // Remove the pending message because login flow is complete
            IBotData       dataBag = new JObjectBotData(reply);
            PendingMessage pending;

            if (dataBag.PerUserInConversationData.TryGetValue("pendingMessage", out pending))
            {
                dataBag.PerUserInConversationData.RemoveValue("pendingMessage");
                var pendingMessage = pending.GetMessage();
                reply.To   = pendingMessage.From;
                reply.From = pendingMessage.To;

                // Send the login success asynchronously to user
                var client = Conversation.ResumeContainer.Resolve <IConnectorClient>(TypedParameter.From(connectorType));
                await client.Messages.SendMessageAsync(reply);

                return(Request.CreateResponse("You are now logged in! Continue talking to the bot."));
            }
            else
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException("Cannot resume!")));
            }
        }
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string userId, [FromUri] string botId, [FromUri] string conversationId, [FromUri] string channelId, [FromUri] string serviceUrl, [FromUri] string locale, [FromUri] string code, [FromUri] string state, CancellationToken token)
        {
            // Get the resumption cookie
            var address = new Address
                          (
                // purposefully using named arguments because these all have the same type
                botId: FacebookHelpers.TokenDecoder(botId),
                channelId: channelId,
                userId: FacebookHelpers.TokenDecoder(userId),
                conversationId: FacebookHelpers.TokenDecoder(conversationId),
                serviceUrl: FacebookHelpers.TokenDecoder(serviceUrl)
                          );
            var resumptionCookie = new ResumptionCookie(address, userName: null, isGroup: false, locale: locale);

            // Exchange the Facebook Auth code with Access token
            var accessToken = await FacebookHelpers.ExchangeCodeForAccessToken(resumptionCookie, code, SimpleFacebookAuthDialog.FacebookOauthCallback.ToString());

            // Create the message that is send to conversation to resume the login flow
            var msg = resumptionCookie.GetMessage();

            msg.Text = $"token:{accessToken.AccessToken}";

            // Resume the conversation to SimpleFacebookAuthDialog
            await Conversation.ResumeAsync(resumptionCookie, msg);

            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, msg))
            {
                var dataBag = scope.Resolve <IBotData>();
                await dataBag.LoadAsync(token);

                ResumptionCookie pending;
                if (dataBag.PrivateConversationData.TryGetValue("persistedCookie", out pending))
                {
                    // remove persisted cookie
                    dataBag.PrivateConversationData.RemoveValue("persistedCookie");
                    await dataBag.FlushAsync(token);

                    return(Request.CreateResponse("You are now logged in! Continue talking to the bot."));
                }
                else
                {
                    // Callback is called with no pending message as a result the login flow cannot be resumed.
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException("Cannot resume!")));
                }
            }
        }
예제 #6
0
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string userId, [FromUri] string conversationId, [FromUri] string channelId, [FromUri] string language, [FromUri] string code, [FromUri] string state)
        {
            // Get the resumption cookie
            var resumptionCookie = new ResumptionCookie(userId, botId.Value, conversationId, channelId, language);

            // Exchange the Facebook Auth code with Access token
            var token = await FacebookHelpers.ExchangeCodeForAccessToken(resumptionCookie, code, SimpleFacebookAuthDialog.FacebookOauthCallback.ToString());

            // Create the message that is send to conversation to resume the login flow
            var msg = resumptionCookie.GetMessage();

            msg.Text = $"token:{token.AccessToken}";

            // Resume the conversation to SimpleFacebookAuthDialog
            var reply = await Conversation.ResumeAsync(resumptionCookie, msg);

            // Remove the pending message because login flow is complete
            IBotData         dataBag = new JObjectBotData(reply);
            ResumptionCookie pending;

            if (dataBag.PerUserInConversationData.TryGetValue("persistedCookie", out pending))
            {
                dataBag.PerUserInConversationData.RemoveValue("persistedCookie");

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, reply))
                {
                    // make sure that we have the right Channel info for the outgoing message
                    var persistedCookie = pending.GetMessage();
                    reply.To   = persistedCookie.From;
                    reply.From = persistedCookie.To;

                    // Send the login success asynchronously to user
                    var client = scope.Resolve <IConnectorClient>();
                    await client.Messages.SendMessageAsync(reply);
                }

                return(Request.CreateResponse("You are now logged in! Continue talking to the bot."));
            }
            else
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException("Cannot resume!")));
            }
        }
예제 #7
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (Settings.Default.AccessToken != "")
            {
                var ListUser = FacebookHelpers.GET_ListFriends(txtIDUser.Text, Settings.Default.AccessToken);

                foreach (var item in ListUser)
                {
                    int id = dataGridViewFriend.Rows.Add();
                    dataGridViewFriend.Rows[id].Cells[0].Value = (id + 1).ToString();
                    dataGridViewFriend.Rows[id].Cells[1].Value = item.Split('|')[0];
                    dataGridViewFriend.Rows[id].Cells[2].Value = item.Split('|')[1];
                }
            }
            else
            {
                MessageBox.Show("No Access Token !");
            }
        }
예제 #8
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
            {
                AppId     = Settings.FacebookAppId,
                AppSecret = Settings.FacebookAppSecret,

                Provider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = context =>
                    {
                        foreach (var x in context.User)
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(x.Key, x.Value.ToString()));
                        }

                        //Get the access token/userId from FB and save to session
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken",
                                                                                   context.AccessToken));

                        var accessToken = context.Identity.FindFirstValue("FacebookAccessToken");
                        var fbUserId    = context.Identity.FindFirstValue("id");

                        FacebookHelpers.UpdateFacebookSessionInfo(accessToken, fbUserId);

                        return(Task.FromResult(true));
                    }
                },
            };

            facebookOptions.Scope.Add("email");
            app.UseFacebookAuthentication(facebookOptions);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
예제 #9
0
 public JsonResult UpdateFacebookSessionInfo(string accessToken, string userId)
 {
     return(Json(new { Success = FacebookHelpers.UpdateFacebookSessionInfo(accessToken, userId) }));
 }