Amazon web services ';匿名用户';对象没有属性';是"行政"';

Amazon web services ';匿名用户';对象没有属性';是"行政"';,amazon-web-services,django-rest-framework,amazon-elastic-beanstalk,django-rest-framework-jwt,Amazon Web Services,Django Rest Framework,Amazon Elastic Beanstalk,Django Rest Framework Jwt,我正在使用Django 2.2和Python 3.6 我使用AWS EB部署了Django REST服务器,但出现以下错误 它在本地端工作正常,但在EB实例中发生错误 根据我的分析,request.user通常在本地被识别,但在EB上被标记为匿名用户 我使用相同的代码,但为什么会发生这种情况 REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumber

我正在使用Django 2.2和Python 3.6

我使用AWS EB部署了Django REST服务器,但出现以下错误

它在本地端工作正常,但在EB实例中发生错误

根据我的分析,request.user通常在本地被识别,但在EB上被标记为匿名用户

我使用相同的代码,但为什么会发生这种情况

REST_FRAMEWORK = {
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 10,
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
}
我将上面的代码更改为下面的代码,因为这是类的身份验证问题,但我仍然得到一个错误

REST_FRAMEWORK = {
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 10,
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework_simplejwt.authentication.JWTAuthentication",
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ],
}
错误详细信息

AttributeError
'AnonymousUser' object has no attribute 'is_admin'

users/permissions.py in has_permission at line 26
    def has_permission(self, request, view):
        print("=" * 50)
        print(request.user)
        print("=" * 50)
        return bool(request.user and request.user.is_admin)
时间线

> GET /api/v1/users/ HTTP/1.1
> Host: instance.ap-northeast-2.elasticbeanstalk.com
> User-Agent: insomnia/2020.2.2
> Content-Type: application/json
> Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkzNjA4Nzg5LCJqdGkiOiJmZGY5YmM4MWM3M2I0YTU3YmZkODg2YmU5ZWVlMGEzZCIsInVzZXJfaWQiOjN9.kLv3H7ygzVomI2DgU84I900m4CydhL48Ob86SX5IEaQ
用户/型号.py

class User(AbstractBaseUser, TimeStampedModel):
    objects = UserManager()

    GENDER_MALE = "male"
    GENDER_FEMALE = "female"
    GENDER_OTHER = "other"

    GENDER_CHOICES = (
        (GENDER_MALE, "Male"),
        (GENDER_FEMALE, "Female"),
        (GENDER_OTHER, "Other"),
    )

    email = models.EmailField(unique=True)
    username = models.CharField(max_length=20, unique=True)
    gender = models.CharField(max_length=5, choices=GENDER_CHOICES)
    birth = models.DateField()
    avatar = models.ImageField(upload_to="user_avatars/%Y/%m/%d", blank=True)
    is_admin = models.BooleanField(default=False)
from .permissions import IsSelf, IsAdminOrSelf, IsAdminUser

class UsersViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.action == "list":
            permission_classes = [IsAdminUser]
        elif self.action == "create" or self.action == "retrieve":
            permission_classes = [AllowAny]
        elif self.action == "destroy":
            permission_classes = [IsAdminOrSelf]
        else:
            permission_classes = [IsSelf]
from rest_framework.permissions import BasePermission


class IsSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        return bool(user == request.user)


class IsAdminOrSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        is_self = bool(user == request.user)
        is_admin = request.user.is_admin

        return is_self or is_admin


class IsAdminUser(BasePermission):
    """
    Allows access only to admin users.
    """

    def has_permission(self, request, view):
        print("=" * 50)
        print(request.user)
        print("=" * 50)
        return bool(request.user and request.user.is_admin)
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views

from django.urls import path

from . import views

urlpatterns = [
    path("token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh"),
]
用户/视图.py

class User(AbstractBaseUser, TimeStampedModel):
    objects = UserManager()

    GENDER_MALE = "male"
    GENDER_FEMALE = "female"
    GENDER_OTHER = "other"

    GENDER_CHOICES = (
        (GENDER_MALE, "Male"),
        (GENDER_FEMALE, "Female"),
        (GENDER_OTHER, "Other"),
    )

    email = models.EmailField(unique=True)
    username = models.CharField(max_length=20, unique=True)
    gender = models.CharField(max_length=5, choices=GENDER_CHOICES)
    birth = models.DateField()
    avatar = models.ImageField(upload_to="user_avatars/%Y/%m/%d", blank=True)
    is_admin = models.BooleanField(default=False)
from .permissions import IsSelf, IsAdminOrSelf, IsAdminUser

class UsersViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.action == "list":
            permission_classes = [IsAdminUser]
        elif self.action == "create" or self.action == "retrieve":
            permission_classes = [AllowAny]
        elif self.action == "destroy":
            permission_classes = [IsAdminOrSelf]
        else:
            permission_classes = [IsSelf]
