Giter Site home page Giter Site logo

eadwincode / django-ninja-jwt Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jazzband/djangorestframework-simplejwt

124.0 124.0 20.0 5.5 MB

A JSON Web Token authentication plugin for the Django REST Framework.

Home Page: https://eadwincode.github.io/django-ninja-jwt/

License: MIT License

Python 99.47% Makefile 0.53%
django-jwt django-ninja django-ninja-extra django-rest-framework drf-jwt jwt jwt-authentication pyjwt pyjwt-django simplejwt

django-ninja-jwt's Introduction

Hi there 👋

Welcome to my github page😄

django-ninja-jwt's People

Contributors

2ykwang avatar adrianodidio avatar ajhodges avatar andrew-chen-wang avatar code-yeongyu avatar damellp avatar davesque avatar demiurg avatar dependabot[bot] avatar dgmouris avatar dzonecat avatar eadwincode avatar fabianlange avatar felixxm avatar fergyfresh avatar ghazi-git avatar hramezani avatar jezdez avatar johnthagen avatar jpadilla avatar lausek avatar llorenspujol avatar m2mbr avatar mateusz-slisz avatar rencesar avatar robrichter avatar sayatp avatar t-io avatar waketzheng avatar xrmx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

django-ninja-jwt's Issues

Add documentation for customizing the fields for authentication

I'm having a hard time trying to change the username field to become email, and use it for validation instead. It would be useful to have a tutorial for making modifications like these in the docs.

I thought it would be on customizing_token_claims.md, but it just adds the field without validating it, and username is still required.

The fields required for generating a token.

Hello, when calling the "http://localhost:8000/api/token/pair" endpoint, I need to provide username and password. However, my User model does not have the password field. How can I modify this without changing the source code?

I only know how to make modifications here, but I prefer not to modify the source code:

class TokenObtainInputSchemaBase(ModelSchema, TokenInputSchemaMixin):
    class Config:
        # extra = "allow"
        model = get_user_model()
        model_fields = ["password", user_name_field]

error detail bad formatted

I'm using the router authentication

code: https://gist.github.com/pedrohsbarbosa99/8e42e54466ef62e0ba439d5177d99db7

OBS: using ninja.errors.ValidationError directly produce:

{
  "detail": {
    "email": "email is required"
  }
}

When I call /pair, the exception, the ninja_jwt.ValidationError produce the following error:

{
  "detail": "{'email': ErrorDetail(string='email is required', code='invalid')}"
}

Curl example:

curl -X 'POST' \
  'http://127.0.0.1:8000/api/pair' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "password": "string"
}'

And ninja_jwt.AuthenticationFailed

{
  "detail": "{'detail': ErrorDetail(string='Usuário e/ou senha incorreto(s)', code=''), 'code': ErrorDetail(string='', code='')}"
}

Curl example:

curl -X 'POST' \
  'http://127.0.0.1:8000/api/pair' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "password": "wrong",
  "email": "wrong"
}'

Bug Report: Inconsistent Response Format for User Authentication in Django


Description

I am implementing a user authentication system in Django, utilizing a standard response format for all API responses. This standard format includes message, success, data, and trace_id. While this format is correctly applied for successful authentication, it fails to be consistent for authentication errors.

Expected Behavior

For both successful and failed authentication attempts, the response should adhere to the following format:

{
  "message": "string or null",
  "success": true or false,
  "data": { /* relevant data or empty */ },
  "trace_id": "string"
}

Current Behavior

  • get token request
curl -X 'POST' \
  'http://127.0.0.1:8000/api/token/pair' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "password": "12345",
  "username": "testuser"
}'
  • Successful Authentication Response:

    {
      "message": null,
      "success": true,
      "data": {
        "refresh": "token",
        "access": "token",
        "user": {
          "first_name": "name",
          "email": "email"
        }
      },
      "trace_id": "string"
    }

    This response is as per the expected format.

  • Failed Authentication Response:

    {
      "detail": "{'detail': ErrorDetail(string='No active account found with the given credentials', code=''), 'code': ErrorDetail(string='', code='')}",
      "trace_id": "string"
    }

    This response does not match the standard format, particularly lacking the message and success fields.

  • refresh token request

