React Native에서 Parse와 Apple 로그인 구현하기
9 분
react native용 apple로 로그인하기 소개 지난 튜토리얼에서는 \<font color="#2166ae">parse user\</font> 클래스를 사용하여 앱에 사용자 로그인/로그아웃 기능을 추가했습니다 이제 apple sign in을 사용하여 apple에서 사용자 데이터를 검색하고 로그인, 가입 또는 기존 사용자와 연결하는 방법을 배울 것입니다 또한 이를 달성하기 위해 \<font color="#2166ae">react native apple authentication\</font> 라이브러리를 설치하고 구성할 것입니다 \<font color="#2166ae">parse user linkwith\</font> 메서드는 각기 다른 제공자가 요청하는 올바른 매개변수만 전달하면 모든 서드파티 인증 방법을 사용하여 사용자를 가입시키고 로그인하는 역할을 합니다 사용자 데이터를 새 또는 기존 \<font color="#2166ae">parse user\</font> 에 연결한 후, parse는 장치에 유효한 사용자 세션을 저장합니다 이후 \<font color="#2166ae">currentasync\</font> 와 같은 메서드를 호출하면 일반 로그인과 마찬가지로 사용자 데이터를 성공적으로 검색할 수 있습니다 언제든지 이 튜토리얼로 구축된 전체 android 프로젝트에 접근할 수 있습니다 github 리포지토리에서 확인하세요 kotlin 예제 리포지토리 https //github com/templates back4app/android parse sdk kotlin java 예제 리포지토리 https //github com/templates back4app/android parse sdk java 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 react native 앱이 생성되고 back4app에 연결됨 https //www back4app com/docs/react native/parse sdk/react native sdk 이전 가이드를 완료하여 parse 사용자 클래스에 대한 이해를 높이세요 https //www back4app com/docs/react native/parse sdk/working with users/react native login 목표 react native 앱에서 parse를 사용하여 apple sign in을 통한 사용자 로그인 기능을 구축합니다 1 의존성 설치 react native에서 apple sign in을 활성화하는 가장 인기 있는 방법은 \<font color="#2166ae">react native apple authentication\</font> 라이브러리를 사용하는 것입니다 이 라이브러리의 구성은 개발 환경, 대상 플랫폼 및 선호도에 따라 다르므로, 공식 문서 https //github com/invertase/react native apple authentication 를 따라 설정하세요 android용으로 개발하는 경우, apple jwt 토큰을 디코딩하기 위해 https //github com/auth0/jwt decode 라이브러리를 설치해야 합니다 참고 xcode 환경의 초기 설정, 앱 id, 키 및 apple developer 포털에서 서비스 id를 만드는 지침을 철저히 따르세요 2 parse와 함께 apple sign in 사용하기 이제 apple sign in 인증 모달을 호출하는 \<font color="#2166ae">userlogin\</font> 컴포넌트 내에 새로운 메서드를 생성해 보겠습니다 \<font color="#2166ae">react native apple authentication\</font> 라이브러리는 사용자 플랫폼에 따라 이 호출을 처리하기 위해 두 개의 별도 모듈을 가지고 있으므로, \<font color="#2166ae">appleauth performrequest\</font> 를 ios에서 사용하고, \<font color="#2166ae">appleauthandroid signin\</font> 을 android에서 사용해야 합니다 사용자가 apple로 로그인하면, 이 호출은 apple로부터 사용자 데이터를 검색하고, \<font color="#2166ae">id\</font> , \<font color="#2166ae">token\</font> , 그리고 나중에 사용할 apple 이메일을 저장해야 합니다 javascript 1 const douserloginapple = async function () promise\<boolean> { 2 try { 3 let response = {}; 4 let appleid = ''; 5 let appletoken = ''; 6 let appleemail = ''; 7 if (platform os === 'ios') { 8 // performs login request requesting user email 9 response = await appleauth performrequest({ 10 requestedoperation appleauth operation login, 11 requestedscopes \[appleauth scope email], 12 }); 13 // on ios, user id and email are easily retrieved from request 14 appleid = response user; 15 appletoken = response identitytoken; 16 appleemail = response email; 17 } else if (platform os === 'android') { 18 // configure the request 19 appleauthandroid configure({ 20 // the service id you registered with apple 21 clientid 'your service id', 22 // return url added to your apple dev console 23 redirecturi 'your redirect url', 24 responsetype appleauthandroid responsetype all, 25 scope appleauthandroid scope all, 26 }); 27 response = await appleauthandroid signin(); 28 // decode user id and email from token returned from apple, 29 // this is a common workaround for apple sign in via web api 30 const decodedidtoken = jwt decode(response id token); 31 appleid = decodedidtoken sub; 32 appletoken = response id token; 33 appleemail = decodedidtoken email; 34 } 35 // format authdata to provide correctly for apple linkwith on parse 36 const authdata = { 37 id appleid, 38 token appletoken, 39 }; 40 } catch (error) { 41 // error can be caused by wrong parameters or lack of internet connection 42 alert alert('error!', error); 43 return false; 44 } 45 };1 const douserloginapple = async function () promise\<boolean> { 2 try { 3 let response object = {}; 4 let appleid string = ''; 5 let appletoken string = ''; 6 let appleemail string = ''; 7 if (platform os === 'ios') { 8 // performs login request requesting user email 9 response = await appleauth performrequest({ 10 requestedoperation appleauth operation login, 11 requestedscopes \[appleauth scope email], 12 }); 13 // on ios, user id and email are easily retrieved from request 14 appleid = response user; 15 appletoken = response identitytoken; 16 appleemail = response email; 17 } else if (platform os === 'android') { 18 // configure the request 19 appleauthandroid configure({ 20 // the service id you registered with apple 21 clientid 'your service id', 22 // return url added to your apple dev console 23 redirecturi 'your service url', 24 responsetype appleauthandroid responsetype all, 25 scope appleauthandroid scope all, 26 }); 27 response = await appleauthandroid signin(); 28 // decode user id and email from token returned from apple, 29 // this is a common workaround for apple sign in via web api 30 const decodedidtoken object = jwt decode(response id token); 31 appleid = decodedidtoken sub; 32 appletoken = response id token; 33 appleemail = decodedidtoken email; 34 } 35 // format authdata to provide correctly for apple linkwith on parse 36 const authdata object = { 37 id appleid, 38 token appletoken, 39 }; 40 } catch (error any) { 41 // error can be caused by wrong parameters or lack of internet connection 42 alert alert('error!', error); 43 return false; 44 } 45 }; android의 경우 apple에서 반환된 토큰을 디코딩해야 한다는 점에 유의하세요 왜냐하면 라이브러리 \<font color="#2166ae">react native apple authentication\</font> 은 인증을 위해 apple sign in 웹 api를 사용하기 때문입니다 이 방법을 사용할 때 데이터 접근에 대한 제한이 있으므로, 사용자 id와 이메일을 가져오는 일반적인 우회 방법은 이 디코딩 과정을 통해 이루어집니다 이는 공식 parse 가이드에서 여기 https //docs parseplatform org/parse server/guide/#apple authdata 에 명시되어 있습니다 그 후, 새로운 \<font color="#2166ae">parse user linkwith\</font> 를 사용하여 새로운 사용자 등록 및 로그인을 할 수 있습니다 사용자가 이미 이 apple 인증을 사용하여 가입한 경우, \<font color="#2166ae">linkwith\</font> 는 기존 계정을 사용하여 그를 로그인 시킵니다 javascript 1 const douserloginapple = async function () promise\<boolean> { 2 try { 3 let response = {}; 4 let appleid = ''; 5 let appletoken = ''; 6 let appleemail = ''; 7 if (platform os === 'ios') { 8 // performs login request requesting user email 9 response = await appleauth performrequest({ 10 requestedoperation appleauth operation login, 11 requestedscopes \[appleauth scope email], 12 }); 13 // on ios, user id and email are easily retrieved from request 14 appleid = response user; 15 appletoken = response identitytoken; 16 appleemail = response email; 17 } else if (platform os === 'android') { 18 // configure the request 19 appleauthandroid configure({ 20 // the service id you registered with apple 21 clientid 'your service io', 22 // return url added to your apple dev console 23 redirecturi 'your service url', 24 responsetype appleauthandroid responsetype all, 25 scope appleauthandroid scope all, 26 }); 27 response = await appleauthandroid signin(); 28 // decode user id and email from token returned from apple, 29 // this is a common workaround for apple sign in via web api 30 const decodedidtoken = jwt decode(response id token); 31 appleid = decodedidtoken sub; 32 appletoken = response id token; 33 appleemail = decodedidtoken email; 34 } 35 // format authdata to provide correctly for apple linkwith on parse 36 const authdata = { 37 id appleid, 38 token appletoken, 39 }; 40 // log in or sign up on parse using this apple credentials 41 let usertologin = new parse user(); 42 // set username and email to match provider email 43 usertologin set('username', appleemail); 44 usertologin set('email', appleemail); 45 return await usertologin 46 linkwith('apple', { 47 authdata authdata, 48 }) 49 then(async (loggedinuser) => { 50 // login returns the corresponding parseuser object 51 alert alert( 52 'success!', 53 `user ${loggedinuser get('username')} has successfully signed in!`, 54 ); 55 // to verify that this is in fact the current user, currentasync can be used 56 const currentuser = await parse user currentasync(); 57 console log(loggedinuser === currentuser); 58 // navigation navigate takes the user to the screen named after the one 59 // passed as parameter 60 navigation navigate('home'); 61 return true; 62 }) 63 catch(async (error) => { 64 // error can be caused by wrong parameters or lack of internet connection 65 alert alert('error!', error message); 66 return false; 67 }); 68 } catch (error) { 69 // error can be caused by wrong parameters or lack of internet connection 70 alert alert('error!', error); 71 return false; 72 } 73 };1 const douserloginapple = async function () promise\<boolean> { 2 try { 3 let response object = {}; 4 let appleid string = ''; 5 let appletoken string = ''; 6 let appleemail string = ''; 7 if (platform os === 'ios') { 8 // performs login request requesting user email 9 response = await appleauth performrequest({ 10 requestedoperation appleauth operation login, 11 requestedscopes \[appleauth scope email], 12 }); 13 // on ios, user id and email are easily retrieved from request 14 appleid = response user; 15 appletoken = response identitytoken; 16 appleemail = response email; 17 } else if (platform os === 'android') { 18 // configure the request 19 appleauthandroid configure({ 20 // the service id you registered with apple 21 clientid 'com back4app userguide', 22 // return url added to your apple dev console 23 redirecturi 'https //tuhl software/back4appuserguide/', 24 responsetype appleauthandroid responsetype all, 25 scope appleauthandroid scope all, 26 }); 27 response = await appleauthandroid signin(); 28 // decode user id and email from token returned from apple, 29 // this is a common workaround for apple sign in via web api 30 const decodedidtoken object = jwt decode(response id token); 31 appleid = decodedidtoken sub; 32 appletoken = response id token; 33 appleemail = decodedidtoken email; 34 } 35 // format authdata to provide correctly for apple linkwith on parse 36 const authdata object = { 37 id appleid, 38 token appletoken, 39 }; 40 // log in or sign up on parse using this apple credentials 41 let usertologin parse user = new parse user(); 42 // set username and email to match provider email 43 usertologin set('username', appleemail); 44 usertologin set('email', appleemail); 45 return await usertologin 46 linkwith('apple', { 47 authdata authdata, 48 }) 49 then(async (loggedinuser parse user) => { 50 // login returns the corresponding parseuser object 51 alert alert( 52 'success!', 53 `user ${loggedinuser get('username')} has successfully signed in!`, 54 ); 55 // to verify that this is in fact the current user, currentasync can be used 56 const currentuser parse user = await parse user currentasync(); 57 console log(loggedinuser === currentuser); 58 // navigation navigate takes the user to the screen named after the one 59 // passed as parameter 60 navigation navigate('home'); 61 return true; 62 }) 63 catch(async (error object) => { 64 // error can be caused by wrong parameters or lack of internet connection 65 alert alert('error!', error message); 66 return false; 67 }); 68 } catch (error any) { 69 // error can be caused by wrong parameters or lack of internet connection 70 alert alert('error!', error); 71 return false; 72 } 73 }; 이 기능을 \<font color="#2166ae">usersignin\</font> 컴포넌트에 추가하고 apple 버튼의 \<font color="#2166ae">onpress\</font> 매개변수에 할당하세요 새 기능을 테스트해 보세요 사용자가 성공적으로 등록하고/또는 로그인한 후에는 홈 화면으로 리디렉션된다는 점에 유의하세요 3 사용자 로그인 및 세션 생성 확인 apple 로그인이 제대로 작동했는지 확인하려면, parse 대시보드를 확인하고 새로운 \<font color="#2166ae">사용자\</font> (apple 인증 데이터가 다른 사용자에 속하지 않는 경우)와 함께 apple \<font color="#2166ae">authdata\</font> 매개변수를 포함하고 있는지 확인할 수 있습니다 대시보드에서 유효한 세션이 생성되었는지 확인할 수도 있으며, 해당 \<font color="#2166ae">사용자\</font> 객체에 대한 포인터를 포함하고 있습니다 4 기존 사용자를 apple 로그인에 연결하기 또 다른 \<font color="#2166ae">linkwith\</font> 가능한 사용법은 기존 사용자를 다른 인증 제공자, 이 경우에는 apple과 연결하는 것입니다 \<font color="#2166ae">linkwith\</font> 를 호출하는 이 기능을 추가하세요 \<font color="#2166ae">userlogin\</font> 에서 했던 것과 같은 방식으로 당신의 \<font color="#2166ae">hellouser\</font> 컴포넌트나 직접 홈 화면에 추가하세요 여기서 유일한 차이점은 빈 \<font color="#2166ae">parse user\</font> 에서 메서드를 호출하는 대신, 로그인한 사용자 객체에서 사용할 것이라는 점입니다 javascript 1 const douserlinkapple = async function (){ 2 try { 3 let response = {}; 4 let appleid = ''; 5 let appletoken = ''; 6 if (platform os === 'ios') { 7 // performs login request requesting user email 8 response = await appleauth performrequest({ 9 requestedoperation appleauth operation login, 10 requestedscopes \[appleauth scope email], 11 }); 12 // on ios, user id and email are easily retrieved from request 13 appleid = response user; 14 appletoken = response identitytoken; 15 } else if (platform os === 'android') { 16 // configure the request 17 appleauthandroid configure({ 18 // the service id you registered with apple 19 clientid 'your service id', 20 // return url added to your apple dev console 21 redirecturi 'your redirect url', 22 responsetype appleauthandroid responsetype all, 23 scope appleauthandroid scope all, 24 }); 25 response = await appleauthandroid signin(); 26 // decode user id and email from token returned from apple, 27 // this is a common workaround for apple sign in via web api 28 const decodedidtoken = jwt decode(response id token); 29 appleid = decodedidtoken sub; 30 appletoken = response id token; 31 } 32 // format authdata to provide correctly for apple linkwith on parse 33 const authdata = { 34 id appleid, 35 token appletoken, 36 }; 37 let currentuser = await parse user currentasync(); 38 // link user with his apple credentials 39 return await currentuser 40 linkwith('apple', { 41 authdata authdata, 42 }) 43 then(async (loggedinuser) => { 44 // login returns the corresponding parseuser object 45 alert alert( 46 'success!', 47 `user ${loggedinuser get( 48 'username', 49 )} has successfully linked his apple account!`, 50 ); 51 // to verify that this is in fact the current user, currentasync can be used 52 currentuser = await parse user currentasync(); 53 console log(loggedinuser === currentuser); 54 return true; 55 }) 56 catch(async (error) => { 57 // error can be caused by wrong parameters or lack of internet connection 58 alert alert('error!', error message); 59 return false; 60 }); 61 } catch (error) { 62 // error can be caused by wrong parameters or lack of internet connection 63 alert alert('error!', error); 64 return false; 65 } 66 };1 const douserlinkapple = async function () promise\<boolean> { 2 try { 3 let response object = {}; 4 let appleid string = ''; 5 let appletoken string = ''; 6 if (platform os === 'ios') { 7 // performs login request requesting user email 8 response = await appleauth performrequest({ 9 requestedoperation appleauth operation login, 10 requestedscopes \[appleauth scope email], 11 }); 12 // on ios, user id and email are easily retrieved from request 13 appleid = response user; 14 appletoken = response identitytoken; 15 } else if (platform os === 'android') { 16 // configure the request 17 appleauthandroid configure({ 18 // the service id you registered with apple 19 clientid 'your service id', 20 // return url added to your apple dev console 21 redirecturi 'your service url', 22 responsetype appleauthandroid responsetype all, 23 scope appleauthandroid scope all, 24 }); 25 response = await appleauthandroid signin(); 26 // decode user id and email from token returned from apple, 27 // this is a common workaround for apple sign in via web api 28 const decodedidtoken object = jwt decode(response id token); 29 appleid = decodedidtoken sub; 30 appletoken = response id token; 31 } 32 // format authdata to provide correctly for apple linkwith on parse 33 const authdata object = { 34 id appleid, 35 token appletoken, 36 }; 37 let currentuser parse user = await parse user currentasync(); 38 // link user with his apple credentials 39 return await currentuser 40 linkwith('apple', { 41 authdata authdata, 42 }) 43 then(async (loggedinuser parse user) => { 44 // login returns the corresponding parseuser object 45 alert alert( 46 'success!', 47 `user ${loggedinuser get( 48 'username', 49 )} has successfully linked his apple account!`, 50 ); 51 // to verify that this is in fact the current user, currentasync can be used 52 currentuser = await parse user currentasync(); 53 console log(loggedinuser === currentuser); 54 return true; 55 }) 56 catch(async (error object) => { 57 // error can be caused by wrong parameters or lack of internet connection 58 alert alert('error!', error message); 59 return false; 60 }); 61 } catch (error any) { 62 // error can be caused by wrong parameters or lack of internet connection 63 alert alert('error!', error); 64 return false; 65 } 66 }; 이 기능을 apple 버튼 \<font color="#2166ae">onpress\</font> 매개변수에 할당하세요 새로운 기능을 테스트하고, \<font color="#2166ae">parse user\</font> 객체의 \<font color="#2166ae">authdata\</font> 값이 새로운 인증 제공자 데이터로 업데이트될 것임을 주의하세요 사용자가 실제로 parse 서버 대시보드에서 업데이트되었는지 확인하세요 결론 이 가이드의 끝에서, apple sign in을 사용하여 react native에서 parse 사용자에게 로그인, 가입 또는 기존 사용자를 연결하는 방법을 배웠습니다 \<font color="#2166ae">react native apple authentication\</font> 을 사용했습니다 다음 가이드에서는 유용한 사용자 쿼리를 수행하는 방법을 보여드리겠습니다