简体   繁体   中英

Connection methods to Google Cloud SQL Database with Java JDBC

Currently, I have created a simple Java application that connects to my Google Cloud SQL database the normal way:

try {
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://-google-cloud-sql-ip:-port-/-projectname-","-user-","-password-");
   Statement st = con.createStatement();
}
catch (Exception ex) {
   ex.printStackTrace();
}

My only concern is that the password is placed here as plain text. It is not protected in any way. I do know that it is possible to protect the source code with something like yGuard . Also, I have to register my external IP address in Google Cloud for it to work.

Therefore, I was wondering if I could use some sort of OAuth method to make a database connection to the Cloud SQL database. I'd prefer a connection method that is independent of my computer's physical location, so I can connect anywhere I want (if I have an internet connection).

Is there a better method than the one presented above, or is this the only way? And if so, please let me know how to protect the plain text password.

Any help is much appreciated!

It is not possible to use OAuth2 to authenticate connections to Cloud SQL. You could use an OAuth2 authenticated API call to create a new, temporary username/password pair (and/or authorize an IP) and then use that to connect, however this does not add any extra safety over simply embedding credentials in your application.

As Razvan suggests in his comment connecting directly to your Cloud SQL instance from your Android app is almost certainly going to be insecure. Moreover it will be impossible for you to do schema changes in the future as you will have old versions of the app in the wild that you cannot control the upgrading of.

Here are a few alternatives:

  • Use Firebase , which is designed for secure database use from mobile and javascript.
  • Develop your own database-backed API to serve your mobile app's needs. Each bit of data to be set or retrieved by your app can have a separate API call, which can do any authorization or validation you need before making the actual database call. You can use Google Cloud Endpoints to do much of this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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