curl -X 'POST' \
  'http://127.0.0.1:8000/api/token/pair' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "password": "12345",
  "username": "testuser"
}'
  • refresh token response
{
  "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwMDE1MzQ4OCwiaWF0IjoxNzAwMDY3MDg4LCJqdGkiOiIzMjU4YjNiYTkyNGE0MjJjOGJiYWRkOTViOTM0MzU1MCIsInVzZXJfaWQiOjF9.tBbo_coSHRo96XmSmdZQjl-Gf2VH5QXb0ZN1AFd_CeA",
  "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzAwMDY3NDcwLCJpYXQiOjE3MDAwNjcwODgsImp0aSI6ImQ0YWY0MzcyYWMzYjQzNzliZGNhYzg4ZjBiZmU0ZGYyIiwidXNlcl9pZCI6MX0.u6ryxuI_kn9RJXK9QJAVcqJSLqPlJeJRqgmQYgdu_9Y",
  "trace_id": "680dc33ef9c149919b6a9ec15d653d16"
}

Code Snippets

  • Custom Schema for Responses:
# core.schemas.py
from pydantic.generics import GenericModel

class ErrorMsg(BaseModel):
    message: Optional[str] = None
    success: bool = True

GenericResultsType = TypeVar("GenericResultsType")


class StandResponse(ErrorMsg, GenericModel, Generic[GenericResultsType]):
    data: GenericResultsType
# custom_token_out.py
from core.schemas import StandResponse

class MyTokenObtainPairOutSchema(Schema):
    refresh: str
    access: str
    user: UserSchema

class MyTokenObtainPairInputSchema(TokenObtainInputSchemaBase):
    @classmethod
    def get_response_schema(cls) -> Type[Schema]:
        return StandResponse[MyTokenObtainPairOutSchema]

  @classmethod
  def get_token(cls, user) -> Dict:
      values = {}
      refresh = RefreshToken.for_user(user)
      values["refresh"] = str(refresh)
      values["access"] = str(refresh.access_token)
      values.update(
          user=UserSchema.from_orm(user)
      )
      return {'data': values}

Steps to Reproduce

  1. Configure the Django application with the mentioned response format.
  2. Implement custom user authentication handling with the provided schemas.
  3. Authenticate with valid credentials to observe the correct format.
  4. Authenticate with invalid credentials to observe the deviation.

Possible Solution

I need guidance on customizing the response format for failed authentication attempts to conform to our standard response format. This might involve modifying the exception handling process within the Django authentication framework or adjusting our custom schema.


Customized input fields

Hello, I'd like to obtain the pair of keys but instead of having just username and password, I need to have a more complexe structure (because I'm building a mobile app).

To better illustrate, here is a simple unit test:

class UserAuthTest(TestCase):
    def test_user_login(self):
        user = User.objects.create_user(
            phone_number="+1234567890",
            password="12345",
        )
        device = DeviceFactory(user=user)
        response = self.client.post(
            "/api/v1/token/pair",
            {
                "user": {"phone_number": "+1234567890", "password": "12345"},
                "device": {"vendor_uuid": device.vendor_uuid},
            },
            content_type="application/json",
        )
        json = response.json()
        self.assertEqual(json, {
            "id": "some-id",
            "access": "accesstoken",
            "is_new_user": False,
            "is_new_device": False,
            "user": {
                "uuid": user.uuid,
            },
            "device": {
                "uuid": device.uuid,
            }
        })
        self.assertEqual(response.status_code, 200)

I override the schema

class UserSchema(Schema):
    uuid: UUID


class MyTokenObtainPairOutSchema(Schema):
    refresh: str
    access: str
    user: UserSchema


class TokenSessionInputSchema(TokenObtainPairInputSchema):

    def output_schema(self):
        out_dict = self.get_response_schema_init_kwargs()
        out_dict.update(user=UserSchema.from_orm(self._user))
        return MyTokenObtainPairOutSchema(**out_dict)

    @classmethod
    def validate_values(cls, values: Dict) -> Dict:
        user = values["user"]
        return {**values, "user": super().validate_values(user)}

However I got the following error:
{'detail': [{'type': 'missing', 'loc': ['body', 'user_token', 'password'], 'msg': 'Field required'}, {'type': 'missing', 'loc': ['body', 'user_token', 'phone_number'], 'msg': 'Field required'}]}.

In the return of validate_values, he doesn't find the password and phone_number field. So when fixing the validate_values function like following

@classmethod
def validate_values(cls, values: Dict) -> Dict:
        user = values["user"]
        return super().validate_values(user)

I got another error: pydantic_core._pydantic_core.ValidationError: 1 validation error for NinjaResponseSchema response.phone_number but I did not specify phone_number for django-ninja-jwt so I don't know how did he found phone_number.

Well sorry for this long issue. I tried debugging but I don't know how to configure a custom input (and not only username and password) and keep the data inside the classes to have custom behavior (for example creating a device when there is none in the database).

Thanks for your help.

How to get user groups

How can I get the groups of a user when getting the TokenPair?

This is what I tried but I get an empty groups list as result for user = UserSchema.from_orm(self._user)

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from ninja_extra import api_controller, route
from ninja_jwt.controller import TokenObtainPairController
from ninja_jwt.schema import TokenObtainPairSerializer
from ninja_schema import ModelSchema, Schema

User = get_user_model()


class GroupSchema(ModelSchema):
    class Config:
        model = Group
        include = ("name",)

class UserSchema(Schema):
    first_name: str
    last_name: str
    username: str
    email: str
    groups: list[GroupSchema]

class TokenObtainPairOutSchema(Schema):
    refresh: str
    access: str
    user: UserSchema

class TokenObtainPairSchema(TokenObtainPairSerializer):
    def output_schema(self):
        out_dict = self.get_response_schema_init_kwargs()
        user = UserSchema.from_orm(self._user)
        out_dict.update(user=user)
        return TokenObtainPairOutSchema(**out_dict)

@api_controller("/auth/token", tags=["Auth"])
class CustomTokenObtainPairController(TokenObtainPairController):
    auto_import = True
    @route.post("/pair", response=TokenObtainPairOutSchema, url_name="token_obtain_pair")
    def obtain_token(self, user_token: TokenObtainPairSchema):
        return user_token.output_schema()

social login

Any plans/ideas how to integrate all auth or something that help accomplish google/fb/etc login?

Operation IDs have ugly prefixes that change across runs

Problem

Django Ninja JWT does not explicitly set the operation ID parameter, so it is partially auto-generated. When the OpenAPI schema is generated, this results in ugly names for the operation IDs like 99fab5a9_controller_refresh_token and 1ba7e0e7_controller_verify_token and so on. I would also argue that controller is an implementation detail and should not be a part of the name. My preferred operation IDs would simply refresh_token, verify_token and so on, very similar to what is already defined for the url_name.

You could argue that these ugly operation IDs might not be a problem, but the reason I care is that I use codegen tools to generate a TypeScript schema for my frontend. The naming of the generated methods are based on the operation IDs, so this is a big issue. Also, the prefix seems to not be consistent across runs but change, which is an issue when re-running the codegen.

Proposed Solution

Explicitly set the operation_id parameter for TokenObtainPairController, AsyncTokenObtainPairController, etc. If you are worried about naming conflicts, the operation IDs could be prepended with some value the user defines in the NINJA_JWT settings.

Resolver gets called twice

I am adding a 'user' key to the token claims with the user data including its permissions. Following exactly this I get the tokens with no problem. But resolving the permissions raises a ValidationError, and I realized that the resolver gets called twice:
-first time the obj is a User instance and context is None, so no problem for getting the permission list
-the second time obj is not a User but a ModelAuthReadSchema instance and context is not None but its user is a AnonymousUser, and here comes the errors

this is my schema for User where AuthModel is just get_user_model()

class ModelAuthReadSchema(ModelSchema):
    permissions: List[str] | None

    class Meta:
        model = AuthModel
        fields = ['id', 'username', 'first_name', 'last_name', 'email']

    @staticmethod
    def resolve_permissions(obj, context):
        return get_permissions(obj)

get_permissions is a custom function for getting just business-related permissions

this is the error:

pydantic_core._pydantic_core.ValidationError: 3 validation errors for NinjaResponseSchema
response.refresh
  Field required [type=missing, input_value=<DjangoGetter: LoginInput...', username='cccccc')>, input_type=DjangoGetter]
    For further information visit https://errors.pydantic.dev/2.6/v/missing
response.access
  Field required [type=missing, input_value=<DjangoGetter: LoginInput...', username='cccccc')>, input_type=DjangoGetter]
    For further information visit https://errors.pydantic.dev/2.6/v/missing
response.user
  Field required [type=missing, input_value=<DjangoGetter: LoginInput...', username='cccccc')>, input_type=DjangoGetter]
    For further information visit https://errors.pydantic.dev/2.6/v/missing

this would be the desired output:

{
  "refresh": "xxxxxxxxxxx",
  "access": "yyyyyyyyyyy",
  "user": {
    "permissions": [
      "app_label1.add_model",
      "app_label2.delete_model"
    ],
    "id": 1,
    "username": "ccccccc",
    "first_name": "",
    "last_name": "",
    "email": "[email protected]"
  }
}

`AuthenticationFailed` exception class does not return correct error code

I couldn't create a pull request for the issue due to limited time but it seems like built-in AuthenticationFailed exception class has an inheritance order issue.

https://github.com/eadwinCode/django-ninja-jwt/blob/master/ninja_jwt/exceptions.py#L35

This class doesn't get default_code attribute from AuthenticationFailed exception, instead it gets from DetailDictMixin class which is empty string.

my implementation:

@api_controller("/auth", tags=["auth"])
class UserTokenController(TokenObtainSlidingController):
    auto_import = True

    @route.post("/login", response=UserTokenOutSchema, url_name="login")
    def obtain_token(self, user_token: jwt_schemas.TokenObtainSlidingInputSchema):
        user = user_token._user
        token = SlidingToken.for_user(user)
        return UserTokenOutSchema(
            user=user,
            token=str(token),
            token_exp_date=datetime.fromtimestamp(token["exp"], tz=timezone.utc),
        )
{
  "detail": "No active account found with the given credentials",
  "code": ""
}

Thanks

How can I use this to verify Auth0 token?

Below is a working example from Django Rest Framework:


REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'EXCEPTION_HANDLER': 'messages_api.views.api_exception_handler',
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',
    ],
}

# JWT

AUTH0_DOMAIN = get_env_var('AUTH0_DOMAIN')
AUTH0_AUDIENCE = get_env_var('AUTH0_AUDIENCE')

SIMPLE_JWT = {
    'ALGORITHM': 'RS256',
    'JWK_URL': f'https://{AUTH0_DOMAIN}/.well-known/jwks.json',
    'AUDIENCE': AUTH0_AUDIENCE,
    'ISSUER': f'https://{AUTH0_DOMAIN}/',
    'USER_ID_CLAIM': 'sub',
    'AUTH_TOKEN_CLASSES': ('authz.tokens.Auth0Token',),
}


class ProtectedMessageApiView(MessageApiView):
    text = "This is a protected message."
    permission_classes = [IsAuthenticated]

Now, how to make it check that the Auth0 is correct and protect the below view until the Auth0 is verified:

@router.get("/protected", response={200: MessageSchema, 403: ErrorResponse})
def protected_message(request):
    if not request.auth:
        return ErrorResponse(message="User is not authenticated"), 403
    return get_message("This is a protected message.")

Outdated doc for customized token claim after upgrade to 5.2.10.

I'm getting a ValidationError after updating to Pydantic 2.5, django-ninja 1.0.1, django-ninja-extra 0.20.0, django-ninja-jwt 5.2.10.

The error states that no access or refresh token are being given in the result dict:

self = ObtainPairSchema(password='password-140422694852304', username='user-140422694852304')

    def output_schema(self):
        result = self.dict(exclude={"password"})
        result.update(user=UserSchema.from_orm(self._user))
>       return ObtainPairOutputSchema(**result)
E       pydantic_core._pydantic_core.ValidationError: 2 validation errors for ObtainPairOutputSchema
E       refresh
E         Field required [type=missing, input_value=<ninja.schema.DjangoGette...bject at 0x7fb6b49e44c0>, input_type=DjangoGetter]
E           For further information visit https://errors.pydantic.dev/2.5/v/missing
E       access
E         Field required [type=missing, input_value=<ninja.schema.DjangoGette...bject at 0x7fb6b49e44c0>, input_type=DjangoGetter]
E           For further information visit https://errors.pydantic.dev/2.5/v/missing

The code is roughly this.

schema.py:

import typing as t

from ninja import Schema
from ninja_jwt.schema import TokenObtainInputSchemaBase, TokenObtainPairInputSchema


class UserSchema(Schema):
    id: int
    username: str
    is_superuser: bool
    first_name: str | None
    last_name: str | None
    email: str | None


class ObtainPairOutputSchema(Schema):
    refresh: str
    access: str
    user: UserSchema


class ObtainPairBaseSchema(TokenObtainPairInputSchema):
    def output_schema(self):
        result = self.dict(exclude={"password"})
        result.update(user=UserSchema.from_orm(self._user))
        return ObtainPairOutputSchema(**result)


class ObtainPairSchema(ObtainPairBaseSchema):
    pass


class ObtainPairInputSchema(TokenObtainInputSchemaBase):
    @classmethod
    def get_response_schema(cls) -> t.Type[Schema]:
        return ObtainPairOutputSchema

The controller is like:

@api_controller("/token", tags=["token"])
class ObtainPairController(TokenObtainPairController):
    @route.post("/pair", response=ObtainPairOutputSchema, url_name="token_obtain_pair")
    def obtain_token(self, user_token: ObtainPairSchema):
        result = user_token.output_schema()
        if isinstance(user := user_token._user, AbstractBaseUser):
            if not user.is_anonymous and user.is_superuser:
                request: HttpRequest = self.context.request  # type: ignore
                login(request, user)
        return result

and the test that fails is:

class TestJWTLoginv2023(MagicAPITestCase):
    def setUp(self):
        super().setUp()
        User = get_user_model()
        self.username = username = f"user-{id(self)}"
        self.password = password = f"password-{id(self)}"
        self.user = User.objects.create_user(username, password=password)  # type: ignore

    def test_can_obtain_token_for_existing_user(self):
        response = self.client.post(
            "token/pair",
            data={"username": self.username, "password": self.password},
            content_type="application/json",
        )
        self.assertHTTPOk(response)

(The MagicAPITestCase simply takes the version from the name of the class).

In settings.py, I have:

NINJA_JWT = {
   ...
   "TOKEN_OBTAIN_PAIR_INPUT_SCHEMA": "accounts.schema.ObtainPairInputSchema",
   ...
}

Unable To Customize Token Claims on TOKEN_VERIFY_INPUT_SCHEMA

Hello, I have an issue with modifying the token claims when using /verify/. I followed through the docs to modify TOKEN_VERIFY_INPUT_SCHEMA

By default, the verify's response is {} and I wanted to add refresh, access, and user there.

from ninja_jwt.schema import (
    TokenObtainInputSchemaBase,
    TokenVerifyInputSchema,
    InputSchemaMixin,
)

class CustomVerifyInputSchema(TokenVerifyInputSchema, InputSchemaMixin):
    token: str

    @classmethod
    def get_response_schema(cls) -> Type[Schema]:
        return CustomVerifyOutSchema

    def to_response_schema(self):
        try:
            access_token = AccessToken(self.token)
            user_id = access_token["user_id"]

            User = get_user_model()
            user = User.objects.get(id=user_id)
            user_schema = UserSchema.from_orm(user)

            values = {
                "refresh": "your_refresh_token_here", 
                "access": self.token,
                "user": user_schema.dict(),
            }

           return values
        except (KeyError, ValidationError, get_user_model().DoesNotExist) as e:
            raise e

I've also defined it in settings.py of course.

Token lifetime dynamic change

I want to implement remember_me functionality into jwt. Users that have remember_me=True should have Refresh token lifetime set to 90 days. How to implement that?

Refresh Token never expires

settings.py

...
NINJA_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(seconds=30),
    "REFRESH_TOKEN_LIFETIME": timedelta(minutes=1),
}
...