from rest_framework.permissions import BasePermission


class IsSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        return bool(user == request.user)


class IsAdminOrSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        is_self = bool(user == request.user)
        is_admin = request.user.is_admin

        return is_self or is_admin


class IsAdminUser(BasePermission):
    """
    Allows access only to admin users.
    """

    def has_permission(self, request, view):
        print("=" * 50)
        print(request.user)
        print("=" * 50)
        return bool(request.user and request.user.is_admin)
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views

from django.urls import path

from . import views

urlpatterns = [
    path("token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh"),
]
用户/权限.py

class User(AbstractBaseUser, TimeStampedModel):
    objects = UserManager()

    GENDER_MALE = "male"
    GENDER_FEMALE = "female"
    GENDER_OTHER = "other"

    GENDER_CHOICES = (
        (GENDER_MALE, "Male"),
        (GENDER_FEMALE, "Female"),
        (GENDER_OTHER, "Other"),
    )

    email = models.EmailField(unique=True)
    username = models.CharField(max_length=20, unique=True)
    gender = models.CharField(max_length=5, choices=GENDER_CHOICES)
    birth = models.DateField()
    avatar = models.ImageField(upload_to="user_avatars/%Y/%m/%d", blank=True)
    is_admin = models.BooleanField(default=False)
from .permissions import IsSelf, IsAdminOrSelf, IsAdminUser

class UsersViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.action == "list":
            permission_classes = [IsAdminUser]
        elif self.action == "create" or self.action == "retrieve":
            permission_classes = [AllowAny]
        elif self.action == "destroy":
            permission_classes = [IsAdminOrSelf]
        else:
            permission_classes = [IsSelf]
from rest_framework.permissions import BasePermission


class IsSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        return bool(user == request.user)


class IsAdminOrSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        is_self = bool(user == request.user)
        is_admin = request.user.is_admin

        return is_self or is_admin


class IsAdminUser(BasePermission):
    """
    Allows access only to admin users.
    """

    def has_permission(self, request, view):
        print("=" * 50)
        print(request.user)
        print("=" * 50)
        return bool(request.user and request.user.is_admin)
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views

from django.urls import path

from . import views

urlpatterns = [
    path("token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh"),
]
服务器回溯

Traceback:

File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
  114.             return self.dispatch(request, *args, **kwargs)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  505.             response = self.handle_exception(exc)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  465.             self.raise_uncaught_exception(exc)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception
  476.         raise exc

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  493.             self.initial(request, *args, **kwargs)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py" in sentry_patched_drf_initial
  258.                     return old_drf_initial(self, request, *args, **kwargs)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in initial
  411.         self.check_permissions(request)

File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in check_permissions
  332.             if not permission.has_permission(request, self):

File "/opt/python/current/app/users/permissions.py" in has_permission
  26.         return bool(request.user and request.user.is_admin)

Exception Type: AttributeError at /api/v1/users/
Exception Value: 'AnonymousUser' object has no attribute 'is_admin'
Request information:
USER: AnonymousUser

GET: No GET data

POST: No POST data

FILES: No FILES data

COOKIES: No cookie data
JWT-Auth
users/url.py

class User(AbstractBaseUser, TimeStampedModel):
    objects = UserManager()

    GENDER_MALE = "male"
    GENDER_FEMALE = "female"
    GENDER_OTHER = "other"

    GENDER_CHOICES = (
        (GENDER_MALE, "Male"),
        (GENDER_FEMALE, "Female"),
        (GENDER_OTHER, "Other"),
    )

    email = models.EmailField(unique=True)
    username = models.CharField(max_length=20, unique=True)
    gender = models.CharField(max_length=5, choices=GENDER_CHOICES)
    birth = models.DateField()
    avatar = models.ImageField(upload_to="user_avatars/%Y/%m/%d", blank=True)
    is_admin = models.BooleanField(default=False)
from .permissions import IsSelf, IsAdminOrSelf, IsAdminUser

class UsersViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.action == "list":
            permission_classes = [IsAdminUser]
        elif self.action == "create" or self.action == "retrieve":
            permission_classes = [AllowAny]
        elif self.action == "destroy":
            permission_classes = [IsAdminOrSelf]
        else:
            permission_classes = [IsSelf]
from rest_framework.permissions import BasePermission


class IsSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        return bool(user == request.user)


class IsAdminOrSelf(BasePermission):
    def has_object_permission(self, request, view, user):
        is_self = bool(user == request.user)
        is_admin = request.user.is_admin

        return is_self or is_admin


class IsAdminUser(BasePermission):
    """
    Allows access only to admin users.
    """

    def has_permission(self, request, view):
        print("=" * 50)
        print(request.user)
        print("=" * 50)
        return bool(request.user and request.user.is_admin)
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views

