다단계 사용자 작업
이 문서에서는 다단계 인증에 등록된 Identity Platform 사용자로 일반적인 태스크를 수행하는 방법을 설명합니다.
사용자 이메일 업데이트
다단계 사용자는 항상 확인된 이메일 주소를 가지고 있어야 합니다. 이를 통해 악의적인 행위자가 자신이 소유하지 않은 이메일에 앱을 등록한 후 두 번째 단계를 추가하여 실제 소유자의 접근을 막는 일을 방지할 수 있습니다.
사용자 이메일을 업데이트하려면 verifyBeforeUpdateEmail()
메서드를 사용합니다. updateEmail()
과 달리, 이 메서드를 사용하려면 Identity Platform에서 이메일 주소를 업데이트하기 전에 사용자가 확인 링크를 따라야 합니다. 예를 들면 다음과 같습니다.
웹 버전 8
var user = firebase.auth().currentUser;
user.verifyBeforeUpdateEmail(newEmail).then(function() {
// Email sent.
// User must click the email link before the email is updated.
}).catch(function(error) {
// An error happened.
});
웹 버전 9
import { getAuth, verifyBeforeUpdateEmail } from "firebase/auth";
const auth = getAuth(firebaseApp);
verifyBeforeUpdateEmail(auth.currentUser, newEmail).then(() => {
// Email sent.
// User must click the email link before the email is updated.
}).catch((error) => {
// An error happened.
});
iOS
let user = Auth.auth().currentUser
user.verifyBeforeUpdateEmail(newEmail, completion: { (error) in
if error != nil {
// An error happened.
}
// Email sent.
// User must click the email link before the email is updated.
})
Android
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.verifyBeforeUpdateEmail(newEmail)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Email sent.
// User must click the email link before the email is updated.
} else {
// An error occurred.
}
}
});
기본적으로 Identity Platform은 사용자에게 이메일을 보내고 확인을 처리하는 간단한 웹 기반 핸들러를 제공합니다. 이 흐름을 맞춤설정할 수 있는 몇 가지 방법이 있습니다.
확인 이메일 현지화
Identity Platform에서 보낸 이메일을 현지화하려면 verifyBeforeUpdateEmail()
을 호출하기 전에 언어 코드를 설정합니다.
웹 버전 8
firebase.auth().languageCode = 'fr';
웹 버전 9
import { getAuth } from "firebase/auth";
const auth = getAuth();
auth.languageCode = 'fr';
iOS
Auth.auth().languageCode = 'fr';
Android
FirebaseAuth.getInstance().setLanguageCode("fr");
추가 상태 전달
작업 코드 설정을 사용하여 확인 메일에 추가 상태를 포함하거나 모바일 앱에서 인증을 처리할 수 있습니다. 예를 들면 다음과 같습니다.
웹 버전 8
var user = firebase.auth().currentUser;
var actionCodeSettings = {
url: 'https://www.example.com/completeVerification?state=*****',
iOS: {
bundleId: 'com.example.ios'
},
android: {
packageName: 'com.example.android',
installApp: true,
minimumVersion: '12'
},
handleCodeInApp: true,
// When multiple custom dynamic link domains are defined, specify which
// one to use.
dynamicLinkDomain: "example.page.link"
};
user.verifyBeforeUpdateEmail(newEmail, actionCodeSettings).then(function() {
// Email sent.
// User must click the email link before the email is updated.
}).catch(function(error) {
// An error happened.
});
웹 버전 9
import { getAuth, verifyBeforeUpdateEmail } from "firebase/auth";
const auth = getAuth(firebaseApp);
const user = auth.currentUser
const actionCodeSettings = {
url: 'https://www.example.com/completeVerification?state=*****',
iOS: {
bundleId: 'com.example.ios'
},
android: {
packageName: 'com.example.android',
installApp: true,
minimumVersion: '12'
},
handleCodeInApp: true,
// When multiple custom dynamic link domains are defined, specify which
// one to use.
dynamicLinkDomain: "example.page.link"
};
verifyBeforeUpdateEmail(auth.currentUser, newEmail, actionCodeSettings).then(() => {
// Email sent.
// User must click the email link before the email is updated.
}).catch((error) => {
// An error happened.
})
iOS
var actionCodeSettings = ActionCodeSettings.init()
actionCodeSettings.canHandleInApp = true
let user = Auth.auth().currentUser()
actionCodeSettings.URL =
String(format: "https://www.example.com/?email=%@", user.email)
actionCodeSettings.iOSbundleID = Bundle.main.bundleIdentifier!
actionCodeSettings.setAndroidPakageName("com.example.android",
installIfNotAvailable:true,
minimumVersion:"12")
// When multiple custom dynamic link domains are defined, specify which one to use.
actionCodeSettings.dynamicLinkDomain = "example.page.link"
user.sendEmailVerification(withActionCodeSettings:actionCodeSettings { error in
if error != nil {
// Error occurred. Inspect error.code and handle error.
return
}
// Email verification sent.
})
user.verifyBeforeUpdateEmail(newEmail, actionCodeSettings, completion: { (error) in
if error != nil {
// An error happened.
}
// Email sent.
// User must click the email link before the email is updated.
})
Android
ActionCodeSettings actionCodeSettings =
ActionCodeSettings.newBuilder()
.setUrl("https://www.example.com/completeVerification?state=*****")
.setHandleCodeInApp(true)
.setAndroidPackageName(
"com.example.android",
/* installIfNotAvailable= */ true,
/* minimumVersion= */ null)
.setIOSBundleId("com.example.ios")
// When multiple custom dynamic link domains are defined, specify
// which one to use.
.setDynamicLinkDomain("example.page.link")
.build();
FirebaseUser multiFactorUser = FirebaseAuth.getInstance().getCurrentUser();
multiFactorUser
.verifyBeforeUpdateEmail(newEmail, actionCodeSettings)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Email sent.
// User must click the email link before the email is updated.
} else {
// An error occurred.
}
}
});
인증 핸들러 맞춤설정
이메일 확인을 처리하는 자체 핸들러를 만들 수 있습니다. 다음 예시에서는 작업 코드를 적용하기 전에 작업 코드를 확인하고 메타데이터를 검사하는 방법을 보여줍니다.
웹 버전 8
var email;
firebase.auth().checkActionCode(actionCode)
.then(function(info) {
// Operation is equal to
// firebase.auth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL
var operation = info['operation'];
// This is the old email.
var previousEmail = info['data']['previousEmail'];
// This is the new email the user is changing to.
email = info['data']['email'];
// TODO: Display a message to the end user that the email address of the account is
// going to be changed from `fromEmail` to `email`
// …
// On confirmation.
return firebase.auth().applyActionCode(actionCode)
}).then(function() {
// Confirm to the end user the email was updated.
showUI('You can now sign in with your new email: ' + email);
})
.catch(function(error) {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
});
웹 버전 9
import { getAuth, checkActionCode, applyActionCode} from "firebase/auth";
const auth = getAuth(firebaseApp);
var email;
checkActionCode(auth, actionCode)
.then((info) => {
// Operation is equal to
// ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL
const operation = info['operation'];
// This is the old email.
const previousEmail = info['data']['previousEmail'];
// This is the new email the user is changing to.
email = info['data']['email'];
// TODO: Display a message to the end user that the email address of the account is
// going to be changed from `fromEmail` to `email`
// …
// On confirmation.
return applyActionCode(auth, actionCode)
}).then(() => {
// Confirm to the end user the email was updated.
showUI('You can now sign in with your new email: ' + email);
})
.catch((error) => {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
});
iOS
Auth.auth().checkActionCode(actionCode) { info, error in
if error != nil {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
return
}
// This is the new email the user is changing to.
let email = info?.email
// This is the old email.
let oldEmail = info?.previousEmail
// operation is equal to
// firebase.auth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL
let operation = info?.operation
// TODO: Display a message to the end user that the email address of the account is
// going to be changed from `fromEmail` to `email`
// …
// On confirmation.
return Auth.auth().applyActionCode(actionCode)
}
Android
FirebaseAuth.getInstance().checkActionCode(actionCode).addOnCompleteListener(
new OnCompleteListener<ActionCodeResult>() {
@Override
public void onComplete(@NonNull Task<ActionCodeResult> task) {
if (!task.isSuccessful()) {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
return;
}
ActionCodeResult result = task.getResult();
// This maps to VERIFY_AND_CHANGE_EMAIL.
int operation = result.getOperation();
if (operation == ActionCodeResult.VERIFY_AND_CHANGE_EMAIL) {
ActionCodeEmailInfo actionCodeInfo =
(ActionCodeEmailInfo) result.getInfo();
String fromEmail = actionCodeInfo.getFromEmail();
String email = actionCodeInfo.getEmail();
// TODO: Display a message to the user that the email address
// of the account is changing from `fromEmail` to `email` once
// they confirm.
}
}
});
자세한 내용은 커스텀 이메일 작업 핸들러 만들기에 대한 Firebase 문서를 참조하세요.
사용자 재인증하기
사용자가 이미 로그인한 경우에도 다음과 같은 민감한 작업을 수행하기 전에 재인증해야 할 수 있습니다.
- 비밀번호 변경
- 새로운 두 번째 단계 추가 또는 삭제
- 주소와 같은 개인정보 업데이트
- 금융 거래 실행
- 사용자 계정 삭제
이메일과 비밀번호로 사용자를 다시 인증하려면 다음 안내를 따르세요.
웹
var resolver;
var credential = firebase.auth.EmailAuthProvider.credential(
firebase.auth().currentUser.email, password);
firebase.auth().currentUser.reauthenticateWithCredential(credential)
.then(function(userCredential) {
// User successfully re-authenticated and does not require a second factor challenge.
// ...
})
.catch(function(error) {
if (error.code == 'auth/multi-factor-auth-required') {
// Handle multi-factor authentication.
} else {
// Handle other errors.
}
});
iOS
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
Auth.auth().currentUser.reauthenticate(with: credential, completion: { (result, error) in
let authError = error as NSError?
if (authError == nil || authError!.code != AuthErrorCode.secondFactorRequired.rawValue) {
// User is not enrolled with a second factor or is successfully signed in.
} else {
// Handle multi-factor authentication.
}
})
Android
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
AuthCredential credential = EmailAuthProvider.getCredential(user.getEmail(), password);
user.reauthenticate(credential)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// User successfully re-authenticated and does not
// require a second factor challenge.
// ...
return;
}
if (task.getException() instanceof FirebaseAuthMultiFactorException) {
// Handle multi-factor authentication.
} else {
// Handle other errors.
}
}
});
Microsoft와 같은 OAuth 공급업체를 사용하여 다시 인증하려면 다음 단계를 따르세요.
웹
var resolver;
var user = firebase.auth().currentUser;
// Ask the user to re-authenticate with Microsoft.
var provider = new firebase.auth.OAuthProvider('microsoft.com');
// Microsoft provider allows the ability to provide a login_hint.
provider.setCustomParameters({
login_hint: user.email
});
user.reauthenticateWithPopup(provider)
.then(function(userCredential) {
// User successfully re-authenticated and does not require a second factor challenge.
// ...
})
.catch(function(error) {
if (error.code == 'auth/multi-factor-auth-required') {
// Handle multi-factor authentication.
} else {
// Unsupported second factor.
} else {
// Handle other errors.
}
});
iOS
var provider = OAuthProvider(providerID: "microsoft.com")
// Replace nil with the custom class that conforms to AuthUIDelegate
// you created in last step to use a customized web view.
provider.getCredentialWith(nil) { credential, error in
Auth.auth().currentUser.reauthenticate(with: credential, completion: { (result, error) in
let authError = error as NSError?
if (authError == nil || authError!.code != AuthErrorCode.secondFactorRequired.rawValue) {
// User is not enrolled with a second factor or is successfully signed in.
// ...
} else {
// Handle multi-factor authentication.
}
}
})
Android
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
OAuthProvider.Builder provider = OAuthProvider.newBuilder("microsoft.com");
provider.addCustomParameter("login_hint", user.getEmail());
user.startActivityForReauthenticateWithProvider(/* activity= */ this, provider.build())
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// User successfully re-authenticated and does not
// require a second factor challenge.
// ...
return;
}
if (task.getException() instanceof FirebaseAuthMultiFactorException) {
// Handle multi-factor authentication.
} else {
// Handle other errors such as wrong password.
}
}
});
최근에 추가된 두 번째 단계 취소
사용자가 두 번째 단계를 등록하면 Identity Platform은 이메일로 알림을 전송합니다. 승인되지 않은 활동을 방지하기 위해 이메일에는 두 번째 단계 추가를 되돌리는 옵션이 포함되어 있습니다.
Identity Platform은 기본 이메일 템플릿과 핸들러를 제공하지만 직접 만들 수도 있습니다. 다음 예시는 커스텀 핸들러를 만드는 방법을 보여줍니다.
웹 버전 8
var obfuscatedPhoneNumber;
firebase.auth().checkActionCode(actionCode)
.then(function(info) {
// operation is equal to
// firebase.auth.ActionCodeInfo.Operation.REVERT_SECOND_FACTOR_ADDITION
var operation = info['operation'];
// info.data.multiFactorInfo contains the data corresponding to the
// enrolled second factor that the user is revoking.
var multiFactorInfo = info['data']['multiFactorInfo'];
obfuscatedPhoneNumber = multiFactorInfo['phoneNumber'];
var displayName = multiFactorInfo['displayName'];
// TODO: Display a message to the end user about the second factor that
// was enrolled before the user can confirm the action to revert it.
// ...
// On confirmation.
return firebase.auth().applyActionCode(actionCode)
}).then(function() {
// Confirm to the end user the phone number was removed from the account.
showUI('The phone number ' + obfuscatedPhoneNumber +
' has been removed as a second factor from your account.' +
' You may also want to reset your password if you suspect' +
' your account was compromised.');
})
.catch(function(error) {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
});
웹 버전 9
const {
getAuth,
checkActionCode,
applyActionCode
} = require("firebase/auth");
const auth = getAuth(firebaseApp);
var obfuscatedPhoneNumber;
checkActionCode(auth, actionCode)
.then((info) => {
// Operation is equal to
// ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION
const operation = info['operation'];
// info.data.multiFactorInfo contains the data corresponding to the
// enrolled second factor that the user is revoking.
var multiFactorInfo = info['data']['multiFactorInfo'];
obfuscatedPhoneNumber = multiFactorInfo['phoneNumber'];
const displayName = multiFactorInfo['displayName'];
// TODO: Display a message to the end user about the second factor that
// was enrolled before the user can confirm the action to revert it.
// ...
// On confirmation.
return applyActionCode(auth, actionCode)
}).then(() => {
// Confirm to the end user the phone number was removed from the account.
showUI('The phone number ' + obfuscatedPhoneNumber +
' has been removed as a second factor from your account.' +
' You may also want to reset your password if you suspect' +
' your account was compromised.');
})
.catch((error) => {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
});
iOS
Auth.auth().checkActionCode(actionCode) { info, error in
if error != nil {
// Error occurred during confirmation. The code might have expired or the
// link has been used before.
return
}
// This is the new email the user is changing to.
let email = info?.email
// This is the old email.
let oldEmail = info?.previousEmail
// operation is equal to
// firebase.auth.ActionCodeInfo.Operation.REVERT_SECOND_FACTOR_ADDITION
let operation = info?.operation
// info.multiFactorInfo contains the data corresponding to the enrolled second
// factor that the user is revoking.
let multiFactorInfo = info?.multiFactorInfo
let obfuscatedPhoneNumber = (multiFactorInfo as! PhoneMultiFactorInfo).phone
// TODO: Display a message to the end user that the email address of the account is
// going to be changed from `fromEmail` to `email`
// …
// On confirmation.
return Auth.auth().applyActionCode(actionCode)
}
Android
FirebaseAuth.getInstance()
.checkActionCode(actionCode)
.continueWithTask(
new Continuation<ActionCodeResult, Task<Void>>() {
@Override
public Task<Void> then(Task<ActionCodeResult> task) throws Exception {
if (!task.isSuccessful()) {
// Error occurred during confirmation. The code might have expired
// or the link has been used before.
return Tasks.forException(task.getException());
}
ActionCodeResult result = task.getResult();
// The operation is equal to ActionCodeResult.REVERT_SECOND_FACTOR_ADDITION.
int operation = result.getOperation();
// The ActionCodeMultiFactorInfo contains the data corresponding to
// the enrolled second factor that the user is revoking.
ActionCodeMultiFactorInfo actionCodeInfo =
(ActionCodeMultiFactorInfo) result.getInfo();
PhoneMultiFactorInfo multiFactorInfo =
(PhoneMultiFactorInfo) actionCodeInfo.getMultiFactorInfo();
String obfuscatedPhoneNumber = multiFactorInfo.getPhoneNumber();
String displayName = multiFactorInfo.getDisplayName();
// We can now display a message to the end user about the second
// factor that was enrolled before they confirm the action to revert
// it.
// ...
// On user confirmation:
return FirebaseAuth.getInstance().applyActionCode(actionCode);
}
})
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// Display a message to the user that the second factor
// has been reverted.
}
}
});
자세한 내용은 커스텀 이메일 작업 핸들러 만들기에 대한 Firebase 문서를 참조하세요.
두 번째 단계 복구
Identity Platform에는 두 번째 단계를 복구하는 메커니즘이 내장되어 있지 않습니다. 사용자가 두 번째 단계에 액세스하지 못하면 계정에 액세스할 수 없게 됩니다. 이를 방지하려면 다음을 검토하세요.
- 두 번째 단계 없이 계정에 액세스할 수 없다는 사용자 경고
- 사용자가 백업 보조 단계를 등록하도록 강력히 유도
- Admin SDK를 사용하여 사용자가 ID를 충분히 확인할 수 있는 경우(예: 복구 키 업로드 또는 개인정보 질문 답변) 다단계 인증을 사용 중지하는 복구 흐름 빌드
- 지원팀에 사용자 계정을 관리(두 번째 단계 삭제 포함)할 수 있는 권한을 부여하고 사용자가 계정에 액세스할 수 없는 경우 문의할 수 있는 옵션 제공
비밀번호를 재설정해도 다단계 인증을 우회할 수 없습니다.
sendPasswordResetEmail()
을 사용하여 사용자의 비밀번호를 재설정하더라도 새 비밀번호로 로그인할 때 다단계 질문을 통과해야 합니다.
두 번째 단계 등록 해제
두 번째 요소를 등록 해제하려면 사용자의 등록된 단계 목록에서 단계를 가져온 다음 unenroll()
을 호출합니다. 이 작업은 민감한 작업이므로 최근에 로그인하지 않은 경우 사용자를 다시 인증해야 합니다.
웹 버전 8
var options = user.multiFactor.enrolledFactors;
// Ask user to select from the enrolled options.
return user.multiFactor.unenroll(options[selectedIndex])
.then(function() {
// User successfully unenrolled selected factor.
});
웹 버전 9
const multiFactorUser = multiFactor(auth.currentUser);
const options = multiFactorUser.enrolledFactors
// Ask user to select from the enrolled options.
return multiFactorUser.unenroll(options[selectedIndex])
.then(() =>
// User successfully unenrolled selected factor.
});
iOS
// Ask user to select from the enrolled options.
user?.multiFactor.unenroll(with: (user?.multiFactor.enrolledFactors[selectedIndex])!,
completion: { (error) in
// ...
})
Android
List<MultiFactorInfo> options = user.getMultiFactor().getEnrolledFactors();
// Ask user to select from the enrolled options.
user.getMultiFactor()
.unenroll(options.get(selectedIndex))
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Successfully un-enrolled.
}
}
});
두 번째 단계를 삭제한 후 사용자가 로그아웃할 수도 있습니다.
이러한 케이스를 리슨하려면 onAuthStateChanged()
를 사용하고 사용자에게 다시 로그인하도록 요청합니다.
다음 단계
다단계 사용자를 프로그래매틱 방식으로 관리합니다.