gpt4 book ai didi

python - Django 休息框架 {"detail":"Authentication credentials were not provided."}

转载 作者:太空狗 更新时间:2023-10-29 18:17:15 26 4
gpt4 key购买 nike

我已尝试使用 OAuth 工具包向我的 Rest API 添加身份验证。我进入登录页面并输入我的用户名和密码,然后重定向到我的 api。然后我收到一条消息 {"detail":"Authentication credentials were not provided."} 我试过调查这个问题,大多数遇到问题的人似乎都错过了 Rest_Framework 设置中的某些内容。不过我想我没有。

这是我的代码:

设置.py

LOGIN_REDIRECT_URL = '/api/users/'

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
),
}

网址.py

urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}),

url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),

url(r'^api/users/$', api.UserList.as_view()),
url(r'^api/users/(?P<pk>[0-9+]+)/$', api.UserDetail.as_view()),
)

API.py

@receiver(post_save, sender=User)
def init_new_user(sender, instance, signal, created, **kwargs):
if created:
Token.objects.create(user=instance)


class APIEndpoint(ProtectedResourceView):
def get(self, request, *args, **kwargs):
return HttpResponse('Protected with OAuth2!')


class UserViewSet(viewsets.ModelViewSet):
model = User
serializer_class = UserSerializer

def retrieve(self, request, pk=None):
if pk == 'me':
return Response(UserSerializer(request.user).data)
return super(UserViewSet, self).retrieve(request, pk)


class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer


class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer

最佳答案

在我的案例中, token 身份验证在开发服务器上运行良好,而不是在 Apache 上。原因正是缺少 WSGIPassAuthorization On

http://www.django-rest-framework.org/api-guide/authentication/#apache-mod_wsgi-specific-configuration

关于python - Django 休息框架 {"detail":"Authentication credentials were not provided."},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com