【发布时间】:2023-03-10 05:27:01
【问题描述】:
我正在尝试将 Firebase 用于我的 django rest / nuxt 项目,并且我需要在用户登录后验证 id 令牌 - 我只将 Firebase 用于身份验证部分。
我的自定义身份验证类如下所示:
class FirebaseAuthentication(authentication.BaseAuthentication):
def authenticate(self, request, **kwargs):
print("Why is this never called")
auth_header = request.META.get("HTTP_AUTHORIZATION")
if not auth_header:
raise NoAuthToken("No auth token provided")
id_token = auth_header.split(" ").pop()
decoded_token = None
try:
decoded_token = auth.verify_id_token(id_token)
except Exception:
raise InvalidAuthToken("Invalid auth token")
pass
if not id_token or not decoded_token:
return None
try:
uid = decoded_token.get("uid")
except Exception:
raise FirebaseError()
user, created = User.objects.get_or_create(email=uid)
user.profile.last_activity = timezone.localtime()
return (user, None)
在我的settings.py 我得到了
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"firebase.authentication.FirebaseAuthentication",
),
}
views.py
@require_POST
def login_view(request):
data = json.loads(request.body)
email = data.get("email")
password = data.get("password")
if email is None or password is None:
return JsonResponse({"detail": "Please provide email and password."}, status=400)
user = authenticate(email=email, password=password)
if user is None:
return JsonResponse({"detail": "Invalid credentials."}, status=400)
login(request, user)
return JsonResponse({"detail": "Successfully logged in.", "isAuthenticated": True})
在我的 nuxt 应用上,登录:
async login() {
this.error = null;
try {
const response = await firebase.auth().signInWithEmailAndPassword(this.email, this.password);
const token = await response.user.getIdTokenResult();
console.log(token.token);
const res = await fetch("/account/login/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"HTTP_AUTHORIZATION": token.token,
"X-CSRFToken": this.$store.getters.CSRFToken
},
credentials: "include",
mode: "cors",
body: JSON.stringify({ email: this.email, password: this.password }),
});
return await res.json()
} catch (error) {
this.error = error;
}
},
我到处都得到 200 - 用户在 firebase 和 django 方面都已登录,但 FirebaseAuthentication 没有被解雇。我错过了什么?
【问题讨论】:
标签: firebase django-rest-framework firebase-authentication django-authentication