React Native и Parse: Вход с Apple
9 мин
вход с apple для react native введение в последнем уроке вы создали функцию входа/выхода пользователя в ваше приложение, используя класс \<font color="#2166ae">parse user\</font> теперь вы узнаете, как использовать вход с apple для получения данных пользователя от 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 цель создать функцию входа пользователя с использованием входа через apple в parse для приложения react native 1 установка зависимостей самый популярный способ включить вход с помощью apple в react native это использовать \<font color="#2166ae">react native apple authentication\</font> для обработки этого поскольку конфигурация этой библиотеки зависит от вашей среды разработки, целевой платформы и предпочтений, настройте её, следуя официальной документации https //github com/invertase/react native apple authentication если вы разрабатываете для android, вам также нужно установить https //github com/auth0/jwt decode библиотеку для декодирования токенов apple jwt примечание убедитесь, что вы тщательно следуете инструкциям по первоначальной настройке среды xcode, созданию вашего идентификатора приложения, ключей и идентификатора службы на портале разработчиков apple 2 использование входа через apple с parse теперь давайте создадим новый метод внутри \<font color="#2166ae">userlogin\</font> компонента, который вызывает модальное окно аутентификации через apple библиотека \<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> использует веб api входа в систему apple для аутентификации существуют ограничения на доступ к данным при использовании этого метода, поэтому распространенным обходным путем для получения вашего идентификатора пользователя и электронной почты является этот процесс декодирования, как указано здесь https //docs parseplatform org/parse server/guide/#apple authdata в официальных руководствах parse после этого вы можете использовать \<font color="#2166ae">parse user linkwith\</font> на новом \<font color="#2166ae">parse user\</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 не принадлежали другому пользователю), содержащего параметры \<font color="#2166ae">authdata\</font> apple вы также можете проверить, что действительная сессия была создана на панели управления, содержащей указатель на этот \<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 сервером заключение в конце этого руководства вы узнали, как войти в систему, зарегистрироваться или связать существующих пользователей parse в react native, используя вход с помощью apple \<font color="#2166ae">react native apple authentication\</font> в следующем руководстве мы покажем вам, как выполнять полезные запросы пользователей