1

我想使用 3rd 方身份验证(facebook)登录我的 Web 应用程序。我在谷歌上搜索得到这种类型的代码,大多数用户说它有效但不适合我。我使用以下代码。

  1. ConnectAuthentication 类

    public class ConnectAuthentication
    {
    
    public static bool isConnected()
    {
        return (SessionKey != null && UserID != -1);
    }
    public static string ApiKey
    {
        get { return System.Configuration.ConfigurationManager.AppSettings["ApplicationKey"]; }
    }
    public static string SecretKey
    {
        get { return System.Configuration.ConfigurationManager.AppSettings["SecretKey"]; }
    }
    public static string SessionKey
    {
        get { return GetFacebookCookie("session_key"); }
    }
    public static int UserID
    {
        get
        {
            int userID = -1;
            int.TryParse(GetFacebookCookie("user"), out userID);
            return userID;
        }
    }
    private static string GetFacebookCookie(string cookieName)
    {
        string retString = null;
        string fullCookie = ApiKey +"_" + cookieName;
        if (HttpContext.Current.Request.Cookies[fullCookie] != null)
            retString = HttpContext.Current.Request.Cookies[fullCookie].Value;
        return retString;
    }
    

    }

  2. FBLogin.js



    function CallFB() {
        FB.ensureInit(function () { FB.XFBML.Host.parseDomTree(); });
        FB.init("203596266327066", "http://localhost:61283/xd_receiver.htm");
    }

    function FBLogOut() {
        FB.ensureInit(function () { FB.XFBML.Host.parseDomTree(); });
        FB.init("203596266327066", "http://localhost:61283/xd_receiver.htm");
        if (FB.Connect != null)
            FB.Connect.logout();
    }
  1. Default.aspx - 起始页

    <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
        type="text/javascript"></script>
    <script src="js/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript" src="JS/fblogin.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            CallFB();
        });        
    </script>
    <form id="form1" runat="server">
    <div>
        <br />
        <div id="facebk" style="height: 5px;">
            <fb:login-button length='long' onlogin='window.location.reload()' size='medium'>
            </fb:login-button>
        </div>
    </div>
    </form>
    

3.Default.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {            
        if (ConnectAuthentication.isConnected())
            Response.Redirect("AuthUser.aspx");
    }
  1. AuthUser.aspx - 仅访问经过身份验证的用户

    $(document).ready(function () { $("#btn").click(function () { FBLogOut(); }); });

4

0 回答 0