Firebase Auth在Spring Boot中未能初始化

huangapple go评论93阅读模式
英文:

Firebase Auth not getting initialized in spring boot

问题

我在我的Spring Boot应用程序(API应用程序)中使用Firebase Admin SDK。

在IntelliJ中本地运行时,一切正常。但是在部署到Tomcat时,出现空指针异常(NPE)。

在Spring Boot应用程序中:

public static void main(String[] args) {
    SpringApplication.run(InfanoApplication.class, args);

    try {
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();

        File file = new File(classloader.getResource("firebase2.json").getFile());
        logger.info("FILE PATH : " + file.getAbsolutePath());
        FileInputStream serviceAccount = new FileInputStream(file.getAbsolutePath());

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl(FB_BASE_URL)
                .build();

        firebaseApp = FirebaseApp.initializeApp(options);
        logger.info("FIREBASE NAME : " + firebaseApp.getName());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

在API代码中:

userRecord = FirebaseAuth.getInstance(InfanoApplication.firebaseApp).getUserByPhoneNumber(mobile);

错误信息:

java.lang.NullPointerException
	at com.google.firebase.ImplFirebaseTrampolines.getService(ImplFirebaseTrampolines.java:62)
	at com.google.firebase.auth.FirebaseAuth.getInstance(FirebaseAuth.java:101)

有人能帮忙解决这个问题吗?提前谢谢。

英文:

I am using firebase admin sdk in my spring boot app. (API app)

When I run locally in intelliJ its working fine. But when deployed in tomcat its giving me NPE.

In Springboot application

 public static void main(String[] args) {
    SpringApplication.run(InfanoApplication.class, args);

    try {
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();

        File file = new File(classloader.getResource("firebase2.json").getFile());
        logger.info("FILE PATH : " + file.getAbsolutePath());
        FileInputStream serviceAccount = new FileInputStream(file.getAbsolutePath());

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl(FB_BASE_URL)
                .build();

        firebaseApp = FirebaseApp.initializeApp(options);
        logger.info("FIREBASE NAME : "+firebaseApp.getName());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

In API code

userRecord = FirebaseAuth.getInstance(InfanoApplication.firebaseApp).getUserByPhoneNumber(mobile);

ERROR:

java.lang.NullPointerException
at com.google.firebase.ImplFirebaseTrampolines.getService(ImplFirebaseTrampolines.java:62)
at com.google.firebase.auth.FirebaseAuth.getInstance(FirebaseAuth.java:101)

Can someone help in fixing this issue. Thank you in advance.

答案1

得分: 4

你不应该在主方法中像这样创建 Firebase 的实例。很可能你的服务账户没有在正确的类路径中被找到。我会创建一个 Spring 配置,在应用程序启动时创建一个 Firebase 应用。我已经将我的服务账户放在 resources 文件夹的根目录下。

@Configuration
public class FirebaseConfig {

    //TODO: 在你的情况下可能会有其他配置
    @Value(value = "classpath:serviceAccount.json")
    private Resource serviceAccountResource;

    @Bean
    public FirebaseApp createFireBaseApp() throws IOException {
        InputStream serviceAccount = serviceAccountResource.getInputStream();

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl("<db-url>")
                .setStorageBucket("<storage-url>")
                .build();

        //添加日志记录
        System.out.println("Firebase 配置已初始化");

        return FirebaseApp.initializeApp(options);
    }

    
    @Bean
    @DependsOn(value = "createFireBaseApp")
    public StorageClient createFirebaseStorage() {
        return StorageClient.getInstance();
    }

    @Bean
    @DependsOn(value = "createFireBaseApp")
    public FirebaseAuth createFirebaseAuth() {
        return FirebaseAuth.getInstance();
    }

    @Bean
    @DependsOn(value = "createFireBaseApp")
    public FirebaseDatabase createFirebaseDatabase() {
        return FirebaseDatabase.getInstance();
    }

    @Bean
    @DependsOn(value = "createFireBaseApp")
    public FirebaseMessaging createFirebaseMessaging() {
        return FirebaseMessaging.getInstance();
    }
}

现在,如果我想在任何一个服务类中使用 Firebase Auth,我只需执行以下操作:

@Service
class MyService {

    @Autowired
    private FirebaseAuth firebaseAuth;

    //TODO: 可能应该有返回类型
    public void findUser(String mobile) {
        firebaseAuth.getUserByPhoneNumber(mobile);
    }
}
英文:

You shouldn't create an instance of Firebase like this in the main method. Probably your service account is not being found in the proper classpath. I would create a Spring Configuration which creates a Firebase app on application startup. I have kept my service account in the root of resources folder.

@Configuration
public class FirebaseConfig {

    //TODO: In your case maybe something else
    @Value(value = &quot;classpath:serviceAccount.json&quot;)
    private Resource serviceAccountResource;

    @Bean
    public FirebaseApp createFireBaseApp() throws IOException {
        InputStream serviceAccount = serviceAccountResource.getInputStream();

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl(&quot;&lt;db-url&gt;&quot;)
                .setStorageBucket(&quot;&lt;storage-url&gt;&quot;)
                .build();

        //Add loggers
        System.out.println(&quot;Firebase config initialized&quot;);

        return FirebaseApp.initializeApp(options);
    }

    
    @Bean
    @DependsOn(value = &quot;createFireBaseApp&quot;)
    public StorageClient createFirebaseStorage() {
        return StorageClient.getInstance();
    }

    @Bean
    @DependsOn(value = &quot;createFireBaseApp&quot;)
    public FirebaseAuth createFirebaseAuth() {
        return FirebaseAuth.getInstance();
    }

    @Bean
    @DependsOn(value = &quot;createFireBaseApp&quot;)
    public FirebaseDatabase createFirebaseDatabase() {
        return FirebaseDatabase.getInstance();
    }

    @Bean
    @DependsOn(value = &quot;createFireBaseApp&quot;)
    public FirebaseMessaging createFirebaseMessaging() {
        return FirebaseMessaging.getInstance();
    }
}

Now if I want to use Firebase Auth in any of my service classes I would just do the following:

@Service
class MyService {

    @Autowired
    private FirebaseAuth firebaseAuth;

    //TODO: Probably should have return type
    public void findUser(String mobile) {
        firebaseAuth.getUserByPhoneNumber(mobile);
    }
}

huangapple
  • 本文由 发表于 2020年8月26日 03:57:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63586220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定