question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Authorization based on JWT, how can i get works?

See original GitHub issue

Hi, linuxlewis.

I think it’s question to you …

I have the trouble with authorization based on this package:

https://github.com/GetBlimp/django-rest-framework-jwt

If i try to do normal ajax request to collection /questions i get errors:

HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer.

So … ok. That’s can be good for me, i would change all application logic for use websockets and it’s not problem for me.

But when i try to send request with ws.send(JSON.stringify(msg)):

var msg = { stream: "questions", payload: { action: "create", data: { description: "What is your favorite python package?", categories: ["http://localhost:8000/api/categories/1/"] }, request_id: "some-guid" } } ws.send(JSON.stringify(msg))

I get this error:

IntegrityError: null value in column “owner_id” violates not-null constraint DETAIL: Failing row contains (11, 2017-06-11 12:06:02.583387+00, What is your favorite python package?, , 1200.00000000, f, f, f, null).

My QuestionSerializer looks like:

`class QuestionSerializer(serializers.HyperlinkedModelSerializer):

def create(self, validated_data):

    categories_data = validated_data.pop('categories')

    question = Question.objects.create(**validated_data)

    question.is_open = True
    question.is_finish = True
    question.save()

    for category in categories_data:
        question.categories.add(category)

    return question

owner = UserSerializer(read_only=True)
answers = AnswerSerializer(many=True, read_only=True)
elo = serializers.ReadOnlyField()
is_verified = serializers.ReadOnlyField()
is_finish = serializers.ReadOnlyField()
is_open = serializers.ReadOnlyField()

class Meta:
    model = Question
    fields = (
        'url',
        'id',
        'created',
        'owner',
        'description',
        'elo',
        'is_verified',
        'is_finish',
        'is_open',
        'categories',
        'answers'
    )`

The model:

`class Question(models.Model):

created = models.DateTimeField(auto_now_add=True)

owner = models.ForeignKey(
    'auth.User',
    related_name='%(app_label)s_%(class)s_related'
)

categories = models.ManyToManyField(
    'core.Category'
)

answers = models.ManyToManyField(
    'learn.Answer'
)

description = models.TextField()

additional = models.TextField()

elo = models.DecimalField(
    max_digits=20,
    decimal_places=8,
    default=Decimal('1200.0000')
)

is_verified = models.BooleanField(
    default=False
)

is_finish = models.BooleanField(
    default=False
)

is_open = models.BooleanField(
    default=False,
    blank=True
)

def __unicode__(self):
    return self.description`

And view:

`class QuestionViewSet(viewsets.ModelViewSet):

serializer_class = QuestionSerializer
permissions_classes = (
    IsOwnerOrReadOnly,
)

def get_queryset(self):

    queryset = Question.objects.all()

    category = self.request.query_params.get('category', None)
    description = self.request.query_params.get('description', None)

    if description is not None:
        queryset = Question.objects.filter(description__icontains=description)

    if category is not None and description is None:

        is_verified = self.request.query_params.get('is_verified', None)
        is_finish = self.request.query_params.get('is_finish', None)

        if is_verified is not None and is_finish is not None:
            queryset = Question.objects.filter(categories__pk=category, is_verified=True, is_finish=True)
        else:
            queryset = Question.objects.filter(categories__pk=category)

    if category is not None and description is not None:
        queryset = Question.objects.filter(categories__pk=category, description=description)

    return queryset

def perform_create(self, serializer):
    serializer.save(owner=self.request.user)`

Can you explain me how can i get it works all together?

Basicly i need to create only private chat for this moment for my users but i trying to understand how can i make other stuff in application with channels_api and this crap won’t let me fall a sleep…

Thank you for your attention and suggestion if you know how i can resolve this problem.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
linuxlewiscommented, Jul 11, 2017

The websocket protocol unfortunately does not support the Authorization: header so reusing JWT from your API won’t be quite as easy as you would expect. I would actually keep authentication for the API/websocket separate. My preferred solution to this problem is outlined in more detail here

0reactions
rossmc7commented, Oct 2, 2017

@storerjeremy Hey, how did you get on with this? I was planning on doing the same thing, thanks 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

JSON Web Token Introduction - jwt.io
How do JSON Web Tokens work? In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be...
Read more >
What is JWT (JSON Web Token)? - Blog - miniOrange
On successful authentication, a JWT token is generated and returned, which can be consumed by the app to create a user session. The...
Read more >
JWT authentication: Best practices and when to use it
JWT is a very popular standard you can use to trust requests by using signatures, and exchange information between parties. Make sure you...
Read more >
What Is JWT? How Does It Work? | Akana by Perforce
A common way to use JWTs is as OAuth bearer tokens. In this example, an authorization server creates a JWT at the request...
Read more >
How JSON Web Token(JWT) authentication works? - Medium
JWT is a token based stateless authentication mechanism. Since it is a client-side based stateless session, server doesn't have to ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found