【问题标题】:Firebase Multi Factor Authentication for a web app returns "auth/code-expired" errorWeb 应用程序的 Firebase 多因素身份验证返回“auth/code-expired”错误
【发布时间】:2021-08-28 16:12:39
【问题描述】:

我正在尝试对使用 Angular 构建的 Web 应用程序实施多因素身份验证,这会引发以下错误:"auth/code-expired", "SMS 代码已过期。请重新发送验证码再试一次。”即使我在一分钟内输入代码。

我已经手动将我的电话号码(iPhone)注册到 ID 平台,并且能够接收到我的手机的验证码。 另外,如果我将手机号和验证码输入ID平台进行开发,我可以毫无问题地登录。

我已阅读此问题,但似乎不适用于我的情况,因为当我收到验证码时身份验证状态不会改变。 The sms code has expired. Please re-send the verification code to try again

谁能告诉我怎么了?下面是我的代码。

    <section>
      <h4>Sign in with MFA</h4>
      <div class="flex">
        <input placeholder="Email" [(ngModel)]="email">
        <input placeholder="Password" [(ngModel)]="pass">
        <button (click)="onAuth()">Submit</button>
      </div>
    </section>

    <section>
      <div style="position:relative;z-index:10;width:100%;margin-top:2em;margin-left:2em;margin-right:auto;">
        <div id="recaptcha-container"></div>
      </div>
   </section>

   <section>
     {{ user$ | async | json }}
   </section>
import { Component } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase';
import { environment } from 'src/environments/environment';
firebase.default.initializeApp(environment.firebaseConfig);

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  email: string = 'myEmail@gmail.com';
  pass = 'myPassword';


  windowRef;
  resolver;
  user$: Observable<any>;

  constructor(
    private fireAuth: AngularFireAuth,
  ) { }

  ngOnInit(): void {
    this.user$ = this.fireAuth.user;
    this.windowRef = window;
    this.windowRef.recaptchaVerifier = new firebase.default.auth
      .RecaptchaVerifier(
        'recaptcha-container',
        {
          'size': 'invisible',
          'callback': (response) => {
            console.log('recapcha solved', response);
          }
        });
  }


  onAuth() {
    this.fireAuth.signInWithEmailAndPassword(this.email, this.pass)
      .then(result => {
        alert('Sign in Success');
      })
      .catch(err => {
        console.log('Sign-in catch block', err);
        if (err.code === 'auth/multi-factor-auth-required') {
          alert('MFA required');
          this.resolver = err.resolver;
          const selectedIndex = 0;
          // Ask user which second factor to use.
          if (this.resolver.hints[selectedIndex].factorId === firebase.default.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
            const phoneNumber = prompt('Enter your phone number with a country code (e.g. +18881231234).');
            const phoneInfoOptions = {
              multiFactorHint: this.resolver.hints[selectedIndex],
              session: this.resolver.session,
              phoneNumber
            };
            const phoneAuthProvider = new firebase.default.auth.PhoneAuthProvider();
            // Send SMS verification code
   
            return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions.phoneNumber, this.windowRef.recaptchaVerifier)
              .then((verificationId) => {
                // Ask user for the SMS verification code.
                const verificationCode = prompt('Enter the 6 digits verification code you received.');

                const cred = firebase.default.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
                const multiFactorAssertion =
                  firebase.default.auth.PhoneMultiFactorGenerator.assertion(cred);

                const result = this.resolver.resolveSignIn(multiFactorAssertion);
                console.log('result', result); // **throws auth/code-expired**

                // Complete sign-in.
                return result;
              })
              .then((userCredential) => {
                // User successfully signed in with the second factor phone number.
                console.log('MFA success', userCredential);

              });
          } else {
            // Unsupported second factor.
            console.log('Unsupported second factor.');

          }
        } else {
          alert('Sign in Failed');
        }
      });

  }

}



提前谢谢你。

【问题讨论】:

    标签: javascript angular firebase firebase-authentication multi-factor-authentication


    【解决方案1】:

    我已经解决了这个问题,但会留下记录。 以下代码不正确:

    // Incorrect
    
              if (this.resolver.hints[selectedIndex].factorId === firebase.default.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
                const phoneNumber = prompt('Enter your phone number with a country code (e.g. +18881231234).');
                const phoneInfoOptions = {
                  multiFactorHint: this.resolver.hints[selectedIndex],
                  session: this.resolver.session,
                  phoneNumber
                };
                const phoneAuthProvider = new firebase.default.auth.PhoneAuthProvider();
                // Send SMS verification code
       
                return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions.phoneNumber, this.windowRef.recaptchaVerifier)
                  .then((verificationId) => {...
    

    一旦我从 phoneInfoOptions 中取出 phoneNumber 并提供 phoneInfoOptions 来验证PhoneNumber(),MFA 就会成功通过。

    // Correct
    
              if (this.resolver.hints[selectedIndex].factorId === firebase.default.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
                prompt('Enter your phone number with a country code (e.g. +18881231234).');
                const phoneInfoOptions = {
                  multiFactorHint: this.resolver.hints[selectedIndex],
                  session: this.resolver.session,
                };
                const phoneAuthProvider = new firebase.default.auth.PhoneAuthProvider();
                // Send SMS verification code
       
                return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, this.windowRef.recaptchaVerifier)
                  .then((verificationId) => {...
    

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2017-08-31
      • 2019-11-22
      • 2020-05-14
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多