I set the lifetime really low to test if the token expires. The access token is not usable after 30 seconds but the refresh token is usable as long as I want it to. Why is that?

When I request my api like that

curl \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"}' \
  http://localhost:8000/api/token/refresh/

And following is the response:

{
  "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4",
  "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzExNDg5MjE0LCJpYXQiOjE3MTE0ODU4NTQsImp0aSI6IjIyNzEwYTI1YzBiNTRiNTJhNzI0NWM5M2ZjNjFjMDMzIiwidXNlcl9pZCI6ImMzODM1OWE5LTIyOTgtNDY5NC04MzVjLTJmZWIzOGRjNjQ4MCJ9.MDTzwh3LRTpKzueqJDbwEh82uDtuJ1MqUD6KJpJ47-c"
}

The response differs from what I can read here, which says the response looks like that:

{"access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNTY3LCJqdGkiOiJjNzE4ZTVkNjgzZWQ0NTQyYTU0NWJkM2VmMGI0ZGQ0ZSJ9.ekxRxgb9OKmHkfy-zs1Ro_xs1eMLXiR17dIDBVxeT-w"}

Am I doing something wrong or is this unintentional?

flushexpiredtokens management command confusion

@eadwinCode, what's the purpose of running a cronjob daily to run the flushexpiredtokens as stated in the docs? (https://eadwincode.github.io/django-ninja-jwt/blacklist_app/). The Docs say:

