我使用的是基于JWT令牌的身份验证系统。即我后端的djangorestframework-simplejwt
现在我使用reactj和axios作为前端:
在向login api提供用户名和传递后,我获得了access_token和refresh_token,并将它们存储在本地存储中
现在,我正在尝试使用access_token连接到api。
我得到了Token invalid or expired
例如,我正在尝试使用此接口更改密码并提供access_token
const url = "dj-rest-auth/password/change/";
const auth = {
headers: {
Authorization: "Bearer " + localStorage.getItem("access_token"),
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
old_password: old_password,
new_password1: new_password1,
new_password2: new_password2,
};
const promise = axios.post(url, data, auth);
promise
.then((res) => {
console.log(res)
})
.catch((err) => {
if (err.response) {
console.log(`${err.response.status} :: ${err.response.statusText}`)
console.log(err.response.data)
}
})当我遇到错误时,我可以使用refresh_token进行另一个api调用来获取access_token。
但有时,错误可能是由于网络错误或其他原因造成的。然后,即使我尝试使用refresh_token获取access_token,它也会陷入循环。
HOw以正确的方式做到这一点
发布于 2021-09-01 08:22:48
身份验证={ 'DEFAULT_AUTHENTICATION_CLASSES':'dj_rest_auth.jwt_auth.JWTCookieAuthentication‘}
REST_SESSION_LOGIN = False SITE_ID=1 REST_USE_JWT = True JWT_AUTH_COOKIE =‘访问令牌’#any name JWT_AUTH_REFRESH_COOKIE = 'refresh_token‘#any name JWT_AUTH_SECURE = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True
从django.utils.deprecation导入json从yourapp.settings导入MiddlewareMixin从settings.py导入JWT_AUTH_REFRESH_COOKIE #
class MoveJWTRefreshCookieIntoTheBody(MiddlewareMixin):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, *view_args, **view_kwargs):
if request.path == '/token/refresh/' and JWT_AUTH_REFRESH_COOKIE in request.COOKIES:
if request.body != b'':
data = json.loads(request.body)
data['refresh'] = request.COOKIES[JWT_AUTH_REFRESH_COOKIE]
request._body = json.dumps(data).encode('utf-8')
else:
print("The incoming request body must be set to an empty object.")
return None前端:
rest响应将是令牌,默认情况下它将存储在 cookie中,因为我们使用的是dj-
python manage.py运行服务器localhost:8080
dj-rest-auth:https://dj-rest-auth.readthedocs.io/en/latest/index.html
https://stackoverflow.com/questions/68677181
复制相似问题