【问题标题】:Django: Use both session and jwt middlewares at a timeDjango:一次使用会话和 jwt 中间件
【发布时间】:2018-06-21 04:16:10
【问题描述】:

我同时使用了 JWT 和会话身份验证中间件。

我发现我无法登录管理员。后来当我删除 JWT 中间件时,它起作用了。

我的网站将同时用作 api 登录和普通浏览器登录。如何同时使用它。

剩下的唯一选项是 jwt 的以下条件。

if request.content_type == 'application/json':

如何解决这个问题

我没有使用 DRF 创建 api 端点。这就是为什么我必须创建自定义中间件来验证 JWT 令牌

Django 设置:

MIDDLEWARE = (
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'webarticles.middleware.jwtWebtoken_mod.BaseJSONWebTokenAuthentication_mod',
)

webarticles.middleware.jwtWebtoken_mod.BaseJSONWebTokenAuthentication_mod

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import exceptions
import json
from django.http import HttpResponse
from rest_framework.settings import api_settings as api_settings2
from rest_framework_jwt.settings import api_settings

jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER

class BaseJSONWebTokenAuthentication_mod(JSONWebTokenAuthentication):
    """
    Token based authentication using the JSON Web Token standard.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.content_type == 'application/json':
            try:
                user_auth_tuple = self.authenticate(request)
            except exceptions.APIException as e:
                self._not_authenticated(request)
                hare = e.get_full_details()
                #hare = {"e": str(e)}
                # return  HttpResponse(
                #                 json.dumps(hare),
                #                 content_type="application/json"
                #             )
                return HttpResponse(
                                json.dumps(hare),
                                content_type="application/json",
                                status=e.status_code
                            )

            if user_auth_tuple is not None:
                request._authenticator = self
                request.user, request.auth = user_auth_tuple
            else:
                self._not_authenticated(request)

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

    def _not_authenticated(self,request):
        """
        Set authenticator, user & authtoken representing an unauthenticated request.

        Defaults are None, AnonymousUser & None.
        """
        request._authenticator = None

        if api_settings2.UNAUTHENTICATED_USER:
            request.user = api_settings2.UNAUTHENTICATED_USER()
        else:
            request.user = None

        if api_settings2.UNAUTHENTICATED_TOKEN:
            request.auth = api_settings2.UNAUTHENTICATED_TOKEN()
        else:
            request.auth = None

目前我已将以下条件进行管理

if request.content_type == 'application/json':

【问题讨论】:

  • 我希望你正在使用 Django REST 框架作为 API,显示你的 settings.py

标签: django


【解决方案1】:

使用 Postman 发出请求,一旦您成功发出请求。按右侧的code按钮生成代码。

我已经从邮递员制作了这个 node.js 脚本来登录特定的网站。

var request = require("request");

var options = { 
  method: 'POST',
  url: 'http://abc.xyz.com/',
  headers: 
   { 
     'postman-token': 'xxxx-xxxx-xx-xx-xxx',
     'cache-control': 'no-cache',
      authorization: 'Basic xxxxxxxxxxxxxxxxxxxxx',
      'content-type': 'application/json' 
   },

  body: 
  { 
     username: 'yourusername.com',
     password: 'Your@password' 
  },

  json: true 

 };

request(options, function (error, response, body) 
{
  if (error) throw new Error(error);

  console.log(body);
});

【讨论】:

  • 是 'content-type': 'application/json' 唯一的方法还是有其他方法
猜你喜欢
  • 2018-09-26
  • 2023-03-18
  • 1970-01-01
  • 2023-03-13
  • 2018-06-21
  • 2020-02-13
  • 1970-01-01
  • 2020-06-18
  • 2010-12-25
相关资源
最近更新 更多