I have an api which needs authorization for access. But I want to pass the authorization in code itself so that I do not need to enter the user id and password each time I use.
String[] apiList = { "https://example.com" };
String user, pass;
System.out.print("Enter your username:");
user = input.nextLine();
System.out.print("Enter your Password:");
pass = input.nextLine();
if (user.equals("user") && (pass.equals("password"))) {
System.out.println("welcome");
} else {
System.out.println("please try again!");
}
String user = "myusername";
String pass = "mypassword";
And remove the code which asks for user input, this way you don't have to enter it every time.
I'd only do this if it were a personal project without source control, you don't want to commit usernames and passwords to repositories especially not public repositories.
An alternative would be to store this data in a text file somewhere and load it into those variables, this text file can be outside the repository folder or you can gitignore this file.
Another way would be to use args inside the main method eg:
public static void main(String[] args) {
String user = args[0];
String pass = args[1];
}
Then you can configure them as commandline arguments in your IDE or pass them on the terminal when running your program.
Related
In my program I have a .txt file that has some config values in it.
I have my config.txt laid out like this:
Users:
Jeff: 14
Jimmy: 23
Jack: 532
I have code that consists of a scanner, a few variables, and a few printline commands.
I want the user of the program to enter a name, and if the name they enter exists in the config, to return the value, and if the name doesn't exist, add the name to a list and assign it a value.
I know how to create and read and write to files, but how do I write and read under the "Users:" key?
I've done a good bit of research but I haven't been able to figure it out.
EDIT:
I've been messing with some code, and I got this.
//Code used to get the username to read.
Scanner sc = new Scanner(System.in);
String user = new String();
String pass = new String();
//Username Detection
System.out.println("Please enter your username.");
user = sc.nextLine();
System.out.println("User name is: "+user);
try {
readSSDB(user);
} catch (FileNotFoundException e) {
// Do something with `e`
}
//Code used to check the file.
public static void readSSDB(String user) throws FileNotFoundException{
File SSDB = new File("SSDB.txt");
System.out.println("File Reader Loaded Successfully.");
Scanner read = new Scanner(SSDB);
String userRead = read.nextLine();
boolean userFound = false;
while(userFound == false){
if(read.nextLine().contains(user)){
System.out.println("Found user: "+userFound);
}else{
System.out.println("No user '"+user+"' found!");
read.nextLine();
}
}
}
EDIT 2: Realized I said while(userFound = false) instead of while(userFound == false).
Output I get is: "No user 'Jimmy' found! Found instead: 'Jimmy: 23'"
Shouldn't if(read.nextLine().contains(user)){ return true because read.nextLine() is "Jimmy: 23" and user is "Jimmy" so logically speaking "Jimmy: 23" does contain "Jimmy"?
You can read file using nextLine() and
if(scannedLine.contains(name)) {
//return data to the user
} else {
//add user to he config file
}
Have you tried something like this?
Question:
create a class named Account that contains the string fields name, email and
password.
Develop a program called LoginSim that simulates a login procedure.
The program reads a list of names, email addresses and passwords from a file pw.txt.
Store the information in an ArrayList of Account objects.
*Note: for Netbeans users the file must be placed in a test folder and accessed with new File("test/pw.txt");
Your program will prompt the user for their email address.
If the email is not in the system, prompt the user to try again. Give them an option to quit.
If the email is found in the system, prompt the user to enter their password.
After 3
unsuccessful tries, inform the user that they are locked out and end the program.
If the password matches, welcome the user by name and ask if they would like to change their
password.
If so, prompt for the new password and change it accordingly. If not, end the
program by confirming that they have signed out.
When the program ends, display the list of accounts.
Sample output:
Enter your email address (q to quit):
draco#hogwarts.com
Email not found, please try again (q to quit):
dmalfoy#hogwarts.com
Email not found, please try again (q to quit):
q
Goodbye!
pw.txt
Hagrid hagrid#hogwarts.com 111
Harry harry#hogwarts.com killvoldy777
Ron ron#hogwarts.com mypassword123
Hermione hermione#hogwarts.com 98fJG83h*4iwrej!
What should I do next, exception at line 16
import java.util.*;
import java.io.*;
public class LoginSim {
private static int index;
public static void main(String args[]) throws
FileNotFoundException, ArrayIndexOutOfBoundsException {
String em;
String pw;
Scanner f = new Scanner(new File("src/pw.txt"));
Scanner kb = new Scanner(System.in);
String[] email = new String[3];
String[] password = new String[3];
int i = 0;
while (f.hasNext()) {
email[i] = String.valueOf(f.hasNext());
password[i] = String.valueOf(f.hasNext());
i++;
}
System.out.println("Enter Email:");
em = kb.next();
System.out.println("Enter Password:");
pw = kb.next();
if (index != -1) {
System.out.println("Enter pw:");
pw = kb.next();
int tries = 0;
while (!pw.equals(tries < 2) &&
!pw.equals(password[index])) {
System.out.println("Incorrect Password, Try Again");
tries++;
pw = kb.next();
}
if (pw.equals(password[index])) {
System.out.println("Successful Login");
}else {
System.out.println("3 Strikes, Locked out");
}
System.out.println("Email not found");
}
}
}
Ok, you are getting java.lang.ArrayIndexOutOfBoundsException: 3 in this line email[i] = String.valueOf(f.hasNext()); because the size of your array is 3 (String[] email = new String[3];), but you are trying to add more then 3 entries to it, at least 4 based on your sample "pw.txt".
Also, you have the same issue with your password array.
I built a simple java app. However, I can't understand how could I secure this app to avoid hard-coded passwords that a decompiler won't be able to reveal.
LoginMain
import java.util.Scanner;
public class LoginMain {
public static void main(String[] args) {
String Username;
String Password;
Password = "admin";
Username = "admin";
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
} else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
LoginNew.java
import java.util.Scanner;
public class LoginNew {
public static void main(String[] args) {
String Username;
String Password;
Scanner scan = new Scanner (new File("1.txt"));
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
} else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
However, the system presents me :
loginNew.java:9: error: cannot find symbol
Scanner scan = new Scanner (new File("1.txt"));
^
symbol: class File
location: class loginNew
1 error
Error: Could not find or load main class loginNew
I created the file 1.txt with my credentials: Password = "admin";
Username = "admin"; Simple stuff but Im lost. sorry..
Normally, passwords wouldn't even be stored in the application code - they'd be validated against a database or some other data source. But throwing those concerns aside for a moment...
The answer to your question is to use a one-way hash. That is, encrypt the password with a hash function that can't be reversed. When the user types in a password, hash it and compare it to the hash that's stored in your application code. (Replace the password variable with a passwordHash variable.) Because the hash can't be (easily) decrypted, it's more secure than storing the plain-text password in your application source (or database, or wherever else you may be storing hashed passwords).
As others have alluded to, cryptographic hashing (and application security) can get complex very quickly, and isn't particularly friendly for beginners to work with. So this answer might help you understand some concepts, but you might need a bit more to secure a production-quality application.
This method is part of a bigger program which asks for specific user input and i need this method to prompt the user for input until its correct. here is what i have
public static String validName(Scanner input, Scanner histogram) {
String user = "";
String name = input.next();
boolean test = false;
while (histogram.hasNext()) {
user = histogram.next();
if (name.equalsIgnoreCase(user)) {
test = true;
break;
}
else {
test = false;
}
}
if (!test) {
System.out.println("Name not found");
}
return user;
}
Scanner histogram is reading a txt file. So far it works fine, but as it is it only goes through once.
What can i change or add to make it work properly?
Here is a quick fix. Create a temporary Scanner and set it equal to histogram before you run through histogram. If the user is found then validName() will return that user, if not then repeat this function by passing in input and the copy of histogram tmp. This will get the job done but is not the right way to go about this task.
Updated
Create a temporary string and add each user to the string followed by a space. If the check fails then recall the function with an anonymous Scanner constructed with the string of users.
public static String validName(Scanner input, Scanner histogram) {
String user = "";
String name = input.next();
String tmp = "";
boolean test = false;
while (histogram.hasNext()) {
user = histogram.next();
tmp += user + " ";
if (name.equalsIgnoreCase(user)) {
test = true;
break;
}
else {
test = false;
}
}
if (!test) {
System.out.println("Name not found");
user = validName(input, new Scanner(tmp));
}
return user;
}
It may not be a perfect solution, but here's how i would do it: first read the complete histogramm into a hash Table. This allows for very efficient input validation later on:
public static String validName(Scanner input, Scanner histogram) {
HashSet<String> validInputs = new HashSet<>();
// read in histogram
while (histogram.hasNext())
validInputs.add(histogram.next());
// ask for input and repeat if necessary
while (true) {
String userInput = input.next();
if (validInputs.contains(userInput))
return userInput;
System.out.println("invalid input");
}
}
i've not tested this solution but it should work.
Also the histogram is only ever read once. After that only the hash values of the different Strings are compared. Since 2 Strings with the same content should always have the same hash value this should work.
Also this solution does not require any recursion.
You can use the Scanner's findInLine(String pattern) method, try the following:
public static String validName(Scanner input, Scanner histogram) {
String user = "";
String name = input.next();
if(histogram.findInLine(name) != null){
System.out.println("This name exist");//Do what you have to do here
}
else{
System.out.println("Name not found");
user = validName(input, histogram);
}
return user;
}
Take a look at the Scanner Class methods for more information.
I am trying to write the information into a textfile after the user has input all their fields.
My text file have a already some information in it.
Anthony Ducan;anthony;a123;55 Peter Street;3321444;VISA;3213504011223
Barry Blake;barry;a999;456 George Street;23239876;VISA;435677779876
Claire Rerg;clare;c678;925 Edward
Lane;67893344;MASTERCARD;223344556677
I want to enter them into as a string into my textfile, and each line has multiple items seprated by ;.
Do I need to open my file , read what it contains before adding new information , or I can just simply add into it?
I have set up a constructor for inputting values, but how do I use it? Do i need to make a new method for my main to call it?
import java.io.*;
import java.util.*;
public class newCust{
String name,username,password,address,contact,creditType,creditNum;
Scanner input = new Scanner(System.in);
public newCust(String name , String username, String password, String address, String contact, String creditType, String creditNum){
this.name= name;
this.username= username;
this.password = password;
this.address = address;
this.contact = contact;
this.creditType = creditType;
this.creditNum = creditNum;
System.out.println("Welcome to Kreg Hotel Booking System");
System.out.println("==============================================");
System.out.println("Please enter your name: ");
name = input.nextLine();
System.out.println("Please enter your login username: ");
username = input.nextLine();
System.out.println("Please enter your login password: ");
password = input.nextLine();
System.out.println("Please enter your address: ");
address = input.nextLine();
System.out.println("Please enter your contact: ");
contact = input.nextLine();
System.out.println("Please enter your credit card type: ");
creditType = input.nextLine();
System.out.println("Please enter your credit card number: ");
creditNum = input.nextLine();
try{
PrintWriter fileout = new PrintWriter("customerinfo");
newCust info = new newCust(name,username,password,address,contact,creditType,creditNum);
fileout.print(info);
}
catch(IOException ex){
}
}
public static void main(String[] args){
}
}
Do i need to open my file , read what it contains before adding new information , or i can just simply add into it?
You can append to a file, but you can't insert characters or lines in the middle of it.
You can append to it by using for instance new FileWriter(file, true).
If this is production code and not simply an exercise for you, I recommend you to look into OpenCSV.
To write to a file, you use FileOutputStream.
Check if there is any constructor or methods that allows you to open the file appending to it instead of overwritting