iT邦幫忙

0

ASP.NET MVC無法用FaceBook登入

  • 分享至 

  • xImage

最近在研究社群登入,
不知為何用Google登入就很容易,
但用Facebook登入用了兩種方式都抓不到資訊
附上前後端原始碼,
希望有高手能幫忙解答,感恩~

前端cshtml

@using (Html.BeginForm("ExternalLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))
{
    @Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary" id="Facebook" name="provider" value="Facebook" title="Signin with Facebook account">Signin with Facebook account</button>}

後端controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
     // 要求重新導向至外部登入提供者
     if(provider != "Facebook")
         return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
      else
         return new ChallengeResult(provider, Url.Action("FacebookExternalLoginCallback", "Account", new { ReturnUrl = Request.UrlReferrer.OriginalString }));
}

[AllowAnonymous]
public async Task<ActionResult> FacebookExternalLoginCallback(string returnUrl)
{
    string myUrl = "";
    //ie的話取returnUrl
    if (!string.IsNullOrEmpty(returnUrl))
    {
        Uri uri = new Uri(returnUrl);
        myUrl = HttpUtility.ParseQueryString(uri.Query).Get("myUrl");
    }
    else
    {//Google chrome
        Uri uri = new Uri(Request.UrlReferrer.OriginalString);
        myUrl = HttpUtility.ParseQueryString(uri.Query).Get("myUrl");
    }
            
    AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("FacebookExternalLoginCallback", new { ReturnUrl = returnUrl }));

    if (!result.IsSuccessful)
    {//FB登入失敗
        //導回會員登入頁
        return RedirectToAction("Login", "Account");
    }
    else
    {//FB登入成功
        //FB回傳的資料
        // id,username,name,link,gender,birthday,accesstoken,
        string fbID = result.ProviderUserId;
        string fbName = result.ExtraData["name"];
        string fbEmail = result.ExtraData["username"];

        if (string.IsNullOrEmpty(myUrl))
        {
            //導至首頁
            return RedirectToAction("Index", "Home");
        }
        else
        {//先前Request的Url
            Response.Redirect(myUrl);
        }
    }
}
小魚 iT邦大師 1 級 ‧ 2017-05-30 09:23:14 檢舉
話說,我前端Button那一段都被處理掉了,總之button是可以用的,後端也能跑到FacebookExternalLoginCallback裡面,但每次抓到的結果都是登入失敗
小魚 iT邦大師 1 級 ‧ 2017-05-30 22:45:48 檢舉
不用了,自己解決了,可以給自己最佳解答嗎?
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答