在Windows 10中,我正在使用react-router-dom 5.2.0和react-redux 7.2.5和react 17.0.2和axios 0.21.4和WebStorm 2023.1.3 IDE和PyCharm Community Edition 2023.2和djangorestframework==3.14.0和Django==4.2.4和djangorestframework-simplejwt==5.3.0。
1.前台
考虑- axiosInstance.js:
import jwt_decode from 'jwt-decode';
import dayjs from 'dayjs';
import axios from 'axios';
import { AxiosRequestConfig } from 'axios';
import {updateAccessToken} from '../actions/userActions';
const baseURL = 'http://127.0.0.1:8000';
export const axiosInstance = (userInfo , dispatch) => {
const instance = axios.create({
baseURL : baseURL,
headers : {
'Content-Type': 'application/json',
Authorization:`Bearer ${userInfo?.access}`,
}
});
instance.interceptors.request.use(async (req)=> {
const user = jwt_decode(userInfo.access);
const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000;
if (!(isExpired)) {
return req
}
const response = await axios.post(
'/api/v1/users/token/refresh/' , {refresh:userInfo.refresh},
);
dispatch(updateAccessToken(response.data))
req.headers.Authorization = `Bearer ${response.data.access}`;
return req;
});
return instance
}
字符串
考虑-userProfile.js- updateUserProfileAction:
export const updateUserProfileAction = (user) => async (dispatch, getState) => {
try {
dispatch({ // USER UPDATE PROFILE REQUEST
type: USER_UPDATE_PROFILE_REQUEST,
});
const {userLogin: {userInfo}} = getState(); //GET STATE FROM STORE BY KEY `USER_LOGIN`
const authRequestAxios = axiosInstance(userInfo,dispatch)
const {data} = await authRequestAxios.put('http://127.0.0.1:8000/api/v1/users/profile/update/', user)
dispatch({ // USER UPDATE PROFILE SUCCESS
type: USER_UPDATE_PROFILE_SUCCESS, payload: data,
});
dispatch({ //USER LOGIN SUCCESS
type: USER_LOGIN_SUCCESS, payload: data,
});
localStorage.setItem('userInfo', JSON.stringify(data));
} catch (error) {
dispatch({ // USER UPDATE PROFILE FAILED
type: USER_UPDATE_PROFILE_FAILED,
payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
});
}
}
型
考虑-userDetails.js- getUserDetailsAction:
export const getUserDetailsAction = () => async (dispatch , getState) => {
try {
dispatch({
type: USER_DETAILS_REQUEST
});
const {userLogin:{userInfo}} = getState();
const authRequestAxios = axiosInstance(userInfo,dispatch)
const {data} = await authRequestAxios.get(`/api/v1/users/${userInfo._id}/`);
dispatch({
type: USER_DETAILS_SUCCESS,
payload: data,
});
localStorage.setItem('userDetails' , JSON.stringify(data));
} catch (error) {
dispatch({ // USER FURTHER INFORMATION FAILED
type: USER_DETAILS_FAILED,
payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
});
}
}
型
考虑- profile_screen.js:
import React , {useState , useEffect} from "react";
import FormContainer from "../components/FormContainer";
import {Link, useHistory , useLocation} from "react-router-dom";
import {userLoginAction , getUserDetailsAction} from "../actions/userActions";
import {useDispatch , useSelector} from "react-redux";
import Loader from "../components/Loader";
import Message from "../components/Message";
function LoginScreen() {
const dispatch = useDispatch();
const userLogin = useSelector((state) => state.userLogin);
const {error , userInfo , loading } = userLogin;
const history = useHistory();
const location = useLocation();
const redirect = location.search ? location.search.split("=")[1]:'/profile';
const [email , setEmail] = useState('');
const [password , setPassword] = useState('');
const [activateMessage , setActivateMessage] = useState('');
const [expiredMessage , setExpiredMessage] = useState('');
const [invalidMessage , setInvalidMessage] = useState('');
const submitHandler = (e) => {
e.preventDefault();
dispatch(userLoginAction(email , password));
}
useEffect(() => {
if (redirect === "success") {
setActivateMessage(() => "you are activate , please login")
} else if (redirect === "expired") {
setExpiredMessage(() => "you are expired please register again to earn Activate url via your gmail")
} else if (redirect === "invalid") {
setInvalidMessage(() => "you are invalid user , you are not allowed with information to activate , please wait or contacting with website's manager !")
}
if (userInfo) {
history.push(redirect);
}
} , [history , userInfo , redirect])
return (
<>
{userInfo ? "" :
(<FormContainer>
<>
{invalidMessage && (<div className="mb-3">
<div className="alert alert-danger">
{invalidMessage}
</div>
</div>) }
{error && (<div className="mb-3">
<div className="alert alert-danger">
<ul style={{ listStyleType:"none",}} >
<li>1 - email or password is invalid , please careful !!!</li>
<li>2 - do you register ? if , <b>No</b> -> go <Link style={{textDecoration:"none", fontWeight:"bold",}} to="/register" >register page</Link></li>
</ul>
</div>
</div>) }
{expiredMessage && (<div className="mb-3">
<div className="alert alert-danger">
{expiredMessage}
</div>
</div>) }
{activateMessage && (<div className="mb-3">
<div className="alert alert-success">
{activateMessage}
</div>
</div>) }
<div className="mb-3" >login</div>
{loading ? <Loader />:<form onSubmit={(e) => submitHandler(e)} >
<div className="mb-3" >
<label className="form-label" for="email" >email address</label>
<input type="email" className="form-control" placeholder="enter email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="mb-3">
<label className="form-label" htmlFor="password">password</label>
<input type="password" className="form-control" placeholder="enter password"
id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<div className="mb-3 col d-grid gap-1" >
<button type="submit" className="btn btn-info text-white">sign in</button>
</div>
<div className="mb-3" >
<div className="alert alert-info" >do you a new customer ?
<Link to={redirect ? `/register?redirect=${redirect}`:`/register`}>Register</Link>
</div>
</div>
</form>}</>
</FormContainer>)}
</>
)
}
export default LoginScreen;
型
- 我 * 猜测 * 这个 * 错误 * 在
profile_screen.js
中有占用空间,但我 * 猜测 * 是弱 *,但这是一个猜测,让我们解决这个常见错误 * ->(指定的令牌无效)**。
我的问题-> axiosInstance后更新用户配置文件通过操作(箭头功能)-> updateUserProfileAction
显示我在用户的详细信息,通过行动工作(箭头功能)-> getUserDetailsAction
通过raise错误无效的token指定在profile_screen.js
的屏幕中,请帮助我解决它?我猜错误是在axiosInstance.js中的axiosInstance上->请解决它.
1.结束
考虑-settings.py:
第1条:
#### --------------------------- OUR SETTINGS ---------------------------------####
# settings for allowed origins (https://example.com:port)
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000",
]
CORS_ALLOW_METHODS = (
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
)
CORS_ALLOW_HEADERS = (
"accept",
"authorization",
"content-type",
"user-agent",
"x-csrftoken",
"x-requested-with",
)
CSRF_TRUSTED_ORIGINS = [
"http://localhost:3000/",
"http://27.0.0.1:3000/",
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework.authentication.BasicAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
# 'DEFAULT_PERMISSION_CLASSES' : [
# 'rest_framework.permissions.IsAuthenticated' ,
# ]
'DEFAULT_RENDERER_CLASSES': [
# 'rest_framework_yaml.renderers.YAMLRenderer',
'rest_framework.renderers.JSONRenderer',
# 'rest_framework.renderers.AdminRenderer',
# 'rest_framework.renderers.BrowsableAPIRenderer',
],
}
# Django project settings.py (JWT_SYSTEM_SETTINGS)
from datetime import timedelta
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=10),
"REFRESH_TOKEN_LIFETIME": timedelta(days=30),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
"UPDATE_LAST_LOGIN": False,
"ALGORITHM": "HS256",
"SIGNING_KEY": SECRET_KEY,
"VERIFYING_KEY": "",
"AUDIENCE": None,
"ISSUER": None,
"JSON_ENCODER": None,
"JWK_URL": None,
"LEEWAY": 0,
"AUTH_HEADER_TYPES": ("Bearer",),
"AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "user_id",
"USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
"TOKEN_TYPE_CLAIM": "token_type",
"TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",
"JTI_CLAIM": "jti",
"SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
"SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
"SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
"TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer",
"TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer",
"TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer",
"TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer",
"SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer",
"SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer",
}
型
第2条:
from pathlib import Path
import os, sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'my secret key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# my apps
'base.apps.BaseConfig',
'rest_framework',
'corsheaders',
'security',
'rest_framework_simplejwt',
'rest_framework_simplejwt.token_blacklist',
# 'rest_framework_simplejwt.token_blacklistauthentication',
'chat',
'channels',
# default apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'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',
# django-security middleWare
'security.middleware.DoNotTrackMiddleware',
'security.middleware.ContentNoSniff',
'security.middleware.XssProtectMiddleware',
'security.middleware.XFrameOptionsMiddleware',
# cors-headers middleWare
"corsheaders.middleware.CorsMiddleware",
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# ASGI_APPLICATION = 'backend.asgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
# for deploy by run `python manage.py collectstatic` in terminal or cmd in virtual enviroment (example : venv folder)
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'statics/')
MEDIA_URL = 'images/'
MEDIA_ROOT = 'static/images/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
型
考虑- user_views.js:
第1节:
@api_view(http_method_names=['GET'])
@permission_classes([IsAuthenticated])
def get_user(request, user_id):
CustomUser = get_user_model()
user = CustomUser.objects.filter(id=user_id).first()
if request and hasattr(request, "META"):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
else:
x_forwarded_for = False
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
user_ip = ip
user.user_ip = user_ip
user.save()
srz_data = UserSerializerWithToken(instance=user, many=False)
return Response(data=srz_data.data)
型
第2节:
@api_view(http_method_names=['PUT'])
@permission_classes([IsAuthenticated])
def update_profile(request):
CustomUser = get_user_model()
visitor_user = request.user
try:
data = request.data
user = CustomUser.objects.filter(id=data['id']).first()
if user != visitor_user:
return Response({"Permission denied": "you are not the owner"}, status=status.HTTP_401_UNAUTHORIZED)
user.first_name = data['name']
user.last_name = data['family']
user.email = data['email']
user.username = data['email']
if request and hasattr(request, "META"):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
else:
x_forwarded_for = False
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
user_ip = ip
user.user_ip = user_ip
if data['password'] != "":
user.password = make_password(data['password'])
user.save()
serializer = UserSerializerWithToken(instance=user, many=False, partial=True)
return Response(serializer.data, status=status.HTTP_201_CREATED)
# email_exists = CustomUser.objects.filter(email=data['email']).first()
# if email_exists is None:
# user.save()
# serializer = UserSerializerWithToken(instance=user, many=False, partial=True)
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# return Response({"detail": "user with email already exists"}, status=status.HTTP_400_BAD_REQUEST)
except APIException as err:
message = {'detail': str(err)}
return Response(str(err), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
型
我在运行python manage.py migrate
迁移时出错-> 'rest_framework_simplejwt.token_blacklist'
,但几秒钟后自动解决,我代码正确,但给予我常见错误**(指定的令牌无效)在FRONTEND**,请帮助我解决.
try:
pass
except APIException as err:
pass
型
在功能视图def get_user(request, user_id):
atuser_views.pywhom withAPIconnect toFRONTENDbyreactjsatarrow function-> getUserDetailsAction
that it给予me same error**(指定的令牌无效)在更新用户配置文件后的屏幕中,通过操作执行更新(react-redux)->arrow function -> userFurtherInformationAction
,这个arrow function的动作是通过API(djangorest API)连接到def update_profile(request):
,在后端**通过django.
1条答案
按热度按时间b09cbbtk1#
哦,是的,我解决了它!我应该改变
Bearer ${response.data.access}
到Bearer ${response.data.token}
,所以改变Authorization:'Bearer ${userInfo.access}',
到Authorization:'Bearer ${userInfo.token}',
考虑axiosInstance.js:
字符串
事实上,我让
Authorization:'Bearer ${userInfo.access}',
在第一次请求服务器**(后端)后将其更改为空字符串,* 通过django和django-rest-framework和django-rest-frame-work-simplejwt在此 Web应用程序 * 和jwt_decode()
模块中 * 实现 ,只接受验证jwt-token,对于空字符串返回相同的常见错误(指定的token无效)因为,这里token为空**,未验证,所以jwt_decode()
模块无法解析好,引发此错误。幸运的是,对于这个问题,我在django后端的serializers.py中有很好的实现-考虑:
第1节:
型
在节1i编程类->
class UserSerializer(serializers.ModelSerializer):
作为此Web应用程序的活动用户,但此系统在simplejwt*(对于django)* once generatejwt_tokenin login and after first login access and refresh token do not generate jwt so I programmingsection 2that it is aclass**->UserSerializerWithToken(UserSerializer):
whom thisclass继承父类classinsection 1and has special method ->def get_token(self, obj):
-考虑:型
该方法在每个请求中生成访问令牌,因此
Authorization:'Bearer ${userInfo.token}',
不是空的,并且jwt_decode()
正确地解析它。第2节:
型
更多信息->我的代码中有错误,因为在方法->
def get_token(self, obj):
中我只获得访问令牌,但我也应该获得刷新令牌->所以:考虑:型
而是:
型
我应该兼容我的应用程序与此脚本和访问,而不是刷新和访问,*simplejwt 生成 * 一次后登录用户,并将其发送到还原React在前端