django oauth 工具包 unsupported_grant_type 错误

django oauth toolkit unsupported_grant_type error

我试图将 outh2 添加到我的 django 应用程序中,所以我使用了 django oauth 工具包。 所以我按照教程进行操作,但是如果我尝试获取用户令牌,它总是会向我发送 unsupported_grant_type 错误。我该如何解决这个错误?

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    )
}

OAUTH2_PROVIDER = {
    # parses OAuth2 data from application/json requests
    'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
}

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.api.urls')),
    path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]

客户类型:机密

授权授予类型:基于资源所有者密码

chrome advanced rest client

url : http://client_id:client_secret@localhost:8000/o/token/

requirements.txt

asgiref==3.2.5
autopep8==1.5
certifi==2019.11.28
chardet==3.0.4
Django==3.0.4
django-oauth-toolkit==1.3.0
djangorestframework==3.11.0
idna==2.9
oauthlib==3.1.0
pycodestyle==2.5.0
pytz==2019.3
requests==2.23.0
sqlparse==0.3.1
urllib3==1.25.8

1.您必须创建应用程序:

http://localhost:8000/o/applications/

单击 link 创建一个 新应用程序 并使用以下数据填写表格:

姓名:随便取一个名字

客户类型:机密

授权授予类型: 资源所有者基于密码 然后你给 clientIdSecretClient

2。获取您的令牌并使用您的 API

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/

示例:

curl -X POST -d "grant_type=password&username=Alex&password=Won123" -u"cWS5WudFiBhHh6BZxcaOgRGfrZjhcP2rfQcWVyaU:puNJ1SgQbp39Ai1TmYJx0wL9LnC6FNarnY3dgYBA3Z7AgQR5zRcfw5U144zxJ6vndW0jtV4WWKip33kQnFUl4v73xt2IosLGHo7k1w35R7aK8aFL3ZBoMcQ3pyaWjkBT" http://127.0.0.1:8000/o/token/

user_name 和密码是在您的授权服务器中注册的用户的凭据,最后作为响应,您提供令牌并为您的请求使用这样的令牌:

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/users

注意您的应用程序配置以及您的用户名和密码。

只需在 OAUTH2_PROVIDER 设置中删除 OAUTH2_BACKEND_CLASS

OAUTH2_PROVIDER = {
    # parses OAuth2 data from application/json requests
    # 'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
    # this is the list of available scopes
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}

如果您打算使用 OAUTH2_BACKEND_CLASS,您应该以 JSON 格式发送正文。

{
    "grant_type":"password",
    "client_id":"<client_id>",
    "client_secret":"<client_secret>",
    "username":"<usename>",
    "password":"<password>"
}
curl -X POST -d '{"grant_type":"password","client_id":"<client_id>","client_secret":"<client_secret>","username":"<username>","password":"<password>"}' http://localhost:8000/o/token/