Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Oauth2-使用Google登录_Python_Oauth_Token - Fatal编程技术网

Python Oauth2-使用Google登录

Python Oauth2-使用Google登录,python,oauth,token,Python,Oauth,Token,我已经找了两天的答案,但什么也没找到 我正在尝试将Oauth2集成到Django上的Google登录中。我的代码抛出了一个异常——“令牌无效” 发生这种情况: resp, content = client.request(access_token_url, "POST") if resp['status'] != '200': print content raise Exception("Invalid response from Google."+con

我已经找了两天的答案,但什么也没找到

我正在尝试将Oauth2集成到Django上的Google登录中。我的代码抛出了一个异常——“令牌无效”

发生这种情况:

resp, content = client.request(access_token_url, "POST")
    if resp['status'] != '200':
        print content
        raise Exception("Invalid response from Google."+content)
在google_authenticate()中

请帮帮我

我的代码:

    def google_login(request):
    scope = "https://www.googleapis.com/auth/userinfo.profile"

    request_token_url = "https://www.google.com/accounts/OAuthGetRequestToken?scope=%s" % scope
    authorize_url = 'https://www.google.com/accounts/OAuthAuthorizeToken'
    authenticate_url = "https://accounts.google.com/o/oauth2/auth"

    response_type = "code"
    redirect_uri = "http://127.0.0.1:8000/login/google/auth"
    scope = "https://www.googleapis.com/auth/userinfo.profile"

    oauth_key = settings.GOOGLE_KEY
    oauth_secret = settings.GOOGLE_SECRET

    consumer = oauth.Consumer(oauth_key, oauth_secret)
    client = oauth.Client(consumer)

    # Step 1: Get a request token. This is a temporary token that is used for 
    # having the user authorize an access token and to sign the request to obtain 
    # said access token.

    resp, content = client.request(request_token_url, "POST")
    request_token = dict(urlparse.parse_qsl(content))

    if resp['status'] != '200':
        raise Exception("Invalid response from Google.")

    # Step 2. Store the request token in a session for later use.
    request.session['request_token'] = dict(cgi.parse_qsl(content))

    # Step 3. Redirect the user to the authentication URL.
    url = "%s?oauth_token=%s&client_id=%s&response_type=%s&redirect_uri=%s&scope=%s" % (authenticate_url,
        request.session['request_token']['oauth_token'],
        oauth_key,response_type,redirect_uri,scope)

    return HttpResponseRedirect(url)

def google_authenticate(request):
    access_token_url = 'https://www.google.com/accounts/OAuthGetAccessToken'

    oauth_key = settings.GOOGLE_KEY
    oauth_secret = settings.GOOGLE_SECRET

    consumer = oauth.Consumer(oauth_key, oauth_secret)

    # Step 1. Use the request token in the session to build a new client.
    token = oauth.Token(request.session['request_token']['oauth_token'],
        request.session['request_token']['oauth_token_secret'])
    if 'oauth_verifier' in request.GET:
        token.set_verifier(request.GET['oauth_verifier'])
    client = oauth.Client(consumer, token)

    # Step 2. Request the authorized access token from Google.
    resp, content = client.request(access_token_url, "POST")
    if resp['status'] != '200':
        print content
        raise Exception("Invalid response from Google."+content)

    access_token = dict(cgi.parse_qsl(content))

    # Step 3. Lookup the user or create them if they don't exist.
    try:
        user = User.objects.get(username=access_token['screen_name'])
    except User.DoesNotExist:
        # When creating the user I just use their screen_name@twitter.com
        # for their email and the oauth_token_secret for their password.
        # These two things will likely never be used. Alternatively, you 
        # can prompt them for their email here. Either way, the password 
        # should never be used.
        user = User.objects.create_user(access_token['screen_name'],
            '%s@twitter.com' % access_token['screen_name'],
            access_token['oauth_token_secret'])

        # Save our permanent token and secret for later.
        profile = Profile()
        profile.user = user
        profile.oauth_token = access_token['oauth_token']
        profile.oauth_secret = access_token['oauth_token_secret']
        profile.save()

    # Authenticate the user and log them in using Django's pre-built 
    # functions for these things.
    user = authenticate(username=access_token['screen_name'],
        password=access_token['oauth_token_secret'])
    login(request, user)

    return HttpResponseRedirect('/')

经过很长时间的浪费,我放弃了OAuth2,因为它很难配置,我所需要的只是让用户登录。下面的代码应该可以帮助需要执行类似操作的人,并且可以进行自定义。我所做的一切就是按照形成URL的说明进行操作,例如->

我创建了两个视图(对于不使用Django-pages的人),并创建了第一个视图的链接: 这个页面我称之为login/google,并从登录页面链接到它

def google_login(request):
    token_request_uri = "https://accounts.google.com/o/oauth2/auth"
    response_type = "code"
    client_id = XXXXXX-your_client_id
    redirect_uri = "http://mysite/login/google/auth"
    scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
    url = "{token_request_uri}?response_type={response_type}&client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}".format(
        token_request_uri = token_request_uri,
        response_type = response_type,
        client_id = client_id,
        redirect_uri = redirect_uri,
        scope = scope)
    return HttpResponseRedirect(url)
上述代码已重定向到第二个页面(此页面必须在google应用程序定义中定义为重定向uri)。 我将此页面称为login/google/auth:

def google_authenticate(request):
    parser = Http()
    login_failed_url = '/'
    if 'error' in request.GET or 'code' not in request.GET:
        return HttpResponseRedirect('{loginfailed}'.format(loginfailed = login_failed_url))

    access_token_uri = 'https://accounts.google.com/o/oauth2/token'
    redirect_uri = "http://mysite/login/google/auth"
    params = urllib.urlencode({
        'code':request.GET['code'],
        'redirect_uri':redirect_uri,
        'client_id':XXXXX_your_google_key,
        'client_secret':XXXXX_your_google_secret,
        'grant_type':'authorization_code'
    })
    headers={'content-type':'application/x-www-form-urlencoded'}
    resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers = headers)
    token_data = jsonDecode(content)
    resp, content = parser.request("https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}".format(accessToken=token_data['access_token']))
    #this gets the google profile!!
    google_profile = jsonDecode(content)
    #log the user in-->
    #HERE YOU LOG THE USER IN, OR ANYTHING ELSE YOU WANT
    #THEN REDIRECT TO PROTECTED PAGE
    return HttpResponseRedirect('/dashboard')

我真的希望这能帮助那里的人们,节省我浪费的时间。欢迎对代码发表评论

如果有人想知道的话,现在有一个来自Google的oauth2client库,它实现了凭证的流和存储=>现在总共需要10行@user1160475。请访问developers.Google.com。你应该已经有谷歌用户名和密码,请登录。谢谢。代码起作用。我花了一些时间才弄明白Http()类是在httplib2中定义的。如何检查已通过google身份验证的用户是否是新用户?我需要这个为用户创建注册手续。每个用户都有一个唯一的id。我要做的是检查我是否有一个带有该id的条目。如果没有,他是一个新用户