2

新しいバージョンの Facebook SDK を使用しようとしましたが、接続できません。

エラー :

Could not parse Facebook OAuth url.

最初に、この関数でログイン uri を定義します

public static string FacebookConnectUrl(this UrlHelper urlHelper, string callbackUrl = null, string returnUrl = null)
{
        // By default, point to the login route
        if (callbackUrl == null)
            callbackUrl = urlHelper.AbsoluteRouteUrl("FacebookConnectCallback");

        dynamic parameters = new ExpandoObject();
        parameters.client_id = AppSettings.Get<long>("FacebookAppID");
        parameters.client_secret = AppSettings.Get("FacebookAppSecret");
        parameters.redirect_uri = callbackUrl;
        parameters.response_type = "code";
        parameters.scope = "email";

        var fb = new FacebookClient();
        return fb.GetLoginUrl(parameters).ToString();
}

Facebook ボタン (以前の関数から返された文字列を href として使用します):

<a href="@Url.FacebookConnectUrl()" class="btn btn-facebook btn-rounded fb-logo" rel="nofollow">Se connecter avec Facebook</a>

CallbackUrl 関数:

public ActionResult FacebookConnectCallback(string returnUrl)
    {
        var client = new FacebookClient();
        var oauthResult = client.ParseOAuthCallbackUrl(Request.Url);

        // Build the Return URI form the Request Url
        var redirectUri = new UriBuilder(Request.Url);
        redirectUri.Path = Url.Action("FacebookConnectCallback", "Account");

        // Exchange the code for an access token
        dynamic tokenResult = client.Get("/oauth/access_token", new
        {
            client_id = ConfigurationManager.AppSettings["FacebookAppId"],
            redirect_uri = redirectUri.Uri.AbsoluteUri,
            client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
            code = oauthResult.Code,
        });

        // Read the auth values
        string accessToken = tokenResult.access_token;

        // Get the user details
                dynamic me = client.Get("me?fields=id,first_name,last_name,email,gender,birthday");
                long facebookID = Convert.ToInt64(me.id);
                string email = Convert.ToString(me.email);

                // Log the user agent
                LogUserAgent(email, Request, null);

                // Do we already have an account for this user?
                var user = userRepository.GetUserByFacebookIDOrEmail(facebookID, email);
        if (user == null)
        {
            // Create the registration model
            var model = new RegisterModel
                            {
                                FirstName = me.first_name,
                                LastName = me.last_name,
                                Email = me.email,
                                Gender = ParseFacebookGender(me.gender as string),
                                DateOfBirth = ParseFacebookDate(me.birthday as string),
                                FacebookID = facebookID,
                                ProfilePicture = Tribway.Models.User.GetFacebookProfilePictureUrl(facebookID),
                                Referrer = Request.Cookies["referrer"]
                            };

            // Don't use Facebook proxymail addresses
            if (model.Email != null && model.Email.EndsWith("@proxymail.facebook.com"))
            {
                Logger.WarnFormat("User #{0} trying to register via Facebook but we got a proxymail address: {1}",
                                  model.FacebookID, model.Email);
                model.Email = null;
            }

            // Did Facebook give us all the info?
            if (string.IsNullOrWhiteSpace(model.Email) || string.IsNullOrWhiteSpace(model.Gender) ||
                model.DateOfBirth == null)
            {
                Logger.Warn("Redirecting FB user #" + model.FacebookID +
                            " to registration form after FB connect. Some user information is missing: " +
                            new JavaScriptSerializer().Serialize(model));

                return View("Register", model);
            }

            // Create a new user
            user = userRepository.CreateUser(model);

            // Save Facebook access token
            FacebookHelpers.StoreFacebookTokenResult(user, tokenResult);

            // Save
            userRepository.SaveChanges();

            // Set a cookie to remember the authentication
            FormsAuthentication.SetAuthCookie(user.Email, true);

            // Send notifications to their friends
            try
            {
                friendRepository.SendRegistrationNotifications(user, Html);
                friendRepository.SaveChanges();
            }
            catch (Exception x)
            {
                ErrorHelpers.LogInElmah(x);
            }

            // Redirect to the invitations page
            if (GetDisplayMode() == DisplayMode.Default)
                return RedirectToRoute("InvitesAfterRegistration");
            else
                return Redirect(GetAndClearLoginReturnUrl());
        }
        else
        {
            // Set a cookie to remember the authentication
            FormsAuthentication.SetAuthCookie(user.Email, true);

            // Update the last login date
            userRepository.UpdateLastLoginDate(user.Email);

            // Recover the gender / date of birth if missing
            if (user.Gender == null) user.Gender = ParseFacebookGender(me.gender as string);
            if (user.DateOfBirth == null) user.DateOfBirth = ParseFacebookDate(me.birthday as string);

            // Get the Facebook ID if missing
            if (user.FacebookID == null)
            {
                user.FacebookID = facebookID;
                if (user.ProfilePicture.StartsWith("http://www.gravatar.com/"))
                    user.ProfilePicture = Models.User.GetFacebookProfilePictureUrl(facebookID);
            }

            // Save Facebook ccess token
            FacebookHelpers.StoreFacebookTokenResult(user, tokenResult);

            // Save
            userRepository.SaveChanges();

            // Refresh Facebook friends
            ThreadPool.QueueUserWorkItem((_) =>
                                             {
                                                 try
                                                 {
                                                     friendRepository.GetFacebookFriendsFromCache(user.ID,
                                                                                                  accessToken);
                                                 }
                                                 catch (Exception x)
                                                 {
                                                     Logger.Error(
                                                         "Error while refreshing Facebook friend list for user #" +
                                                         user.Email, x);
                                                 }
                                             });

            return Redirect(returnUrl);
        }
    }
4

0 に答える 0