【问题标题】:Firebase user authentication for java application (Not Android)java应用程序的Firebase用户身份验证(非Android)
【发布时间】:2017-04-11 00:22:54
【问题描述】:

我想使用 firebase 为我的 java 应用程序创建一个用户身份验证表单。连接到实时数据库的依赖项可用,并且 Firebase Admin 的使用有据可查here

但目前 Firebase Admin 仅支持 Node.js 的用户身份验证,并记录在 here

这是我的测试代码。

public class Login {
    private JPanel jPanel;

    public static void main(String[] args) {
//        Show My Form
        JFrame jFrame = new JFrame("Login");
        jFrame.setContentPane(new Login().jPanel);
        jFrame.pack();
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);

//        Firebase
        FirebaseOptions options = null;
        try {
            options = new FirebaseOptions.Builder()
                    .setServiceAccount(new FileInputStream("xxx.json"))
                    .setDatabaseUrl("https://xxx.firebaseio.com/")
                    .build();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if (options != null) {
            FirebaseApp.initializeApp(options);
            DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Clip");
            ref.addValueEventListener(new ValueEventListener() {
                public void onDataChange(DataSnapshot dataSnapshot) {
                    System.out.println("ClipText = [" + dataSnapshot.getValue() + "]");
                }

                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }
}

谁能指导我如何为我的 java 应用程序创建用户身份验证(例如,使用电子邮件和密码创建用户、登录)?

注意:我正在使用 Gradle。

【问题讨论】:

    标签: java firebase firebase-authentication


    【解决方案1】:

    基于此处的 REST API 文档:https://firebase.google.com/docs/reference/rest/auth/ 我创建了一个这样的单例以从电子邮件和密码中获取有效令牌并使用 getAccountInfo 方法对其进行验证:

    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    
    public class FireBaseAuth {
    
        private static final String BASE_URL = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/";
        private static final String OPERATION_AUTH = "verifyPassword";
        private static final String OPERATION_REFRESH_TOKEN = "token";
        private static final String OPERATION_ACCOUNT_INFO = "getAccountInfo";
    
        private String firebaseKey;
    
        private static FireBaseAuth instance = null;
    
        protected FireBaseAuth() {
           firebaseKey = "YOUR FIREBASE KEY HERE";
        }
    
        public static FireBaseAuth getInstance() {
          if(instance == null) {
             instance = new FireBaseAuth();
          }
          return instance;
        }
    
        public String auth(String username, String password) throws Exception { 
    
            HttpURLConnection urlRequest = null;
            String token = null;
    
            try {
                URL url = new URL(BASE_URL+OPERATION_AUTH+"?key="+firebaseKey);
                urlRequest = (HttpURLConnection) url.openConnection();
                urlRequest.setDoOutput(true);
                urlRequest.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                OutputStream os = urlRequest.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                osw.write("{\"email\":\""+username+"\",\"password\":\""+password+"\",\"returnSecureToken\":true}");
                osw.flush();
                osw.close();
    
                urlRequest.connect();
    
                JsonParser jp = new JsonParser(); //from gson
                JsonElement root = jp.parse(new InputStreamReader((InputStream) urlRequest.getContent())); //Convert the input stream to a json element
                JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    
                token = rootobj.get("idToken").getAsString();
    
            } catch (Exception e) {
                return null;
            } finally {
                urlRequest.disconnect();
            }
    
            return token;
        }
    
        public String getAccountInfo(String token) throws Exception {
    
            HttpURLConnection urlRequest = null;
            String email = null;
    
            try {
                URL url = new URL(BASE_URL+OPERATION_ACCOUNT_INFO+"?key="+firebaseKey);
                urlRequest = (HttpURLConnection) url.openConnection();
                urlRequest.setDoOutput(true);
                urlRequest.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                OutputStream os = urlRequest.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                osw.write("{\"idToken\":\""+token+"\"}");
                osw.flush();
                osw.close();
                urlRequest.connect();
    
                JsonParser jp = new JsonParser(); //from gson
                JsonElement root = jp.parse(new InputStreamReader((InputStream) urlRequest.getContent())); //Convert the input stream to a json element
                JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    
                email = rootobj.get("users").getAsJsonArray().get(0).getAsJsonObject().get("email").getAsString();
    
            } catch (Exception e) {
                return null;
            } finally {
                urlRequest.disconnect();
            }
    
            return email;
    
        }
    
    }
    

    这不允许您动态创建用户,但假设他们已经在 Firebase 上创建了

    【讨论】:

      猜你喜欢
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 2021-07-31
      相关资源
      最近更新 更多