from django.urls import path

from . import views

urlpatterns = [
    path("token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh"),
]
基于会话的身份验证似乎有效

在我看来,授权头似乎不起作用

# code
class IsAdminUser(BasePermission):
    """
    Allows access only to admin users.
    """

    def has_permission(self, request, view):
        print("=" * 50)
        print(request.auth)
        print(request.data)
        print(request.user)
        print("=" * 50)
        return bool(request.user and request.user.is_admin)

# result in AWS EB
[Wed Jul 01 20:37:28.712785 2020] [:error] [pid 3995] ==================================================
[Wed Jul 01 20:37:28.712834 2020] [:error] [pid 3995] None
[Wed Jul 01 20:37:28.713505 2020] [:error] [pid 3995] <QueryDict: {}>
[Wed Jul 01 20:37:28.713522 2020] [:error] [pid 3995] AnonymousUser
[Wed Jul 01 20:37:28.713529 2020] [:error] [pid 3995] ==================================================

# result in localhost
System check identified no issues (0 silenced).
July 01, 2020 - 20:43:04
Django version 2.2.12, using settings 'config.settings'
Starting development server at http://127.0.0.1:9000/
Quit the server with CONTROL-C.
==================================================
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkzNjA1MzM0LCJqdGkiOiIyOTY3ZTQ3MDEzY2Q0MDNlODQxN2VjNTNkMDU4ZDRjZiIsInVzZXJfaWQiOjF9.3czMFSzMR-g-vraPnOhhf0UCWamlIpSLuD0I1RBJOnA
<QueryDict: {}>
1 : tim
==================================================
[01/Jul/2020 20:43:13] "GET /api/v1/users/ HTTP/1.1" 200 1768
#代码
类IsAdminUser(基本权限):
"""
仅允许管理员用户访问。
"""
def具有_权限(自我、请求、查看):
打印(“=”*50)
打印(request.auth)
打印(请求数据)
打印(请求.用户)
打印(“=”*50)
返回bool(request.user和request.user.is_admin)
#导致AWS EB
[Wed Jul 01 20:37:28.712785 2020][:错误][pid 3995]==================================================
[Wed Jul 01 20:37:28.712834 2020][:错误][pid 3995]无
[Wed Jul 01 20:37:28.713505 2020][:错误][pid 3995]
[Wed Jul 01 20:37:28.713522 2020][:错误][pid 3995]匿名用户
[Wed Jul 01 20:37:28.713529 2020][:错误][pid 3995]==================================================
#导致本地主机
系统检查未发现任何问题(0静音)。
2020年7月1日-20:43:04
Django版本2.2.12,使用“config.settings”设置
正在启动开发服务器http://127.0.0.1:9000/
使用CONTROL-C退出服务器。
==================================================
EYJ0Exiaioijkv1QILCJ0HBGCIOIJIUZI1NIJ9.EYJ0B2TLBL90EXBLIYWZZZZIIWIZXHWIJOXNTKZNJA1MZM0LCJQDGIOIYYOY3ZTQMDEZY2Q0MDNLODQN2VJNKmDu4ZDRJZINVZZJFAWQIOJF9.3czMFSzMR-g-VRAPNOHf0UCWAMLIPSLUDI1BJONA
1:蒂姆
==================================================
[01/Jul/2020 20:43:13]“GET/api/v1/users/HTTP/1.1”200 1768

到底是什么问题。

第一个问题是,
AnonymousUser
在django中没有
is_admin
属性。您可以在调用
is\u admin
之前检查
is\u superuser
或检查您的用户是否经过身份验证。看看吧


关于本地应用和远程应用的区别,我猜您登录的是本地应用,而不是远程应用。这就是为什么在您的远程应用程序上,
请求返回
匿名用户
。用户

我遇到的问题与此问题的原因相同

这也是AWS论坛上的一个已知问题

您可以通过以下方式修复它:

# .ebextensions/wsgihacks.config

files:
  "/etc/httpd/conf.d/wsgihacks.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      WSGIPassAuthorization on

原始线程:

很抱歉,尽管使用Json类型放置授权头,但还是出现了一个错误。Heather正在发送:Authorization:Bearer{JWT}我似乎无法仅通过JWT Auth在部署环境中登录,但我可以从Django Admin窗口登录。我如何解决这个问题?如果您无法登录,那么您在头文件中传递的JWT来自哪里?(你在第一次评论中提到了这一点)。这可能是很多事情,也许你的API不能与你的后端通信?尝试在你的问题中添加更多关于网络的信息,登录时传递的信息,服务器返回的信息等。我在问题中添加了更多信息,请检查!谢谢你花时间陪我。