test

import jwt
import requests
from django.conf import settings
from rest_framework import authentication, exceptions

class AzureADAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
# リクエストからトークンを取得
auth_header = authentication.get_authorization_header(request).split()
if not auth_header or auth_header[0].lower() != b'bearer':
return None

token = auth_header[1]

# Azure AD公開鍵を取得
jwks_url = 'https://login.microsoftonline.com/common/discovery/v2.0/keys'
jwks_resp = requests.get(jwks_url)
jwks = jwks_resp.json()

# トークンの検証
try:
unverified_header = jwt.get_unverified_header(token)
rsa_key = next(key for key in jwks['keys'] if key['kid'] == unverified_header['kid'])
payload = jwt.decode(
token,
rsa_key,
algorithms=['RS256'],
audience=settings.AZURE_AD_CLIENT_ID
)
except Exception as e:
raise exceptions.AuthenticationFailed('トークンの検証に失敗しました。')

# ここでユーザーモデルとのマッピングを行う
# 例: ユーザーの作成や取得
# user = ...

return (user, None) # (ユーザーインスタンス, 認証トークン)

# settings.py でのバックエンドの設定
# REST_FRAMEWORK = {
# 'DEFAULT_AUTHENTICATION_CLASSES': [
# 'myapp.authentication.AzureADAuthentication',
# ],
# }

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です