Hello everyone at StackOverflow,
I will be asking a question that I'm confused about and searched for hours for, it's to put a 2-Step authentication on a Java program, what I want is that is send a generated code to a login page like the one I created below.
package log;
import javax.swing.JOptionPane;
public class Login {
public static void main(String args[]) {
String username = JOptionPane.showInputDialog("Enter your username");
String password = JOptionPane.showInputDialog("Enter your password");
if (
username != null && password != null &&
(
(username.equals("g17") && password.equals("ire35")) ||
(username.equals("ree") && password.equals("melikejava")) ||
(username.equals("citizenzap") && password.equals("javarules23"))||
(username.equals("devs") && password.equals("password"))
)
)
{
JOptionPane.showMessageDialog(null, "Logged in!" );
} else {
JOptionPane.showMessageDialog(null, "Incorrect username or password! Try again later." );
}
}
}
Everything is fine with the code above, it's just that I want to send a randomly generated code to a phone number, like as I said before a 2-Step verification. Like Google has or Microsoft and etc. For example: You write a phone number, 123-456-7890, then it sends a code to the phone number and it's says something like Your code is 178634 then you write it into the input box, then it checks if it was the code it sent.
If the question I said is not specific enough or something like that please tell me.
Thanks and keep on coding!
-CitizenZap
First, I suggest you put your data in map, combine username, password, phoneNumber into one class, like UserInfo. Because you need to bind phoneNumber to user, or any phoneNumber after login is acceptable.
Then, you replace
{
JOptionPane.showMessageDialog(null, "Logged in!" );
}
with
String newPhoneNumber = null;
{
newPhoneNumber = JOptionPane.showInputDialog("Enter your phone number");
}
You need to check if newPhoneNumber equals with the phoneNumber bind to the user.
// this should be in a while(true) loop
if (newPhoneNumber.equals(phoneNumber)) {
sendSms(phoneNumber);
String code = JOptionPane.showInputDialog("Enter your code");
boolean result = validateAuthorizationCode(code); // here you validate the code
if (result) {
JOptionPane.showMessageDialog(null, "Logged in!" );
} else {
JOptionPane.showMessageDialog(null, "Wrong code!" );
}
} else {
noticeWrongNumber(newPhoneNumber); // tell him the number is wrong, please reinput.
}
Related
so I know that there are many similar questions to mine but i do not really understand what they mean as i am not that great when it comes to coding.
my login screen in the GUI is this:
public void createLoginPanel()
{
loginPanel.setLayout(null);
loginLbl.setLocation(425,50);
loginLbl.setSize(500,50);
loginLbl.setText("Login");
loginPanel.add(loginLbl);
usernameLbl.setLocation(250,300);
usernameLbl.setSize(250,50);
usernameLbl.setText("Username: ");
loginPanel.add(usernameLbl);
usernameTxt.setLocation(350,300);
usernameTxt.setSize(250,50);
usernameTxt.setText("");
usernameTxt.setColumns(10);
loginPanel.add(usernameTxt);
passwordLbl.setLocation(250,400);
passwordLbl.setSize(250,50);
passwordLbl.setText("Password: ");
loginPanel.add(passwordLbl);
passwordTxt.setLocation(350,400);
passwordTxt.setSize(250,50);
passwordTxt.setText("");
passwordTxt.setColumns(10);
loginPanel.add(passwordTxt);
loginBtn.setLocation(675,400);
loginBtn.setSize(100,50);
loginBtn.addActionListener(this);
loginBtn.setText("Login");
loginPanel.add(loginBtn);
gotoWelcomeScreenBtn2.setLocation(100,600);
gotoWelcomeScreenBtn2.setSize(150,50);
gotoWelcomeScreenBtn2.addActionListener(this);
gotoWelcomeScreenBtn2.setText("Home");
loginPanel.add(gotoWelcomeScreenBtn2);
}
the login i currently have is this:
if(e.getSource() == loginBtn)
{
String pass;
String user;
user = usernameTxt.getText();
pass = passwordTxt.getText();
if(user.equals("username") && pass.equals("pass") )
{
JOptionPane.showMessageDialog(null,"Login successful");
allTheGUITabs.setSelectedIndex(7);
}
else
{
JOptionPane.showMessageDialog(null,"Please try again.");
}
System.out.println("Login Button pressed");
}
i want to login using existing info that i have stored in a text file called "employeelist.txt" and i am not sure how to do this.
edit: i have changed the login to user.equals and pass.equals but i am still unsure on how to login with anything other than what i've declared.
edit:
this is the contents of my text file. the second is the username and the third is the password. how will i scan this text file to ensure that the username and password match?
1,MSmith01,Pass123,Mark Smith,12 Yellow Lane,L34GF4,07837463
2,JSmith02,Pass456,Joan Smith,8 Green Road,L394RQ,08765456765
3,PSmith03,Pass678,Paul Smith,9 Orange Street,L435RE,07485747362
4,WSmith04,Pass910,Walter Smith,8 Green Road,L394RQ,08765456765
5,CSmith05,Pass149,Callum Smith,12 Yellow Lane,L34GF4,07485848373
6,MSmith06,Pass213,Mark Smith,32 Red Road,L384GT,07874636472
7,TMath07,Pass141,Terry Matthews,4 Peach Street,L219RB,07564737283
Let’s say you have next strings in your txt file
admin
qwerty12345
Use scanner and pass values for your variables reading them from txt
File employeelist;
Scanner scanner;
String login;
String password;
try
{
employeelist = new File("employeelist.txt"); // changed code
scanner = new Scanner(employeelist); //changed code
while(scanner.hasNextLine())
{
login = scanner.nextLine();
password = scanner.nextLine();
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
}
Then use it in your if statement.
if(user.equals(login) && pass.equals(password)
{
// your code here
}
I'm learning Java in school right now and I've tried to make a little login/signup form. So everyone who wants to play my small game has to signup/login first to get their stats loaded. I've seen some basic login forms when I searched some solutions on google, but always with lines like this:
if ( username_tf.getText() == "admin" && password_tf.getText() == "123" ) { ...
But I want people to be able to make their own username & password. That's what I was trying to do:
int i;
String username[] = new String[500];
String password[] = new String[500];
// REGISTER BUTTON - no if else yet, just the basics I need to test login button
public void jButton2_ActionPerformed(ActionEvent evt) {
username[i] = jTextField1.getText();
password[i] = jPasswordField1.getText();
i++;
} // end of jButton2_ActionPerformed
// LOGIN BUTTON
public void jButton1_ActionPerformed(ActionEvent evt) {
for ( int j = 0; j < i; j++ ) {
username[j] = jTextField1.getText(); // same error without this line
password[j] = jPasswordField1.getText(); // "
if ( username[j].equals(username[i]) && password[j].equals(password[i]) ) {
JOptionPane.showMessageDialog(this, username[j] + ", welcome back.", "Successfully logged in.", JOptionPane.INFORMATION_MESSAGE);
} else {
if ( !username[j].equals(username[i]) ) {
JOptionPane.showMessageDialog(this, "Wrong username.", "Error.", JOptionPane.ERROR_MESSAGE);
} else if ( !password[j].equals(password[i]) ) {
JOptionPane.showMessageDialog(this, "Wrong password.", "Error.", JOptionPane.ERROR_MESSAGE);
} else if ( !username[j].equals(username[i]) && !password[j].equals(password[i]) ) {
JOptionPane.showMessageDialog(this, "Wrong username & password.", "Mega Error.", JOptionPane.ERROR_MESSAGE);
}
} // end of if-else
} // end of for
} // end of jButton1_ActionPerformed
I've tried the same code with == operators, but I'm still getting the same error. ^^
I'm getting the Username is wrong option pane always, can somebody help me there? :)
Would appreciate any kind of help and therefore I'm new to Java I'd also appreciate if you could explain why you're using it when you use some difficult code. :D
Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.
Hello i am a new java student i have been working on a library system containing ( users - library workers and books ) so i am trying to create a log in form i already have an array list but i did a file stream ( to clarify i let the new user to register and his/her information will be saved to the file like this ID Name Password Age ) so i have tried to do something as this method in the library users class
private Scanner x;
private String user_name , password ;
public void openfile(){
try {x= new Scanner (new File ("E:\\javaapplication1
\\test\\professors.txt"));
}
catch(Exception e){
System.out.println("couldn't find file");
}
}
public void checklog ( String username , String password ){
String a , b ,c ,d ;
while(x.hasNext()){
a = x.next();
b = x.next();
c = x.next();
d = x.next();
if ( b == username ||c == password ){
System.out.println("Loggin successful ");
}
else
System.out.println("Loggin failed wrong id or password ");
break;
and then call it like this in the main with the full code
System.out.println ("Enter your name ");
check_name = reader.next();
System.out.println ("Enter your password ");
check_password =reader.next();
lib_us professor ;
professor = new lib_us();
professor.openfile();
professor.checklog(check_name, check_password);
i get all passwords wrong i save them like 4 id name password and age that's why i created a b c and d ...
i am still new in this kind of log in forms so please specify me a solution and if you need the whole code please ask for it :)
So in your checkLog() method you have the statement if(b == username || c == password) should be if(b.equals(username) && c.equals(password)) OR if(b.equalsIgnoreCase(username) && c.equalsIgnoreCase(password)) for case sensitive or not (use the equals() method for case sensitivity or the equalsIgnoreCase() method for non case sensitivity).
Understand why that is? Because in your original statement you are saying only one of them has to be true in order for it to be a successful login. With the revised one both of them must be true. Also you should not use the operator == to compare two strings to see if they are the same string. That will only compare their addresses.
EDIT:
If your file is kind of like what is shown below:
12 Name Pass 12
13 Namez Passz 13
14 Namezz Passzz 14
Try this code to read it in and compare:
private Scanner x;
private String user_name, password;
public void openFile()
{
try
{
x = new Scanner(new File("FILE PATH"));
}
catch(Exception e)
{System.out.println("Couldn't find file"); System.exit(0);}
}
public boolean checklog(String username, String password)
{
String temp;
String[] info;
while(x.hasNext())
{
temp = x.nextLine();
info = temp.split(" ");
//info[0] = id, info[1] = username, info[2] = password, info[3] = age;
//Right here that means the username and password is correct
if(info[1].equals(username) && info[2].equals(password))
{
System.out.println("Login Successful");
return true;
}
}
System.out.println("Login failed wrong id or password");
return false;
}
I have a login frame, That has two different login mode, "User" and "Admin".
My problem is in admin mode (when select admin from jcombobox),
When i select admin, my first textfield should fill with "Administration" automatically and did, And in my jpasswordfiled, It should search it's password number from text file (that is 2).
But, Not accept in admin mode:
public class LoginFrame extends javax.swing.JFrame implements ActionListener {
private String username;
private char[] Password;
...
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
username = String.valueOf(jTextField1.getText());
Password = jPasswordField1.getPassword();
if (jComboBox1.getSelectedIndex() == 2) {
if (adminCanGoNext2()) {
goAdminMainPage(); // Execute work
} else {
ErrorMessageLabel.setText("Did Not Match");
}
}
} catch (Exception e) {
ErrorMessageLabel.setText("Enter Correct Input");
}
public boolean adminCanGoNext2() throws IOException {
FileReader fr = new FileReader("LoginInformation.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while( (line = br.readLine())!= null ){
if(line.startsWith("Admin")){
char[] charedPass=line.toCharArray(); // char password that read from file
System.out.println("readed password is: "+ charedPass.toString());
if(Arrays.equals(charedPass, Password)){
return true;
}
}
}
return false;
}
public void goAdminMainPage() {
System.out.println("Go ");
}
...
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jComboBox1) {
if (jComboBox1.getSelectedIndex() == 2) {
jTextField1.setText("Administration");
}
}
}
}
Login Information.txt file:
Admin 2
271 tes tt Male 2013/05/30
458 tttt uuuu Female 2013/05/30
Now, When i select admin mode, my jtextfield1 text is "Administration" perfectly,
But when i try number "2" for passwordfield, and clicked to login button, make no change!
You are comparing a String with a character array (and they are always found non-equal obviously).
You have to convert the password read from the file into a character array using toCharArray() and then compare the resulting array with the character array returned by JPasswordFields gePassword() method. For easy comparing of arrays you can use the utility methods of java.util.Arrays.
See, also, this short demo.
EDIT:
Please note, that storing passwords in String variables is not advisable due to security concerns. (Of course storing passwords in files in clear-text is probably an even greater security risk.)
The "How to Use Password Fields" section of the Java Tutorials might be a good source of info and directions to get you started.