새소식

개발일지

UniNuri (9) : Amplify Authentication

  • -

커뮤니티에서 가장 중요한 인증 부분을 하였다.
 
공식문서 : https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios/#option-1-use-the-authenticator-ui-component

 

https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios/#option-1-use-the-authenticator-ui-component

docs.amplify.aws

 

이 공식문서에서 주의해야 할 점이 Amplify CLI를 사용하는 버전과 Amplify Studio를 사용하는 버전이 나누어져있는데
 
실수로 Amplify CLI 버전으로 세팅을 하여 프로젝트를 다시 만들기도 하고 오래 걸렸다.
 
구현하면서 나왔던 오류들을 다시 리마인드 해보았다.
 

1. App ID가 일치하지 않음 → 백엔드 다시 구현..


Amplify CLI로 만들었을 때 나왔던 오류인데, 이거는 도저히 찾아봐도 해결법이 없고 stackoverflow나 github에서는
모두 Amplify를 다시 Setting 하였다고 빠르게 다시 Setting 했다.
 
 

2. failed to initialize amplify with pluginerror: unable to decode configuration
Recovery suggestion: Make sure the plugin configuration is JSONValue

 
결국 모든 프로젝트를 다 날려버리고 다시 만들었을 때 나왔던 에러이다. 
찾아봤을 때는 AwsConfig파일들이 잘못되었다는 거 정도만 알게 되었는데 해결을 어떻게 해야 될지 몰랐지만
아래 코드를 입력하여 해결하였다.
 

amplify init

amplify add auth

amplify push

내 경우에는 init을 하지 않아서 발생하였다.

 


연동에 성공하고 회원가입과 로그인 관련 코드가 적혀있는 공식 문서이다.
공식문서 : https://docs.amplify.aws/lib/auth/signin/q/platform/ios/#sign-in-a-user

 

https://docs.amplify.aws/lib/auth/signin/q/platform/ios/#sign-in-a-user

docs.amplify.aws



- 회원가입

// 회원가입
func signUp(username: String, password: String, email: String) async {
    let userAttributes = [AuthUserAttribute(.email, value: email)]
    let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
    do {
        let signUpResult = try await Amplify.Auth.signUp(
            username: username,
            password: password,
            options: options
        )
        if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
            print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
        } else {
            print("SignUp Complete")
        }
        
        // 회원가입 성공 시 다음 ViewController로 이동
        guard let vc = self.storyboard?.instantiateViewController(withIdentifier: "EmailCheckVC") as? EmailCheckViewController else{return}
        vc.userid = self.idTextField.text!
        self.navigationController?.popToViewController(vc, animated: true)
        
    } catch let error as AuthError {
        print("An error occurred while registering a user \(error)")
    } catch {
        print("Unexpected error: \(error)")
    }
}

 
 

- 회원가입 성공 후 이메일 인증

func confirmSignUp(for username: String, with confirmationCode: String) async {
        do {
            let confirmSignUpResult = try await Amplify.Auth.confirmSignUp(
                for: username,
                confirmationCode: confirmationCode
            )
            
            // 인증 성공
            print("Confirm sign up result completed: \(confirmSignUpResult.isSignUpComplete)")
            guard let vc = self.storyboard?.instantiateViewController(withIdentifier: "EmailLoginVC") as? EmailLoginViewController else{return}
            self.present(vc, animated: true)
            
        } catch let error as AuthError {
            print("An error occurred while confirming sign up \(error)")
        } catch {
            print("Unexpected error: \(error)")
        }
}

 

- 로그인

// 로그인
func signIn(username: String, password: String) async {
    do {
        let signInResult = try await Amplify.Auth.signIn(
            username: username,
            password: password
            )
        if signInResult.isSignedIn {
       	// 인증 성공
            print("Sign in succeeded")
            guard let vc = self.storyboard?.instantiateViewController(withIdentifier: "MainVC") as? MainViewController else{return}
            self.navigationController?.pushViewController(vc, animated: true)

        }
    } catch let error as AuthError {
        print("Sign in failed \(error)")
    } catch {
        print("Unexpected error: \(error)")
    }
}

 

로그인을 성공하고 모든 앱을 사용할 때 보면 자동 로그인이 활성화된다. 자동로그인도 구현해 보자
맨 처음 앱을 실행하는 ViewController(Is Initial ViewController)에 구현하면 된다.
 

- 자동로그인

// 로그인 상태확인
func fetchCurrentAuthSession() async {
    do {
        let session = try await Amplify.Auth.fetchAuthSession()
        print("Is user signed in - \(session.isSignedIn)")
		
        // 로그인 되어 있을 때
        if(session.isSignedIn == true){
            guard let vc = self.storyboard?.instantiateViewController(withIdentifier: "MainVC") as? MainViewController else{return}
            self.navigationController?.pushViewController(vc, animated: true)
        }


    } catch let error as AuthError {
        print("Fetch session failed with error \(error)")
    } catch {
        print("Unexpected error: \(error)")
    }
}

 

잠시 Test 할 때 사용했던 로그아웃 코드이다.
 

- 로그아웃 

//로그아웃
func signOutLocally() async {
    let result = await Amplify.Auth.signOut()
    if let signOutResult = result as? AWSCognitoSignOutResult {
        print("Local signout successful: \(signOutResult.signedOutLocally)")
        switch signOutResult {
        case .complete:
            print("SignOut completed")
        case .failed(let error):
            print("SignOut failed with \(error)")
        case let .partial(revokeTokenError, globalSignOutError, hostedUIError):
            print(
            """
            SignOut is partial.
            RevokeTokenError: \(String(describing: revokeTokenError))
            GlobalSignOutError: \(String(describing: globalSignOutError))
            HostedUIError: \(String(describing: hostedUIError))
            """
            )
        }
    }
}
728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.