登录Facebook后如何重定向网址? [英] How to redirect the url after logging into Facebook?

查看:131
本文介绍了登录Facebook后如何重定向网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个带有Facebook连接到应用程序的django应用程序。现在当我点击Facebook登录按钮时,oauth页面弹出。当我提供用户名n密码时,它会关闭,而不实际将页面重定向到任何页面。但是当我在新选项卡中使用FB页面时,我可以看到该用户的FB登录页面。所以登录是完美的工作,但我不明白哪里给页面重定向后,它被认证。有人可以帮我解决这个问题。这是我如何设置在我的设置页面?我找不到任何回调网址在选项中设置。

 应用程序ID 
xxxx
API密钥
xxxx
App Secret
xxx
网站URL
http:// localhost:8080 / redirect_url /
网站域
localhost
画布页
http://apps.facebook.com/registrationforms/
画布网址
http://apps.facebook.com/registrationforms/
安全画布网址
画布FBML / iframe
iframe

登录代码:
This一段代码插入在registrationForm html页面(登录):

  {%load facebookconnect%} 
{% $ _ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ / p>

从django导入模板
从django.conf导入设置
从django.core.urlresolvers导入reverse

register = template.Library()

class FacebookScriptNode(template.Node):
def render(self,context):
return
< script src =http://static.ak.connect.facebook.com/js/api_lib/v0.4/ FeatureLoader.js.phptype =text / javascript>< / script>


< script type =text / javascript> FB.init(%s,%s);
函数facebook_onlogin(){
var uid = FB.Facebook.apiClient.get_session()。uid;
var session_key = FB.Facebook.apiClient.get_session()。session_key;
var expires = FB.Facebook.apiClient.get_session()。expires;
var secret = FB.Facebook.apiClient.get_session()。secret;
var sig = FB.Facebook.apiClient.get_session()。sig;

fb_connect_ajax(expires,session_key,secret,uid,sig);

}

函数fb_connect_ajax(expires,session_key,ss,user,sig){

var post_string ='expires ='+ expires;
post_string = post_string +'& session_key ='+ session_key;
post_string = post_string +'& ss ='+ ss;
post_string = post_string +'& user ='+ user;
post_string = post_string +'& sig ='+ sig;

$ .ajax({
type:POST,
url:%s,
data:post_string,
success:function msg){
window.location ='%s'; //。reload()
}
});
}
< / script>
%(settings.FACEBOOK_API_KEY,reverse('xd_receiver'),reverse('facebook_connect_ajax'),settings.LOGIN_REDIRECT_URL)


def facebook_connect_script(解析器,令牌) :返回FacebookScriptNode()

register.tag(facebook_connect_script)

class FacebookLoginNode(template.Node):
def render(self,context):
return< fb:login-button onlogin ='facebook_onlogin();'>< / fb:login-button>
#return< fb:login-button onclick =openPopup https://graph.facebook.com/oauth/authorize?client_id=a0acfd122e64fc21cfa34d47369f0c97&redirect_uri=http://mysite.com/mypage&display=popup');\"></fb:login-button>



def facebook_connect_login_button(解析器,令牌):返回FacebookLoginNode()

register.tag(facebook_connect_login_button)


解决方案

我想你正在使用JS Facebook库,如果你唉,这个oauth只是弹出。我会去更简单的oauth重定向方式,使用以下:

  def build_authentication_redirect(self):
args = {}
args [client_id] = self.app_id
args [redirect_uri] = self.redirect_uri
args [scope] =,join(self.req_perms )
redirect_url =https://www.facebook.com/dialog/oauth?\"+urllib.urlencode(args)
redirect_code =
< script type =text / javascript>
top.location.href ='%s';
< / script>
%redirect_url;
return HttpResponse(redirect_code,mimetype =text / html)

其中self.app_id是您的Facebook应用程序ID。
其中self.redirect_uri是用户在登录后将重定向的URL。
其中self.scope是由self.req_perms构建的,这是一个所需权限的数组。



之后,用户将被重定向到redirect_uri您可以在post'signed_request'参数中使用以下函数进行解码:

  def load_signed_request(self,signed_request) 
从一个signed_request值加载用户状态
sig,payload = signed_request.split(u'。',1)
sig = self.base64_url_decode(sig)
data = json.loads(self.base64_url_decode(payload))

expected_sig = hmac.new(self.app_secret,msg = payload,digestmod = hashlib.sha256).digest()

#允许signed_request最多工作1天
如果sig == expected_sig和data [u'issued_at']> (time.time() - 86400):
返回data.get(u'user_id'),data.get(u'oauth_token')
else:
返回无,无

示例:

  sigreq = request.POST.get('signed_request',None)
user_id,access_token = load_signed_request(sigreq)

再次,您将需要self.app_secret和以下功能:

  @staticmethod 
def base64_url_decode(data):
data = data.encode(u'ascii')
data + ='='*(4 - (len(data)%4))
return base64 .urlsafe_b64decode(data)

我在FB JS登录和验证方面遇到了很多麻烦,特别是在不同的浏览器,这种方式是我可以找到的更强壮的方式:)



Btw如果你想要我的facebook.py文件,我可以在网上在某个地方可用...甚至有一个@fbsig_required和@f bsig_redirect查看装饰器...



哦,这里也是我的导入:

  import cgi 
import hashlib
import time
import urllib
import base64
import datetime
import hmac

