I've designed ForgotMyPassword.java jFrame Form on NetBeans IDE 8.2
wherein I'm using phpMyAdmin for fetching the E-Mail Address of registered users from it and sending it to their E-Mail Addresses through MYSQL Database using JavaMail
I basically want to fetch the E-Mail Address of registered users from it and send it to their E-Mail Addresses through MYSQL Database using JavaMail as One Time Password (OTP) recovery option
Here's the source code :
String username = usrnmfield.getText();
String email = emailID.getText();
String[] to = {"emailaddr#gmail.com"};
Connection conn=null;
PreparedStatement pstn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection db = DriverManager.getConnection("jdbc:mysql://localhost:3307/app" , "xxxx" , "xxxx");
pstn=db.prepareStatement("select * from register where USERNAME=? and EMAIL=?");
pstn.setString(1,username);
pstn.setString(2,email);
ResultSet i=pstn.executeQuery();
if(i.next())
{
if(JavaMail.send
("abc#gmail.com",
"xxxx",
to,
"Hello world",
"Thank you for reading my post"))
{
JOptionPane.showMessageDialog(null , " Please Check out your Inbox for any Password sent by us to you ");
}
}
else if (usrnmfield != i && emailID != i)
{
JOptionPane.showMessageDialog(null, "Wrong Username or E-Mail ID");
}
} catch(HeadlessException | ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
Some remarks and adjustements that could help:
Concerning your application design you should strongly consider another architecture. It is far not recommended to let a client (desktop) app work directly with the SQL database for security matters. Implementing the whole security on the client-side is obviously a bad idea (and will get bypassed easily) as well as it will be unmanageable. Consider using a centralized secure database on a distant also secure server that provides state-of-the-art authentication and authorization mecanisms (eg. through REST-API over HTTPS). Server-side security frameworks include Keycloak, SpringSecurity, Apache Shiro, JaaS... By searching the Web you will see that your design is not so common. Moreover for OTP the use of a Web server or simply remote exchanges seem obvious (and you will need them). You may also consider implement logging through a centralized LDAP server.
Name your fields in the select statement. Eg. "select password from register where ..." so that you know what you expect in order OR use the field name when using select *:
ResultSet rs = ...
String myValue = rs.getString(1);
String myValueBis = rs.getString("password");
Always surround your database queries with a try-finally block in order to close your ResultSet, the prepared statement and eventually the connection (if not reused) and preferably in this order.
I don't see the purpose of this condition:
else if (usrnmfield != i && emailID != i) { ...
You are comparing text fields against a ResultSet but neither the value contained in the text nor the values of the current row of the ResultSet (cf. 1). This makes no sense.
If you want to allow you user to retrieve its password based on its username or its e-mail you should consider using an "OR" (instead of "and") in your SQL statement.
When using JavaMail you must make sure that your Session contains enough information to send an email. It is generally the first step in any JavaMail app to create a javax.mail.Session object. So you need to configure the smtp server or relay, eventually the port and authentication. As you don't show the code of your JavaMail class I suggest you put it in your original question if you have any issue about it and clarify what is the problem (if any).
Generally speaking if you consider using this app for commercial use or some serious purpose you should also quickly think about storing your passwords in an encrypted way (eg. as SHA-256). And also think about not sending the password via E-mail (it will out come naturally if you only store the hash of the users' password...) but instead propose them a secure way to reset/renew it.
I think you should update your question with more code (more finalized and cleaner preferably) and be more precise about your issue. I would not be surprized that a moderator flags your question as too "general" or obscure.
Related
I'm writing a method that make it possible for my Java program to create a database connection that will eventually make me able to access it from other classes/methods.
public class DatabaseConnection
{
private Connection databaseLink;
public Connection getConnection()
{
String url = "jdbc:mysql://localhost/DBname";
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
databaseLink = DriverManager.getConnection(url, "fakeUsr", "fakePsw"); //these are not the real username/password
}
catch (Exception e)
{
e.printStackTrace();
}
return databaseLink;
}
}
I've got a couple of issues:
1)people not using my computer will not be able to get into my server since I wrote "localhost":
String url = "jdbc:mysql://localhost/DBname";
2)I've typed the real username and password instead of "fakeUsr" and "fakePsw".
The thing is: I'm quite sure that the average user of my program should NOT be able to access that information. Is there any other way to permit access to a DB without making username and password readable by virtually anyone getting access to my source code?
For issue n. 1: I tried to type my IP address instead of "localhost" here:
String url = "jdbc:mysql://localhost/DBname"; //changed localhost to my IP address
but then I get "Communications link failure".
For issue n. 2: I have literally no idea how to solve this. I've never coded a program that needs access to a DB so I had to improvise a bit for that.
About Issue #2:
There is no secure way of storing the password inside the code itself. You can of course try to encrypt the password, but then your code has to decrypt it when the connection is established and therefore the encryption key is visible virtually "to all that have access to your source code". With this key, it is possible to get to the real password, just a little bit more complicated.
The only secure way is to have the user enter the login credentials by his own. Either low level (program arguments when starting your application) or by some form of "login dialog", if the application has a GUI.
A third option would be to create a technical user with restricted DB access, depending on the application you are working on. But this usually causes security issues.
You could create your application such that it sends an https request and authenticate itself against a webserver. What you use to authenticate is up to you: Client IP, username, password, client certificates, ...
Once authenticated, your webserver could transfer a one-time username/password that the client uses to login into your database.
The advantage here is that you can still control whether the user gets full or restricted access, or gets no password any more for whatever reason. And there is no security hole in your application.
1) Most Internet providers don’t allow ordinary users to accept incoming socket connections, both for security reasons and because the network traffic can quickly overwhelm consumer grade networks. You will have to either purchase a commercial Internet connection which allows incoming connections, or look for a server you can lease or borrow. I’m afraid I don’t know what options are available.
2) As MrFreeze correctly pointed out, there is no way to safely embed credentials in an application. No matter what you do to obscure your database login credentials, someone can always decompile your program and figure out how you are decrypting those credentials. The only truly safe solution is to tell users you trust what the credentials are, then write your application so the user must enter them.
Side note: Class.forName("com.mysql.cj.jdbc.Driver"); has not been needed for many years. You can remove that line.
I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?
I want to be able to able to get a connection to a remote mysql database from a hava application. That is suppose i have a database server in london with user table, and another database server in paris with a product table and i want to be able from anywhere to get connection to these 2 databases and perform operations on them separately from a java application. My hope is to hide details such as ip address where the servers are located. I just want a kind of handle that abstract the lower level details for each of the servers and using this handle get a connection in a java application. Any help will be highly appreciated
I think that this works for me, if it is what you are searching for:
try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database, username, password);
Statement stm = connection.createStatement();
stm.execute("SOME PIECE of SQL CODE HERE");
} catch (SQLException e) {
}
Talking about address and that kind of stuff, if just you will have acess to the application, there's no problem to have your mysql data in the code. But if you will send this code for another people, you might need to create a client/server based application to avoid losing your credentials.
Is it possible to connect to a MySQL database without specifying the username and password in Java code :
Connection con=DriverManager.getConnection("database url","username","password");
or is there any way to change the username and password using Java?
There is another method of the same name to connect anonymously (without username or password):
Connection con=DriverManager.getConnection("database url");
Source: https://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html
I don't know if you can setup a default user, but you can most certainly set up a user with no password.
As for the second question, assuming your connection has adequet rights in MySQL, you can most certainly set the password on any user. The most basic way to do that is to do:
update user set password=password('new_pass') where user = 'someuser';
Optionally you may want to specify the host field as well in the where clause. This needs to be ran in the msql database.
I am creating an application and I need to connect to a database. The database requires login/password so the application can do operations like select and insert.
In the application I need to connect to the database using login and password, so the application is free to do some tasks on the database. My question is: how do I store and use a password to connect to the database without exposing the password?
I can't simply use a hash or encryption to store the password because the database must recognize the password (I think most or all databases must receive password as plain text).
.
.
Note: The connection is made by the application. No human input to do the connection.
(Edit)More info about the application: it is a web application using servlets/jsp. The database is on the same server of the application. The user for the application is a default user without complete admin powers, but it may insert/delete rows and do most things that involve queries and data modification in tables.
The usual way this is done is to externalize the username/password to a property/config file which is read at runtime (whether or not you use native JDBC/JNDI/CDI/J2EE datasource/etc).
The file is protected via the O/S security by the sysadmins.
The O/S has better tools for protection than app code.
You can use jasypt for the encryption.And store the username and password to datasource.properties file.
public Connection getConnection() throws IOException{
try{
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword("jasypt");
Properties props = new EncryptableProperties(encryptor);
props.load( this.getClass().getResourceAsStream("datasource.properties") );
String driver = props.getProperty("datasource.driver");
String url = props.getProperty("datasource.url");
String userName = props.getProperty("datasource.userName");
String password = props.getProperty("datasource.password");
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
conn.setAutoCommit(false);
return conn;
} catch(ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch(SQLException e) {
e.printStackTrace();
return null;
}
}
You should use a config file for this. use spring with JDBC to make your life easier!
http://www.youtube.com/watch?v=f-k823MZ02Q
Checkout the above awesome tutorial on the Spring framework and using JDBC. Watch all of his JDBC and spring tutorials.
BTW, he covers how to store passwords in config files and wire beans etc.. Hope this helps.
If it's a web app, deploy it on a Java EE app server and connect using a JNDI resource. Only the admin who set up the JNDI data resource needs to know about the credentials needed to connect. Users and developers don't even have to know them; just the JNDI lookup name.
It's not possible to completely eliminate the need for someone besides the database owner to know the username and password, but it is possible to restrict that knowledge to the app server owner.
You are also well advised to create separate credentials just for that application and GRANT it the minimum access and permissions needed to accomplish its tasks. There should be no knowledge of system tables or any other resources outside the province of the application. IF DELETE permission isn't necessary, don't grant it. If access should only be read only, that's what you should GRANT to that credential.