Docker nginx ELB(负载均衡器)499错误

问题描述 投票:0回答:1

即使我查找了与 nginx 499 错误相关的其他一些问题,我也遇到了一个问题并且无法解决它。 我的项目使用 Django,问题出在社交登录(kakao 登录)错误。

我的帐户/views.py 看起来像这样:

BASE_DIR = Path(__file__).resolve().parent.parent
env_file = BASE_DIR / ".env"
if os.getenv("DJANGO_ENV") == "production":
    env_file = BASE_DIR / ".env.prod"
env = environ.Env()
env.read_env(env_file)

BASE_URL = env("BASE_URL")
KAKAO_CALLBACK_URI = BASE_URL + "accounts/kakao/callback/"
REST_API_KEY = env("KAKAO_REST_API_KEY")
CLIENT_SECRET = env("KAKAO_CLIENT_SECRET_KEY")


@extend_schema(
    summary="카카오 로그인",
    description="카카오 로그인 페이지로 리다이렉트합니다.",
    responses={
        302: OpenApiResponse(
            description="Redirects to the Kakao login page.", response=None
        )
    },
)
@api_view(["GET"])
@permission_classes([AllowAny])
def kakao_login(request):
    return redirect(
        f"https://kauth.kakao.com/oauth/authorize?client_id={REST_API_KEY}&redirect_uri={KAKAO_CALLBACK_URI}&response_type=code"
    )

# @extend_schema(exclude=True)
# @permission_classes([AllowAny])
# def finish_login(data):
#     accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data)
#     return accept

@extend_schema(exclude=True)
@permission_classes([AllowAny])
def kakao_callback(request):
    code = request.GET.get("code")
    print(f"code: {code}")

    # Access Token Request
    token_req = requests.get(
        f"https://kauth.kakao.com/oauth/token?grant_type=authorization_code&client_id={REST_API_KEY}&client_secret={CLIENT_SECRET}&redirect_uri={KAKAO_CALLBACK_URI}&code={code}"
    )
    print(f"token_req: {token_req}")

    token_req_json = token_req.json()
    print(f"token_req_json: {token_req_json}")

    error = token_req_json.get("error")
    if error is not None:
        raise JSONDecodeError(error)

    access_token = token_req_json.get("access_token")
    print(f"access_token: {access_token}")

    # Email Request

    profile_request = requests.get(
        "https://kapi.kakao.com/v2/user/me",
        headers={"Authorization": f"Bearer {access_token}"},
    )
    profile_data = profile_request.json()
    print(f"profile_data: {profile_data}")

    kakao_oid = profile_data.get("id")
    kakao_account = profile_data.get("kakao_account")
    username = kakao_account["profile"]["nickname"]
    profile_image_url = kakao_account["profile"]["profile_image_url"]
    email = kakao_account.get("email")

    # 회원가입, 로그인 로직

    data = {"access_token": access_token, "code": code}
    # TODO 유저 프로필 이미지 저장하도록

    try:
        user = CustomUser.objects.get(email=email)
        # 유저가 존재하는 경우
        accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data)
        accept_status = accept.status_code
        print(accept_status)

        if accept_status != 200:
            return Response({"err_msg": "failed to signin"}, status=accept_status)

        accept_json = accept.json()
        print(f"accept_json, {accept_json}")
        # key 이름 변경
        accept_json["accessToken"] = accept_json.pop("access")
        accept_json["refreshToken"] = accept_json.pop("refresh")
        accept_json["userProfile"] = accept_json.pop("user")
        accept_json["userProfile"]["id"] = accept_json["userProfile"].pop("pk")
        return JsonResponse(accept_json)

    except CustomUser.DoesNotExist:
        # 기존에 가입된 유저가 없으면 새로 가입
        # accept = finish_login(data)
        accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data)
        accept_status = accept.status_code
        if accept_status != 200:
            return Response({"err_msg": "failed to signup"}, status=accept_status)

        # user의 pk, email, first name, last name과 Access Token, Refresh token 가져옴
        accept_json = accept.json()
        # key 이름 변경
        accept_json["accessToken"] = accept_json.pop("access")
        accept_json["refreshToken"] = accept_json.pop("refresh")
        accept_json["userProfile"] = accept_json.pop("user")
        accept_json["userProfile"]["id"] = accept_json["userProfile"].pop("pk")
        return JsonResponse(accept_json)

@extend_schema(exclude=True)
class KakaoLoginView(SocialLoginView):
    adapter_class = kakao_view.KakaoOAuth2Adapter
    client_class = OAuth2Client
    callback_url = KAKAO_CALLBACK_URI

这是我的 urls.py:

urlpatterns = [
    path("kakao/login/", views.kakao_login, name="kakao_login"),
    path("kakao/callback/", views.kakao_callback, name="kakao_callback"),
    path(
        "kakao/login/finish/",
        views.KakaoLoginView.as_view(),
        name="kakao_login_todjango",
    )
]

和 myproject/views.py

urlpatterns = [
    path("", kakao_login_page, name="home"),
    path("admin/", admin.site.urls),
    # path("accounts/", include("dj_rest_auth.urls")),
    # path('accounts/', include('allauth.urls')),
    path("accounts/", include("accounts.urls")),
    path("registration/", include("dj_rest_auth.registration.urls")),
    # swagger 관련
    path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
    path(
        "api/schema/swagger-ui/",
        SpectacularSwaggerView.as_view(url_name="schema"),
        name="swagger-ui",
    ),
    path(
        "api/schema/redoc/",
        SpectacularRedocView.as_view(url_name="schema"),
        name="redoc",
    ),
]

和我的 nginx.conf

upstream resumai {
  server web:8000;
}

server {

  listen 80;

  location / {
    proxy_pass http://resumai;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_redirect off;

    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    send_timeout 300s;
  }

  location /static/ {
    alias /home/app/web/static/;
  }

  location /media/ {
    alias /home/app/web/media/;
  }
}

问题是,当我访问页面/accounts/kakao/login时,我得到了正确的重定向响应(302)。 但是,我从网络收到 502 错误,从 nginx docker 容器收到 499 错误,如下所示(我隐藏了我的代码): enter image description here 这是我的 docker nginx 错误: enter image description here

我认为这可能是与我正在使用的负载均衡器相关的问题,但我不知道如何解决这个问题。有没有人可以帮我解决这个问题??

django nginx amazon-ec2 load-balancing amazon-elb
1个回答
0
投票

您的 ELB 收到 499 错误。

您可以分享您设置的 ELB 代码吗?您能确保 /health 正常工作吗?

© www.soinside.com 2019 - 2024. All rights reserved.