The blacklist app also provides a management command, flushexpiredtokens, which will delete any tokens from the outstanding list and blacklist that have expired. You should set up a cron job on your server or hosting platform which runs this command daily.

Wouldn't you want the expired tokens to persist for some time so that if someone gains access to an expired token, ninja_jwt will check it against the blacklist?

Maybe I'm confused on the wording in the docs.

Thanks!

Suggestion to add router authentication funcion based

Hi,

I'm think about built-in support for funcion router authentication.

I'm able to help to execut it.

But I have some question about the project organization.

If you think this is a good idea, tel me.

Example:

from ninja import NinjaAPI

from ninja_jwt.auth.routers import obtain_token_router

api = NinjaAPI()

...
api.add_router("", obtain_token_router, tags=["auth"])

Django 5.0b1 incompatibility

  File "/Users/jaddison/projects/myproj/api/project/views/urls.py", line 7, in <module>
    from project.views.api.urls import api
  File "/Users/jaddison/projects/myproj/api/project/views/api/urls.py", line 6, in <module>
    from ninja_jwt.authentication import AsyncJWTAuth
  File "/Users/jaddison/projects/myproj/api/venv/lib/python3.11/site-packages/ninja_jwt/authentication.py", line 12, in <module>
    from .tokens import Token
  File "/Users/jaddison/projects/myproj/api/venv/lib/python3.11/site-packages/ninja_jwt/tokens.py", line 13, in <module>
    from .utils import aware_utcnow, datetime_from_epoch, datetime_to_epoch, format_lazy
  File "/Users/jaddison/projects/myproj/api/venv/lib/python3.11/site-packages/ninja_jwt/utils.py", line 9, in <module>
    from django.utils.timezone import is_naive, make_aware, utc
ImportError: cannot import name 'utc' from 'django.utils.timezone' (/Users/jaddison/projects/myproj/api/venv/lib/python3.11/site-packages/django/utils/timezone.py)

From Django 4.1's release deprecation notes:

The django.utils.timezone.utc alias to datetime.timezone.utc is deprecated. Use datetime.timezone.utc directly.

From Django 5.0's release notes:

The django.utils.timezone.utc alias to datetime.timezone.utc is removed.

Refresh sliding token

Hi,
I have problem with sliding tokens.

The problem I'm running into is that I can only refresh the token while the auth expiration claim is valid. When auth exp pass and refresh_exp is still in future i cant refresh the token.

I have done little bit research of this library so the problem is the token is getting decoded only by exp time, same as for access/refresh token, so for sliding token he doesn't look at all at refresh_exp time

issue related to jazzband#154

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.