如何在使用GitHub API时使用基本身份验证创建OAuth令牌

2024-04-26 07:00:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从事一个django项目,我正在尝试使用用户名和密码实现Github登录。你知道吗

以下是我的views.py文件的内容:

@login_required
def github_access_via_username(request):
    if request.method == 'POST':
        form = GitHubUserPassAuthForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')

            payload = {
                "scopes" : [
                    "repo", "admin:org", "admin:public_key", "admin:repo_hook", "admin:org_hook",
                    "gist", "notifications", "user", "delete_repo", "write:discussion", "admin:gpg_key",
                ],
                "note" : "Permissions",
            }
            response = requests.post('https://api.github.com/authorizations', params=payload, auth=(username, password))
            #json_response = response.json()
            #access_token = json_response['token']
            #user = Github(access_token)
            return HttpResponse(response.status_code)
    else:
        form = GitHubUserPassAuthForm()
    return render(request, 'core/github_login.html', {'form':form})

这里是print(reponse)的输出

{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization'}
[23/Sep/2018 19:55:42] "POST /core/github_access_via_username/ HTTP/1.1" 200 5020

我没有得到任何东西,所以我决定返回status_code,它返回了一个400。我卡住了。有开眼剂吗?你知道吗


Tags: formgithubtokenjsonaccessadminresponserequest
1条回答
网友
1楼 · 发布于 2024-04-26 07:00:43

我想出来了!根据GitHub上的文档,您需要您的客户机id和客户机密钥来获取或创建新的授权。所以我修改了payloaddict和response变量如下:

...
payload = {
    ...            
    "client_secret" : settings.GITHUB_CLIENT_SECRET,
}
response = requests.put('https://api.github.com/authorizations/clients/{}'.format(settings.GITHUB_CLIENT_ID), auth=(username, password), data=json.dumps(payload))
...

……而且成功了!你知道吗

相关问题 更多 >