DRF前后端分离实现Oauth2.0的全部代码
时间: 2024-11-09 13:24:22 浏览: 12
在Django Rest Framework (DRF) 中实现OAuth2.0的前后端分离通常涉及到几个关键步骤。由于这里无法直接给出完整的代码,我会提供一个概述以及关键部分的代码示例。首先,你需要安装`djangorestframework-oauth2_provider`库:
```bash
pip install djangorestframework-oauth2_provider
```
然后,在你的Django项目中配置设置文件,例如`settings.py`:
```python
INSTALLED_APPS = [
# ...
'rest_framework',
'oauth2_provider',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
),
}
OAUTH2_PROVIDER = {
'SCOPES': {
'read': 'Read scope',
'write': 'Write scope',
}
}
```
创建应用并注册模型:
```python
from rest_framework import routers, serializers, viewsets
from oauth2_provider.models import Application
class ApplicationSerializer(serializers.ModelSerializer):
class Meta:
model = Application
fields = ['client_id', 'client_secret', 'name', 'redirect_uris', 'user']
class ApplicationViewSet(viewsets.ModelViewSet):
queryset = Application.objects.all()
serializer_class = ApplicationSerializer
router = routers.DefaultRouter()
router.register(r'applications', ApplicationViewSet)
urlpatterns = router.urls
```
在URL配置中添加OAuth2资源:
```python
from django.urls import path, include
urlpatterns += [
path('api/', include(router.urls)),
path('api/oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
```
对于客户端认证,你可以创建一个视图或前端API请求处理登录:
```python
from rest_framework.views import APIView
from oauth2_provider.views.authtoken import ObtainAuthToken
from rest_framework.response import Response
class CustomObtainAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
user = self.user_cache
if user.is_active:
# 这里可以增加额外的数据处理或验证
return Response({
'access_token': response.data['token'],
'user_data': { 'username': user.username, 'email': user.email },
})
else:
return Response(response.data, status=status.HTTP_401_UNAUTHORIZED)
urlpatterns += [
path('login/token/', CustomObtainAuthToken.as_view(), name='token_obtain_pair'),
]
```
这只是一个基础的框架,实际项目中你还需要处理授权码、刷新令牌等其他流程,并在后端验证用户权限。同时,前端需要实现相应的逻辑来请求访问令牌和使用它们获取数据。
阅读全文