我一直在关注本教程:https ://medium.com/@gerrysabar/implementing-google-login-with-jwt-in-django-for-restful-api-authentication-eaa92e50522d尝试实现基于谷歌的登录从我的前端,到目前为止,一切都在基于谷歌令牌创建帐户,然后使用 RefreshToken.for_user() 创建令牌方面。但是,我尝试通过以下权限类创建一个非常简单的视图来测试我的应用程序:
class VerifyAuthView(APIView):
permission_classes = (IsAuthenticated,)
def post(self,request):
return Response({"status":"true"})
当我尝试访问它时,我收到了 401 错误。我有几个想法可能是这样的:
- 我注意到在令牌下的 django 管理面板中,即使在创建后立即也没有列出,也许令牌只是被生成而不是保存,虽然我不知道为什么
- 我见过几个人说这可能与 rest_framework 权限类有关,尽管到目前为止更改这些并没有帮助
我的 Views.py (也包含我上面的 VerifyAuthView):
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password
from rest_framework.utils import json
from rest_framework.views import APIView,status
from rest_framework.response import Response
import requests
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
class GoogleView(APIView):
def post(self,request):
payload = {'access_token':request.data.get("access_token")} #validating token
req = requests.get('https://www.googleapis.com/oauth2/v2/userinfo',params= payload)
data = json.loads(req.text)
if 'error' in data:
content = {'message': 'Invalid Google Token'}
return Response(content)
email = data['email']
#check if user has authenticated before or not
try:
user = User.objects.get(email=data['email'])
except User.DoesNotExist:
#Create user if they have not logged in before
user = User()
user.username = data['email']
user.password = make_password(BaseUserManager().make_random_password())
user.email = data['email']
user.save()
#Creating access token for user
token = RefreshToken.for_user(user)
response = {}
response['username'] = user.username
response['access_token'] = str(token.access_token)
response['refresh_token'] = str(token)
return Response(response)
在我的 settings.py 中,我的 rest_framework 属性设置如下:
CORS_ORIGIN_ALLOW_ALL = True
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':[
#for demo purposes will need to be changed for privacy concerns
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
我通过 axios 在前端发出请求,如下所示:
const headers = { Authorization: 'Bearer ' + accesstoken};
let res = await axios.post("http://localhost:8000/rest-auth/token/verify-access-token/",
{headers}
);