Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?

huangapple go评论72阅读模式
英文:

Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?

问题

以下是要翻译的内容:

我在我的Django应用程序上使用了jwt身份验证。当用户登录我的网站时,我的服务器会将jwt令牌和刷新令牌发送到浏览器的cookie中,但我收到了"用户未经身份验证"的错误,并且在我的"user_profile/" API端点中没有获取到任何个人资料数据。

甚至在用户登录后,我也可以在浏览器的cookie中看到jwt令牌和刷新令牌,还有在我的axios请求中使用了{withCredentials:true}

以下是我的登录代码:

@api_view(['POST'])
def user_login(request):
    if request.method == 'POST':
        
      ...其他代码    
        refresh = RefreshToken.for_user(user)
        response = Response({'message': '登录成功。'}, status=status.HTTP_200_OK)
        response.set_cookie('jwt_token', str(refresh.access_token))
        response.set_cookie('refresh_token', str(refresh))
         
        return response
    
    else:
         return Response({'error': '无效的凭据。'}, status=status.HTTP_401_UNAUTHORIZED)

以下是获取用户个人资料的API:

@api_view(['GET'])
def get_user_profile(request):
    if request.user.is_anonymous:
        return Response({'error': '用户未经身份验证。'}, status=status.HTTP_401_UNAUTHORIZED)
    
    user = request.user
    profile = Profile.objects.get(user=user)
    data = {
        'username': user.username,
         
    }
    return Response(data, status=status.HTTP_200_OK)

我的settings.py配置:

REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',  
    'DEFAULT_AUTHENTICATION_CLASSES': (
       
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    
}

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    
}

我的前端代码:

axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true})
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.error(error);
      });

您可以看到我的API是正常工作的。

英文:

I am using jwt authentication on my Django app. When user login to my website my server sends jwt token and refresh token to the browser cookie but I am getting "User is not authenticated." error and not getting any profile data for my user_profile/ api endpoint.

Even I can see jwt token and refresh token also avaiable on the browser cookie after user login and aslo {withCredentials:true} in my axois post.

Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?

here is my login code:

@api_view(['POST'])
def user_login(request):
    if request.method == 'POST':
        
      ...others code    
        refresh = RefreshToken.for_user(user)
        response = Response({'message': 'Login successful.'}, status=status.HTTP_200_OK)
        response.set_cookie('jwt_token', str(refresh.access_token))
        response.set_cookie('refresh_token', str(refresh))
         
        return response
    
    else:
         return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)

here is my api for get user profile

@api_view(['GET'])
def get_user_profile(request):
    if request.user.is_anonymous:
        return Response({'error': 'User is not authenticated.'}, status=status.HTTP_401_UNAUTHORIZED)
    
    user = request.user
    profile = Profile.objects.get(user=user)
    data = {
        'username': user.username,
         
    }
    return Response(data, status=status.HTTP_200_OK)

my settings.py

REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',  
    'DEFAULT_AUTHENTICATION_CLASSES': (
       
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    
}

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    
}

my frontend code:

 axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true})
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.error(error);
      });
  })

;

you can see my api is working

Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?

答案1

得分: 1

你需要在请求的头部设置JWT令牌。您可以使用axios.interceptors.request来在头部设置令牌。

axios.interceptors.request.use(
  (config) => {
    const token = getToken(); // getToken将从Cookie中返回令牌
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

您可以在发送请求时直接将令牌设置到头部。

axios.get(`${CustomDomain}/user_profile/`, { withCredentials: true, headers: { Authorization: `Bearer ${getToken()}` } })
  .then((res) => {
    console.log(res);
  })
  .catch((error) => {
    console.error(error);
  });

getToken是一个函数,将从Cookie中返回JWT访问令牌。

import cookie from "cookiejs";  // npm i cookiejs
const getToken = () => cookie.get("jwt_token");
英文:

You need to set JWT token in headers of request. You can use axios.interceptors.request to set token in headers

axios.interceptors.request.use(
  (config) => {
    const token = getToken(); // getToken will return token from cookie
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

You can directly set token to header while sending request

axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true, headers:{Authorization: `Bearer ${getToken()}`}})
  .then((res) => {
    console.log(res);
  })
  .catch((error) => {
    console.error(error);
  });

})

getToken is a function which will return JWT access token from cookie

import cookie from "cookiejs";  // npm i cookiejs
const getToken = () => cookie.get("jwt_token")

huangapple
  • 本文由 发表于 2023年6月19日 22:12:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定