from django .conf导入设置
从django.http导入HttpResponseRedirect,HttpResponse,HttpResponseNotFound


I have created a django application with a Facebook connect to the application. Now when i click on the Facebook login button, the oauth page pop ups. When i give the username n password, it gets closed without actually redirecting the page to any page. But when i took FB page in a new tab, i could see the FB logged in page of that user. So the login is working perfect, but i dont understand where to give the page redirection after it gets authenticated. Can somebody help me to solve this. This is how i set in my settings page ? I couldnt find any callback url to be set in the options.

App ID
xxxx
API Key
xxxx
App Secret
xxx
Site URL
http://localhost:8080/redirect_url/
Site Domain
localhost
Canvas Page
http://apps.facebook.com/registrationforms/
Canvas URL
http://apps.facebook.com/registrationforms/
Secure Canvas URL
Canvas FBML/iframe
iframe

The code for login : This piece of code is inserted in the registrationForm html page(login) :

{% load facebookconnect %}
{% facebook_connect_login_button %}
{% facebook_connect_script %}

and the facebookconnect.py code is :

from django import template
from django.conf import settings
from django.core.urlresolvers import reverse

register = template.Library()

class FacebookScriptNode(template.Node):
        def render(self, context):
            return """
            <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>


            <script type="text/javascript"> FB.init("%s", "%s");
                function facebook_onlogin() {
                    var uid = FB.Facebook.apiClient.get_session().uid;
                    var session_key = FB.Facebook.apiClient.get_session().session_key;
                    var expires = FB.Facebook.apiClient.get_session().expires;
                    var secret = FB.Facebook.apiClient.get_session().secret;
                    var sig = FB.Facebook.apiClient.get_session().sig;

                    fb_connect_ajax(expires, session_key, secret, uid, sig);

                }

                function fb_connect_ajax(expires, session_key, ss, user, sig) {

                    var post_string = 'expires=' + expires;
                    post_string = post_string + '&session_key=' + session_key;
                    post_string = post_string + '&ss=' + ss;
                    post_string = post_string + '&user=' + user;
                    post_string = post_string + '&sig=' + sig;

                    $.ajax({
                        type: "POST",
                        url: "%s",
                        data: post_string,
                        success: function(msg) {
                            window.location = '%s'; //.reload()
                        }
                    });
                } 
            </script>       
            """ % (settings.FACEBOOK_API_KEY, reverse('xd_receiver'), reverse('facebook_connect_ajax'), settings.LOGIN_REDIRECT_URL)


def facebook_connect_script(parser, token): return FacebookScriptNode()

register.tag(facebook_connect_script)

class FacebookLoginNode(template.Node):
    def render(self, context): 
        return "<fb:login-button onlogin='facebook_onlogin();'></fb:login-button>"
        #return "<fb:login-button onclick="openPopup('https://graph.facebook.com/oauth/authorize?client_id=a0acfd122e64fc21cfa34d47369f0c97&redirect_uri=http://mysite.com/mypage&display=popup');"></fb:login-button>"



def facebook_connect_login_button(parser, token): return FacebookLoginNode()

register.tag(facebook_connect_login_button)

解决方案

I suppose you are using the JS Facebook library if you say that the oauth just pop ups. I would go the simpler oauth redirect way, using a the following :

def build_authentication_redirect(self):
            args = {}
            args["client_id"]=self.app_id
            args["redirect_uri"]=self.redirect_uri
            args["scope"]=",".join(self.req_perms)
            redirect_url = "https://www.facebook.com/dialog/oauth?"+urllib.urlencode(args)
            redirect_code = """
                    <script type="text/javascript">
                    top.location.href='%s';
                    </script>
            """ % redirect_url;
            return HttpResponse(redirect_code,mimetype="text/html")

Where self.app_id is your facebook app id. Where self.redirect_uri is the url the user will be redirected after login. Where self.scope is built from self.req_perms which is an array of the required permissions.

After that they user will be redirected to redirect_uri with the access token in post 'signed_request' parameter, you can use the following function to decode it :

def load_signed_request(self, signed_request):
            """Load the user state from a signed_request value"""
            sig, payload = signed_request.split(u'.', 1)
            sig = self.base64_url_decode(sig)
            data = json.loads(self.base64_url_decode(payload))

            expected_sig = hmac.new(self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()

            # allow the signed_request to function for upto 1 day
            if sig == expected_sig and data[u'issued_at'] > (time.time() - 86400):
                    return data.get(u'user_id'), data.get(u'oauth_token')
            else:
                    return None,None

Example :

sigreq =request.POST.get('signed_request', None)
user_id,access_token = load_signed_request(sigreq)

Again you will need self.app_secret and the following function :

@staticmethod
    def base64_url_decode(data):
            data = data.encode(u'ascii')
            data += '=' * (4 - (len(data) % 4))
            return base64.urlsafe_b64decode(data)

I had a lot of trouble with FB JS login and auth, especially on different browsers, this way is the more robust way I could find :)

Btw If you want my facebook.py file I can put it available online somewhere ... It even has a @fbsig_required and @fbsig_redirect view decorators ...

Oh Also here are my imports :

import cgi
import hashlib
import time
import urllib
import base64
import datetime
import hmac

from django.conf import settings
from django.http import HttpResponseRedirect,HttpResponse,HttpResponseNotFound

这篇关于登录Facebook后如何重定向网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