Аутентификация токена отлично работает на локальном хосте, но не работает на сервере Ubuntu (Djangorestframework) - PullRequest
0 голосов
/ 04 апреля 2020

Я пишу сервер в django, и я сделал API-интерфейсы в django остальные рамки. Все API-интерфейсы прекрасно работают на локальном хосте, но когда я загружаю свой проект на сервер Ubuntu, его токен аутентификации не работает. Это всегда дает

{"detail":"Authentication credentials were not provided."}

Мой весь код отлично работает на locallost, но на сервере Ubuntu выдает ошибку.

views.py

class ManageUserView(generics.RetrieveUpdateAPIView):
    serializer_class = serializers.UserSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        return self.request.user

Serializers.py *

class UserSerializer(serializers.ModelSerializer):
    """ Serializer for the users object """

    class Meta:
        model = get_user_model()
        fields = ('id', 'email', 'password', 'user_type')
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}

    def create(self, validated_data):
        """ Create a new user with encrypted password and return it"""
        print(validated_data)
        return get_user_model().objects.create_type_user(**validated_data)

    def update(self, instance, validated_data):
        """ Update a user, setting the password correctly and return it """
        password = validated_data.pop('password', None)
        user = super().update(instance, validated_data)

        if password:
            user.set_password(password)
            user.save()

        return user

Ответы [ 2 ]

0 голосов
/ 04 апреля 2020

Это мой (точка конф) файл

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.


    ServerName www.shabber.tech
    ServerAdmin official.kisaziaraat@gmail.com
    ServerAlias shabber.tech
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

    Alias /static /home/shabber/apna/static
    <Directory /home/shabber/apna/static>
        Require all granted
    </Directory>

    Alias /media /home/shabber/apna/media
    <Directory /home/shabber/apna/media>
        Require all granted
    </Directory>

    <Directory /home/shabber/apna/apna>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIScriptAlias / /home/shabber/apna/apna/wsgi.py
    WSGIDaemonProcess apna_app python-path=/home/shabber/apna python-home=/home/shabber/apna/venv
    WSGIProcessGroup apna_app
    WSGIPassAuthorization On

</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
0 голосов
/ 04 апреля 2020

Apache не будет передавать заголовок авторизации при использовании mod_wsgi по умолчанию. Вам необходимо установить WSGIPassAuthorization в конфигурации вашего сервера или виртуального хоста

WSGIPassAuthorization On

https://www.django-rest-framework.org/api-guide/authentication/#apache -mod_wsgi -peci c -configuration

https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIPassAuthorization.html

...