django-oauth-toolkit使用

写在前面

如果不了解Oauth2认证过程的 可以以微信的认证为例子 了解一下

安装

pip install django-oauth-toolkit==1.2.0

settings.py 文件中增加

INSTALLED_APPS = (
    ...
    'oauth2_provider',
)

urls.py 文件中增加路由

urlpatterns = [
    ...
    path(r'oauth/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]

同步数据库

python manage.py migrate oauth2_provider

使用

Oauth 分为两个角色 Oauth2 ProviderOauth2 ConsumerProvider 即提认证的站点。Consumer 即需要从认证站点获取用户信息的站点。例如:我想从微信处获取用户的微信信息,那么微信就是 Provider 而我的站点就是 Consumer 。下面我们就配置 Provider

创建一个应用

创建应用就类似于将自己的平台信息提供给微信,微信认证之后给你提供 API_KEYAPI_SERCRET 一样。这样的好处是可以确认目标站点是可信的。 可以通过 django-admin 的后台来创建。

WechatIMG11.jpeg

为了方便测试 我们可以将 Redirect urls 设置成 http://django-oauth-toolkit.herokuapp.com/consumer/exchange/
同时我们也只以 Authoriation Code 为例进行说明

测试认证服务器

假设我们的任务服务器的URL就是 http://localhost:8010/oauth/

  • 构建认证链接
    http://localhost:8010/oauth/authorize?state=STATE&client_id=client_id&response_type=code&redirect_uri=CALLBACK_URL&scope=read

    • 其中 state 参数可以是一个随机的字符串,即你传给服务器什么 服务器就返回给你什么
    • response_type 对应四种 grant typecodetokenpasswordclient_credentials 并且不同的 response_type 对应的参数也不同
    • redirect_uri 就是后端的路由 认证完成之后 会跳到 redirect_uri?code=xxx
    • scope 对应的是此次请求的授权权限 read 对应只读
  • 授权应用
    当用户点击认证链接的时候,会跳到认证网页上,上面会提示用户是否要授权xxx应用获取你的个人信息。当你点击授权的时候。就会跳转到 上面设置的 redirect_uri 上。如: redirect_uri?code=xxxx 其中 code 就是授权码。你的站点就可以利用 code 去换取 access_token

  • 获取 access_token
    curl -X POST -d "grant_type=authorization_code&code=xxx" -u"<client_id>:<client_secret>" http://localhost:8010/oauth/token/
    其中 这个请求 Basic Auth 认证。注意编码是 x-www-form-urlencode

    {
        "access_token": "5kpaQHTdbnKY86ZI41RQAkU6DNfWKu",
        "expires_in": 36000,
        "token_type": "Bearer",
        "scope": "read write",
        "refresh_token": "GNfVL3x6L20hU95ajvHQtgZI2QBuC2"
    }
    
  • 通过 refresh_token 刷新 access_token

access_token 的使用

  • django 中的使用

    # 首先创建一个路由 继承 oauth2_provider.views.generic.ProtectedResourceView  如:
    from oauth2_provider.views.generic import ProtectedResourceView
    from django.http import HttpResponse
    
    class ApiEndpoint(ProtectedResourceView):
        def get(self, request, *args, **kwargs):
            return HttpResponse('Hello, OAuth2!')
    # 那么在非授权状态下就无法访问这个接口了
    # 需要我们在 request header 中增加  Authorization: Bearer <access_token> 那么就可以访问这个接口了
    
  • 当做 认证的 backend 使用

  • django-rest-framework中使用

    from oauth2_provider.contrib.rest_framework import OAuth2Authentication
    
    class OauthUserViewSet(GenericViewSet):
        serializer_class = serializers.OauthUserModelSerializer
        permission_classes = [perms.UserViewPermission, ]
        queryset = get_user_model().objects.filter(is_active=True)
        authentication_classes = [OAuth2Authentication, ]  # 认证的方式选择  OAuth2Authentication
    
        @action(detail=False, methods=['GET'])
        def user_info(self, request, *args, **kwargs):
            user = request.user
            return Response(self.get_serializer(user, many=False).data)
    # 也可以通过在 header 中增加认证来访问接口了
    

    参考

官方文档
阮老师的解释
关于四种授权模式

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 以下是官网直译:https://oauth.net/ 1. 首页 OAuth是一种开放协议(注:协议是公开的,任何...
    JacoChan阅读 11,378评论 0 20
  • OAuth2.0 是关于授权的开放网络标准,它允许用户已第三方应用获取该用户在某一网站的私密资源,而无需提供用户名...
    baiyi阅读 10,362评论 4 25
  • 我们经常会提到到SSO,OAuth,OpenID,SAML,一时间会让人摸不清他们之间的关系和区别,最近简单粗浅的...
    蒋扬海阅读 6,367评论 4 15
  • OAuth 2.0 是目前比较流行的做法,它率先被Google, Yahoo, Microsoft, Facebo...
    半夜菊花茶阅读 14,673评论 0 12
  • 子夜梦魂忧,幻境终难留。 临窗说旧事,阴郁赴愁池。 雷惊珠玉落,风动影婆娑。 浮云蔽万顷,破夜蛟龙吟。 天色阴郁,...
    星尘梦羽阅读 344评论 0 4