简体   繁体   中英

how to get individual user API by using django rest framework knox

Before I implement token authentication, it worked fine to grab each user,

GET: http://localhost:8000/users/1/  
 {
        "url": "http://localhost:8000/users/1/",
        "id": 1,
        "username": "foo",
        "boards": [
            "http://localhost:8000/boards/15/"
        ]
    },

After I implement knox token authentication,

#settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}

#users/views.py
class UserDetail(generics.RetrieveAPIView):
    permission_classes = [permissions.IsAuthenticated]
    queryset = User.objects.all()
    serializer_class = UserSerializer

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

#users/urls.py
app_name = 'users'
urlpatterns = [
    path('', UserList.as_view(), name='user-list'),
    path('<int:pk>/', UserDetail.as_view(), name='user-detail'),
    path('accounts/register/', RegistrationAPI.as_view(), name='user-register'),
    path('accounts/login/', LoginAPI.as_view(), name='user-login'),
    path('accounts/logout/', knox_views.LogoutView.as_view(), name='user-logout'),

]

urlpatterns = format_suffix_patterns(urlpatterns)

# users/serializer.py
class UserSerializer(serializers.HyperlinkedModelSerializer):

    boards = serializers.HyperlinkedRelatedField(
        view_name='board:board-detail',
        lookup_field='pk',
        many=True, 
        queryset=Board.objects.all()
    )
    url = serializers.HyperlinkedIdentityField(
        read_only=True,
        lookup_field='pk',
        view_name="users:user-detail")


    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'boards')

class CreateSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(
        read_only=True,
        lookup_field='pk',
        view_name="users:user-detail")

    def create(self, validated_data):
        user = User.objects.create_user(
            validated_data['username'], None, validated_data['password']
        )
        return user
    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'password')

class LoginUserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        user = authenticate(**data)
        if user and user.is_active:
            return user
        raise serializers.ValidationError("unable to log in with provided credential")

# project/urls.py
urlpatterns = [
    path('boards/', include('apps.board.urls', namespace='board')),
    path('admin/', admin.site.urls),
    path('users/', include('apps.users.urls', namespace='users')), # detail of users
    path(r'^users/accounts/', include('knox.urls')), # detail of users
]

Now I am getting 401 error,

GET: http://localhost:8000/users/1/
{
    "detail": "Authentication credentials were not provided."
}

Even, POST:http://localhost:8000/logout/ has the same 401 Unauthorized error. I tried login first and then logout , but I still get same error. Why am I getting unauthorized

EDIT
Once I POST login, I got token and I pass this token to the header to
1) GET individual user( http://localhost:8000/users/1/ ,
2) POST logout( http://localhost:8000/users/accounts/logout/
But I still get same 401 Unauthorized status

For someone who just starts using Postman,

  1. Get token when POST login
  2. Switch mode to GET
  3. In Headers session, Key: Authorization Value: Token xxxxx (token from step1)

then send this request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM