• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

auth 쓸때 name 외 정보들은 확인이 안되네요

24.03.25 20:40 작성 조회수 148

0

https://github.com/nextauthjs/next-auth/discussions/10399#discussion-6417675

 

next-auth 쪽에도 help 쪽에 질의를 해놨는데요, 원래 이슈로 쓰려했는데 reproduce url을 요구하더라구요 ㅠㅠ

 

현재 auth는 이슈가 적다고 하신 라이브러리를 쓰고있어요

 



    "@auth/core": "^0.27.0",
    "next": "14.0.4",
    "next-auth": "^5.0.0-beta.11",

를 사용중이고요, custom login 페이지를 두었는데

credentials 정보는 잘 넘어와서 login api 도 잘 타는데

그 내용을 토대로 클라이언트에서 useSession으로 유저 정보를 확인하려해도 name 만 정상적으로 리턴이되네요..

 

 

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { NextResponse } from "next/server";

export const {
	handlers: { GET, POST },
	auth,
	signIn,
} = NextAuth({
	pages: {
		signIn: "/login",
	},
	providers: [
		CredentialsProvider({
			async authorize(credentials) {
				console.log(
					"credentials info: " +
						credentials.email +
						" " +
						credentials.password
				);
				const params = new URLSearchParams(
					`empNo=${credentials.email}&empPassword=${credentials.password}`
				);
				console.log(params);
				const authResponse = await fetch(
					`http://?????:9080/api/getempinfo`,
					{
						method: "POST",
						headers: {
							"Content-Type": "application/x-www-form-urlencoded",
						},
						body: params,
					}
				);
				if (!authResponse.ok) {
					return null;
				}

				const user = await authResponse.json();
				console.log("user", user);
				// user.retData[0] inside informations are all string.
				// {
				//     user_id: '*******',
				//     user_name: 'jinyoung',
				//     sert_num: '*********',
				//     user_rgst_patr_code: '001',
				//     rdp_code: '000'
				//   }

				console.log("user.retdata.user_id =", user.retData[0].user_id);
				console.log(
					"user.retdata.user_name=",
					user.retData[0].user_name
				);
				const id = user.retData[0].user_id;
				return {
					// mapping info
					// id?: string
					// name?: string | null
					// email?: string | null
					// image?: string | null
					id: id,
					name: user.retData[0].user_name,
					...user.retData[0],
				};
			},
		}),
	],
	// secret: ,
	trustHost: true,
});

 

 

아래는 useSession 을 사용하는 클라이언트 컴포넌트에요

 

"use client";
import React, { useEffect, useState } from "react";

...

// import useSWR from "swr";
import { useSession } from "next-auth/react";

...

const Home = () => {
	const { data: session, status } = useSession();

	console.log("status?");
	console.log("status=" + status);

	console.log("session=");
	console.log(session?.user);
	useEffect(() => {
		if (session) {
			console.log("session useEffected = ");
			console.log(session);
		}
	}, [session]);

 

 

아래는 콘솔 찍어본 내용이에요

 

답변 2

·

답변을 작성해보세요.

0

authorize에서 return하는 객체에서는 id, email, name, picture밖에 넣지 못하므로(그 중에서도 id는 token.sub로 갑니다) 다음과 같이 callbacks의 메서드인 session에서 user 데이터를 가져오셔야 합니다.

NextAuth({
  ...
  callbacks: {
    async session({ session, newSession, user, token}) {
      console.log('session callback', session, token);
      const authResponse = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/user/${token.sub}`);
      const userData = await authResponse.json();
      (session as any).userData = userData;
      return session;
   }
  },
  providers: [...]
})


0

authorize 함수에서 콘솔로그 결과를 주석으로 적어주셨는데 저기는 jinyoung 영어인데 브라우저에서는 진영 한글인데 이건 그냥 주석을 잘못 쓰신거죠??

danroom85님의 프로필

danroom85

질문자

2024.03.25

아 네 말씀해주신게 맞아요. 아래는 실제 콘솔에 찍힌거고 그 위에 json 코드는 github에 올려보느라고 저렇게 찍은거에용..

그럼 authorize 함수에서는 user_name: '이진영'과 그 외 나머지 속성 전부 찍히는 것이죠?

danroom85님의 프로필

danroom85

질문자

2024.03.25

네 실제 api 호출했을때 담겨있는 user 에 리턴되는 내용은 아래랑 같아요

 

user {

    retCode: 0,
  
    retMsg: '정상처리 완료',
  
    errCode: 100,
  
    retDataCount: 1,
  
    retData: [
  
      {
  
        user_id: '12975',
  
        user_name: '이진영',
  
        sert_num: '*******',
  
        user_rgst_patr_code: '001',
  
        rdp_code: '000'
  
      }
  
    ],
  
    reqIpAdrs: '??.???.???.??'
  
  }

 

retData 로 Return 이 오다보니

        return {
          // authorize 에 맞게 맵핑해줘야 할 정보
          // id?: string
          // name?: string | null
          // email?: string | null
          // image?: string | null
          id: user.retData[0].user_id,
          name: user.retData[0].user_name,
          ...user.retData[0],
        };

이런식으로 return 쪽에 값을 바인딩 했던거고요.

danroom85님의 프로필

danroom85

질문자

2024.03.25

어 근데 혹시 해서 id 쪽 값만 string 이고 나머진 |null 로 되어있어서 name 이랑 Email 만 넣어봤는데 그 값이 출력이 되네요?;; Id 값에는 여전히 값이 안들어 가고요.. 혹시 커스텀해서 넣을수는 없는걸까요?


          name: user.retData[0].user_id,
          email: user.retData[0].user_name,

image