문제

Facebook 앱을 개발하고 방문자가 Facebook을 통해 승인 된 경우에만 특정보기에 액세스 할 수 있습니다. 이것은 매우 간단한 일이되어야하며, 나는 IE에서 그것을 시도 할 때까지 생각합니다. 다음 코드는 크롬 및 사파리에서 잘 작동합니다. Forms 인증을 사용하고 싶어서 를 설정했습니다.

<forms loginUrl="~/Account/Login" timeout="2880" />
.

web.config. 이렇게하면 방문자가 내 앱을 입력 할 때 다음 ActionResult로 지시합니다.

    public ActionResult Login(string returnUrl)
    {
        ManagerGame2.Utilities.StaticDataContent.InitStaticData();

        var oAuthClient = new FacebookOAuthClient();
        oAuthClient.AppId = FacebookApplication.Current.AppId;
        oAuthClient.RedirectUri = new Uri(redirectUrl);
        var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", returnUrl } });
        return Redirect(loginUri.AbsoluteUri);
    }
.

사용자가 Facebook 페이지로 리디렉션되고 액세스 토큰이 내 OAuth ActionResult로 다시 전송됩니다.

public ActionResult OAuth(string code, string state)
    {
        FacebookOAuthResult oauthResult;
        if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
        {
            if (oauthResult.IsSuccess)
            {
                var oAuthClient = new FacebookOAuthClient();
                oAuthClient.AppId = FacebookApplication.Current.AppId;
                oAuthClient.AppSecret = FacebookApplication.Current.AppSecret;
                oAuthClient.RedirectUri = new Uri(redirectUrl);
                dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                string accessToken = tokenResult.access_token;

                DateTime expiresOn = DateTime.MaxValue;

                if (tokenResult.ContainsKey("expires"))
                {
                    DateTimeConvertor.FromUnixTime(tokenResult.expires);
                }

                FacebookClient fbClient = new FacebookClient(accessToken);
                dynamic me = fbClient.Get("me?fields=id,name");
                long facebookID = Convert.ToInt64(me.id);


                Account acc = (from x in db.Account.OfType<Account>() where x.FaceBookID == facebookID select x).FirstOrDefault();
                if (acc == null)
                {
                    acc = CreateAccount(me);
                }
                acc.LatestLogin = DateTime.Now;
                db.Entry(acc).State = EntityState.Modified;
                db.SaveChanges();

                MemoryUserStore.CurrentAccount = acc;

                UserRoleProvider usp = new UserRoleProvider();
                usp.GetRolesForUser(acc.AccountID.ToString());
                FormsAuthentication.SetAuthCookie(acc.AccountID.ToString(), false);

                if (Url.IsLocalUrl(state))
                {
                    return Redirect(state);
                }
                return RedirectToAction("Details", "Account", new { id = acc.AccountID });
            }
        }

        return RedirectToAction("Index", "Account");
    }
.

여기서 수행하려고하는 것은 리디렉션에서 내가 돌아 오는 토큰이 유효한 것인지를 먼저 확인하는 것입니다. 그렇다면 FacebookID와 Name과 같은 방문자에 대한 데이터를 가져옵니다. 그런 다음 사용자가 이미 존재하는지 확인하고 그렇지 않은지 확인한 다음 내 데이터베이스와 일치시킵니다. 그렇지 않으면 하나를 만듭니다. 또한 사용자 정의 역할 공급자에서 사용자의 역할을 할당하지만이기 전에 무한 루프 문제가있었습니다. 그런 다음 를 설정합니다

FormsAuthentication.SetAuthCookie(acc.AccountID.ToString(), false);
.

그리고 나는 방문자가 승인되었는지 여부를 추적하는 핵심이 이것이 가정한다. 내가 이해하는 한, 방문자가 [권한 부여]가 필요한 ActionResult를 호출하려고 할 때 시스템 이이 쿠키를 확인합니다.

글쎄, 누군가 위의 코드가 Chrome / Safari에서 일하고있는 이유를 명확히하지만, 로그인을 통해 루프를 유지 한 다음 IE에서 무한히 oauth를 유지합니다.

My App은 MVC 3, EF 코드 첫 번째 및 Facebook C # SDK 5.0.25 를 사용하고 있습니다.

도움이 되었습니까?

해결책

Okay, so i figured out that the problem was triggered by the [Authorize] annotation, as expected. The Facebook SDK has a [CanvasAuthorize] annotation, and when i switch to using this, IE works fine and does not login forever.

Before this, i tried using cookieless authentication, but IE still didn't want to play along.

As far as i have figured out, the problem occurs because Facebook apps are inside an IFrame. This supposedly screws something up with cookies and trust. If someone knows why this is, i would appreciate to hear about it.

Also, if anyone knows how to use and maintain roles, easily, with this [CanvasAuthorize], i would be glad to know.

다른 팁

I know this seems obvious but are you sure cookies aren't disabled in IE? There is an option to disable cookies in developer tools.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top