こんにちは!
日本語は第二言語なので、文法の間違いがあれば、あらかじめ謝っておきます。
このビデオに従って、私はDjango REST Framework + Next.js + NextAuthをGoogle認証で実装しようとしています。
https://www.youtube.com/watch?v=TvoMjY291f8
ビデオの指示に従ったのですが、「IDトークン」で問題が発生しています。このサイトの他の質問もチェックしましたが、同じ問題を経験している人を見つけることができませんでした。
サインインページで「Googleでログイン」ボタンをクリックすると、英語で「Access Denied」と書かれたエラーが出ます。
Djangoのサーバーサイドのコンソールでは、以下のようなエラーが表示されます。
raise OAuth2Error("Invalid id_token") from e
allauth.socialaccount.providers.oauth2.client.OAuth2Error: Invalid id_token
[13/Mar/2023 10:26:30] "POST /api/social/login/google/ HTTP/1.1" 500 162465
500エラーなので、URLかビューの問題だと思います。
フロント
[...nextauth].js
import NextAuth from "next-auth";
import axios from "axios";
import GoogleProvider from "next-auth/providers/google";
const settings = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
callbacks: {
async signIn({ user, account }) {
if (account.provider === "google") {
const accessToken = account.access_token;
const idToken = account.id_token;
console.log(idToken);
try {
const response = await axios.post(
`${process.env.DJANGO_URL}/api/social/login/google/`,
{
access_token: accessToken,
id_token: idToken,
}
);
const { access_token } = response.data;
user.accessToken = access_token;
return true;
} catch (error) {
return false;
}
}
return false;
},
async jwt({ token, account }) {
if (account) {
token.accessToken = account.access_token;
}
return token;
},
async session({ session, token }) {
session.accessToken = token.accessToken;
return session;
},
},
pages: {
signIn: "/auth/signin",
},
};
export default (req, res) => NextAuth(req, res, settings);
上記のコードでは、コンソールログにIDトークンが正常に表示されています。
確認のため、.envファイルを示します。
DJANGO_URL=http://localhost:8000
GOOGLE_CLIENT_ID=秘密
GOOGLE_CLIENT_SECRET=秘密
Client IDとClient secretは、私のGoogleコンソールの情報と一致しています。
JavaScript Originはこのように設定されています。
http://localhost:3000
URIはこのように設定されています。
http://localhost:3000/api/auth/callback/google
サーバー
authentication/views.py
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
class GoogleLoginView(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
client_class = OAuth2Client
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('api/auth/', include('dj_rest_auth.urls')), #Endpoints provided by dj-rest-auth
path('api/social/login/', include('authentication.urls')) #Endpoint for Social logins
]
urlpatterns=urlpatterns+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
authentication/urls.py
from django.urls import path, include
from .views import GoogleLoginView
urlpatterns = [
path("google/", GoogleLoginView.as_view(), name="google"),
]
この前、authentication/views.pyに「callback_url」変数を設定してみました。
マイグレーションを消して、新しいマイグレーションを作り、新しいマイグレーションを適用することを試しました。
他のフォーラムの投稿を参考に、POST/レスポンスの変数名を変えてみました。
どうぞよろしくお願いいたします。
はるさん、ご返信ありがとうございます。
両リポジトリーをローカルPCにコピーしてみました。Djangoではこの件に関してエラーが出ました。
'DEFAULT_AUTHENTICATION_CLASSES': (
...
"dj_rest_auth.utils.JWTCookieAuthentication",
),
クラスJWTCookieAuthenticationが見つからないと表示されました。ネットで調べた結果、これに変更しました。
rest_framework_simplejwt.authentication.JWTAuthentication
しかし、この後も、同じエラーが出ます。
raise OAuth2Error("Invalid id_token") from e
allauth.socialaccount.providers.oauth2.client.OAuth2Error: Invalid id_token
[16/Mar/2023 11:29:18] "POST /api/social/login/google/ HTTP/1.1" 500 162417
GCNで新規プロジェクト、クライアントID、クライアントシークレットを作成しました。この新しい情報を env ファイルにコピーし、Django の 'Social Application' 設定にコピーしました。しかし、同じエラーはまだ続いています。
これからも調べていきます。
講座のコードをそのまま動かしてもエラーが発生しますでしょうか?
■フロントエンド
https://github.com/haruyasu/next-blog-auth-tutorial
■バックエンド
https://github.com/haruyasu/drf-blog-auth-tutorial
もしエラーが発生した場合は、GCPの設定や、Djangoの外部アカウントの設定を見直してみて下さい。