AWS Amplify 백엔드가 있는 Flatter 애플리케이션: 섹션 2 - 인증
AWS Amplify 백엔드가 있는 떨림 어플리케이션: 섹션 2 — 인증
AWS Cognito의 도움으로 떨림 응용 프로그램에서 인증을 설정하는 것은 매우 쉬우며, 지금은 떨림을 확대하여 실현할 수 있다.만약 당신이 이 시리즈의 첫 번째 부분을 아직 읽지 않았다면, 나는 당신이 먼저 읽는 것을 건의합니다.
우리 뭐 하는 거야?
인증 백엔드인 Flitter 응용 프로그램을 사용하기 위해 간단한 등록 및 로그인 시스템을 만듭니다.
AWS Cognito 로그인 지연 시간이 매우 낮음
예전과 같이, 당신은 우리의 Github에서 이 강좌의 코드를 찾을 수 있습니다.
되팔다
뭐 공부 해요?
이 강좌는 본 강좌 시리즈의 첫 번째 부분에서 만든 응용 프로그램만 필요합니다. 이것은 단지'확대'를 초기화한 예시 응용 프로그램일 뿐입니다.
섹션 1을 읽지 않고 Amplify Flatter에 익숙해지면 새로운 Flatter 응용 프로그램과
Amplify의 클라우드 인스턴스에 연결합니다.
시작합시다.
기본 확대 항목 만들기
섹션 1에서 만든 응용 프로그램을 사용하는 경우 이 단계를 건너뛸 수 있습니다.
그렇지 않으면 새 떨림 항목을 만들고 프로젝트 디렉터리에서 실행합니다.
amplify init
프로젝트에 AWS Cognito 추가
통합 터미널에서 실행
amplify add auth
그러면 프로젝트에 AWS Cognito**가 추가됩니다.설치 마법사가 완료되면 터미널은 다음과 같습니다.
우리는 전자 우편을 인증 방법으로 사용할 것입니다.나는 앞으로의 강좌에서 다른 방법을 소개할 것이다.
다음에 터미널에서 제시한 설명에 따라amplifypush를 실행하면 인증을 클라우드 프로젝트에 배치합니다.y
우리 자원의 상태를 검사하다
amplifystatus를 실행하여 클라우드 자원의 상태를 검사할 수 있습니다.
클라우드에서 AWS Cognito 서비스에 사용자 풀을 만들었을 것입니다.당신의 로 넘어가면 새로운 사용자 탱크를 볼 수 있습니다.
user pools
클라우드 리소스와 상호 작용
클라우드와 상호작용하려면 몇 가지 절차가 필요합니다. 최종 결과만 얻고 단계별 조작을 상관하지 않는다면
검사점을 제출할 수 있습니다.
이 코드 세그먼트 중 많은 것이 AWShere 에서 파생된 것이다.나는 모든 논리 구성 요소의 작용을 설명하고 당신에게 로그인 폼의 작업 예시를 제공할 것입니다.
amplify init
amplify add auth
amplify_core: '<1.0.0'
amplify_auth_cognito: '<1.0.0'
void _configureAmplify() async {
if (!mounted) return;
// add all of the plugins we are currently using
// in our case... just one - Auth
AmplifyAuthCognito authPlugin = AmplifyAuthCognito();
amplifyInstance.addPlugin(authPlugins: [authPlugin]);
await amplifyInstance.configure(amplifyconfig);
try {
setState(() {
_amplifyConfigured = true;
});
} catch (e) {
print(e);
}
}
3. 사용자 등록등록 사용자는 텍스트 컨트롤러를 사용합니다(이곳은 표시되지 않음).다시 한 번, 등록 작업의 결과에 따라 상태 플래그를 설정합니다(이 예에서는 isSignUpComplete).
Future<String> _registerUser(LoginData data) async
{
try {
Map<String, dynamic> userAttributes = {
"email": emailController.text,
};
SignUpResult res = await Amplify.Auth.signUp(
username: data.name,
password: data.password,
options: CognitoSignUpOptions(
userAttributes: userAttributes
)
);
setState(() {
isSignUpComplete = res.isSignUpComplete;
print("Sign up: " + (isSignUpComplete ? "Complete" : "Not Complete"));
});
} on AuthError catch (e) {
print(e);
return "Register Error: " + e.toString();
}
}
4. 로그인 사용자 Future<String> _signIn(LoginData data) async {
try {
SignInResult res = await Amplify.Auth.signIn(
username: data.name,
password: data.password,
);
setState(() {
isSignedIn = res.isSignedIn;
});
if (isSignedIn)
Alert(context: context, type: AlertType.success, title: "Login Success").show();
} on AuthError catch (e) {
print(e);
Alert(context: context, type: AlertType.error, title: "Login Failed").show();
return 'Log In Error: ' + e.toString();
}
}
이렇게!이것들은 모두 우리가 좋은 등록과 로그인 인터페이스를 만드는 데 사용하는 논리적 구축 블록이다.남은 유일한 일은 이 구성 요소를 사용자 인터페이스에 통합시키는 것이다. 우리는 다음에 이 일을 할 것이다.문서 떨림 로그인
편의를 위해, 우리는 라는 플래터 패키지를 사용하여 우리의 첫 번째 통합을 신속하고 쉽게 할 것이다.생활 속의 모든 것처럼, 키스.
flutter_login
주요했어쏜살같이 달리다
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_core/amplify_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'amplifyconfiguration.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// gives our app awareness about whether we are succesfully connected to the cloud
bool _amplifyConfigured = false;
// Instantiate Amplify
Amplify amplifyInstance = Amplify();
// controllers for text input
final emailController = TextEditingController();
final passwordController = TextEditingController();
bool isSignUpComplete = false;
bool isSignedIn = false;
@override
void initState() {
super.initState();
// amplify is configured on startup
_configureAmplify();
}
@override
void dispose() {
// Clean up the controller when the widget is removed from the
// widget tree.
emailController.dispose();
passwordController.dispose();
super.dispose();
}
void _configureAmplify() async {
if (!mounted) return;
// add all of the plugins we are currently using
// in our case... just one - Auth
AmplifyAuthCognito authPlugin = AmplifyAuthCognito();
amplifyInstance.addPlugin(authPlugins: [authPlugin]);
await amplifyInstance.configure(amplifyconfig);
try {
setState(() {
_amplifyConfigured = true;
});
} catch (e) {
print(e);
}
}
Future<String> _registerUser(LoginData data) async
{
try {
Map<String, dynamic> userAttributes = {
"email": emailController.text,
};
SignUpResult res = await Amplify.Auth.signUp(
username: data.name,
password: data.password,
options: CognitoSignUpOptions(
userAttributes: userAttributes
)
);
setState(() {
isSignUpComplete = res.isSignUpComplete;
print("Sign up: " + (isSignUpComplete ? "Complete" : "Not Complete"));
});
} on AuthError catch (e) {
print(e);
return "Register Error: " + e.toString();
}
}
Future<String> _signIn(LoginData data) async {
try {
SignInResult res = await Amplify.Auth.signIn(
username: data.name,
password: data.password,
);
setState(() {
isSignedIn = res.isSignedIn;
});
} on AuthError catch (e) {
print(e);
return 'Log In Error: ' + e.toString();
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: FlutterLogin(
logo: 'assets/vennify_media.png',
onLogin: _signIn,
onSignup: _registerUser,
onRecoverPassword: (_) => null,
title:'Flutter Amplify'
),
);
}
}
물론 *pubspec에 다음 줄을 추가합니다.yaml** 지원 새 패키지:flutter_login: '<1.0.0'
rflutter_alert: '^1.0.3'
Flitter\u 로그인 로고를 얻기 위해 자산에 이미지를 추가해야 합니다.사용자 등록 테스트
새 사용자를 등록하려면 직관적인flatter\u 로그인 인터페이스를 사용하여 새 사용자 요청을 제출하여Cognito를 확대하십시오.
가짜 이메일 또는 실제 이메일을 사용합니다.너의 선택.
사용자로 이동하면 새로 만든 사용자를 볼 수 있습니다.
user pool 이 예에서 나는 두 명의 사용자를 만들었다
풀에서 사용자를 선택합니다.상태는 "확인되지 않음"입니다.이 강좌에서, 우리는'사용자 확인'단추를 누르면 수동으로 사용자를 확인할 것입니다.미래의 강좌에서, 나는 어떻게 사용자의 휴대전화나 이메일로 보내는 인증코드를 사용하여 자동으로 사용자를 확인하는지 보여 줄 것이다.
"사용자 확인"을 클릭하여 새 계정 활성화
사용자 로그인 테스트
방금 만든 사용자 로그인을 시도해 보겠습니다.
로그인 및 로그인 성공
이gif는 강제적입니다.
끝내다
아직도 나랑 같이 있어?이 점에서 우리는 우리의 응용 프로그램에 매우 기본적인 인증 시스템을 제공했다. 이 시스템은 AWS Cognito를 이용했다.신분 검증에 관해서는 또 다른 몇 가지 주제가 검토되어야 하지만, 그것들은 본 강좌의 범위를 넘어섰다.우리가 대처해야 할 다른 도전은 다음과 같다.
분석 이 시리즈
섹션 1:
섹션 2: Basic Setup
섹션 3: Authentication
섹션 4: Analytics
Reference
이 문제에 관하여(AWS Amplify 백엔드가 있는 Flatter 애플리케이션: 섹션 2 - 인증), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/thatflutterdude/flutter-apps-with-aws-amplify-backend-part-2-authentication-5d36텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)