简体   繁体   English

匿名用户使用带角度和弹簧引导的 firebase 登录

[英]Anonymous user login using firebase with angular and spring boot

I am developing an Angular 10 app using spring boot as a server.我正在使用 Spring Boot 作为服务器开发 Angular 10 应用程序。 I want to anonymously login users using firebase, I use this for favorite items etc and I need the user to be logged in before the first backend request.我想使用 firebase 匿名登录用户,我将它用于最喜欢的项目等,我需要用户在第一个后端请求之前登录。 I added angularfire dependency, I sign in the user anonymously and I get the user token as follows:我添加了 angularfire 依赖项,我匿名登录用户并获得用户令牌,如下所示:

    this.auth.signInAnonymously()
      .catch(err =>
        //log the error
      );

    this.auth.onAuthStateChanged(user => {
      if (user) {
        const token =  user.getIdToken();

        user.getIdToken(true).then(idToken => {
          this.cookieService.set('Authorization', idToken);
        });
      }
    });

I added the token to the cookies because I want to use it on the backend side (and I don't want to make a filter to add it to every request as a header):我将令牌添加到 cookie 中,因为我想在后端使用它(并且我不想制作过滤器以将其作为标头添加到每个请求中):

FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(authCookie.get().getValue());

My problem is that after a while the token expires and on the backend I receive the following error:我的问题是,令牌过期一段时间后,在后端我收到以下错误:

Firebase ID token has expired. Firebase ID 令牌已过期。 Get a fresh ID token and try again获取新的 ID 令牌并重试

I can't figure out if I can refresh the token from the backend.我不知道是否可以从后端刷新令牌。 Is there any way to handle refreshing the token when it expires?有没有办法在令牌过期时处理刷新令牌? (before calling the backend with an expired token) (在使用过期令牌调用后端之前)

Can you give me an idea on how to design anonymous login without much delays and without retries?你能告诉我如何设计没有太多延迟和重试的匿名登录吗?

Best regards此致

You should add code to listen to change in the ID token, as it gets automatically refreshed every hour.您应该添加代码来监听 ID 令牌的变化,因为它每小时自动刷新一次。 Use onIdTokenChanged使用onIdTokenChanged

firebase.auth().onIdTokenChanged(function(user) {
  if (user) {
    // User is signed in or token was refreshed.
  }
});

You will need to update your cookie every time the callback triggers due to an ID token change.每次由于 ID 令牌更改而触发回调时,您都需要更新 cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM