Are there any ready-made solutions for protecting website (or a single page) only with password (i.e. no username field)? I've been searching around but haven't found anything.
The password protection doesn't have to be particularly strong.
I would use md5 to cipher the password, ask for the password with JavaScript, cipher the result and look if the two values are equivalent:
if("<MD5_PASSWORD>" == md5(window.prompt("Password", ""))){
// right
}else{
// wrong
}
the code for a md5-function in JavaScript you can get here.
You can have the password be sent via the url like ?p=password-goes-here at the end of the url.
Than at the webpage do:
if($_GET['p'] != 'mach-password-goes-here'){
die("Wrong password.");
}else{
//the page content goes here
}
for extra security you can hash the password in sha1 and sult
if(sha1($_GET['p'].'sdfjkhdsfiosio213ij2') != 'sha1-with-sult-ass-goes-here'){
die("Wrong password.");
}else{
//the page content goes here
}
Related
im trying to implement function for "user change password".
i want to do:
1.user choose new password.
2.user needs to enter his current password to varificate.
3.if the user currentPassword correct -> change the password.
the problem: i dont know how to get his current password to check if its correct
in my client side i save his hashPassword ("lfds7fdhas784n23489h42")
so i cant do something like:
if state.user.password===currentPassword because i dont have its state password
i need to somhow get his passwsord from the server and check it, or maybe i need to send the
currentPassword to the back end and check it there ,but i dont know how to implement it...
code:
the Form to update password (in shortcut for better understanding):
<TextInput
placeholder"NewPassword"
onChangeText={setNewPass}/>
<TextInput
placeholder"currentPassword"
onChangeText={setCurrentPass}/>
updateUserPssword(state.userId, token, param, value);
the Function for update the password:
const updateUserPssword = dispatch => async (userId, token, newPass, currentPass) => {
try {
const res = await indexApi.put(
`/user/${userId}`,
{
password: newPass,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
}
For summary, the flow of reset password operation is like:
Step 1: User fills in currentPassword, newPassword and confirmedNewPassword in your React App. What you can validate here is only the similatiry of newPassword and confirmNewPassword.
Step 2: When the newPassword and comfirmedNewPassword are similar you send a request to server with data like this : { current: currentPassword, new: newPassword }
Your main concern is how to do that with axios. Below is an example:
axios.post('/reset-password', {
current: currentPassword,
new: newPassword
})
.then(function (response) {
// success case handle here
})
.catch(function (error) {
// error case handle here
});
When your server gets this request, basically, the following steps should be done
Step 1: Use hash function to hash the currentPassword
Step 2: Compare with hashed password of this user in DB
Step 2.1: If the 2 hashed passwords match, hash the newPassword and save the hashed value to DB
Step 2.2: If the 2 hashed passwords do not match, response error to your React App. (something like: passwords do not match)
You should manipulate all your actions on passwords on the server-side. That's the right flow
User types new password (Don't hash)
User types same password for confirmation (you can compare only this on client-side, if fieldA.value == fieldB.value)
User types old password
You send new password and old password as plain, to the server without hash.
Server hashes your old password with the same SALT and compares if generated hash is equal to the hash is stored in the database. That's the KEY MOMENT, you don't need to decode a stored password and compare the plain.
P.S Every time hashing something with the same salt gives you the
same result.
// Pseudo code
decodeHash(passwordInDatabase) == oldPassword // incorrect + impossible
hash(oldPassword) == passwordInDatabase // correct
If it's equal, back-end hash your new password and update in the database.
Return success or error message from back-end.
I'm trying to login user with jaas using Scrypt. I was using sha before and I could just login using:
request.login(username, "password");
and jaas would make the check in the background. But since the method to check if 2 passwords match with scrypt is a check that returns a boolean I had to change the code a bit. I think my code is correct/safe but I prefer being safe than sorry:
// here I get user credential from the db
Usercredential uc = us.getUsercred(username);
boolean matched = false;
if (null != uc) {
// Making the scrypt check to see if password entered by user match db pass matched
matched = SCryptUtil.check(password + uc.getSalt(), uc.getPassword());
}
if (matched) {
// if pass matched I login with the db password value
try {
request.login(username, uc.getPassword());
}...
I'm worried about the fact I'm logging in with the DB value and not the typed value. I make a check to see if they match prior to that though so there should be no problem.
I'm writing an application which needs to have personally identifiable information removed/absent at all times from the database. Given that someone may use their real name in their username, and that an email address may be present in their AspUserIdentity records, I have decided one solution might be to hash these values. In simple terms: when someone logs in with a username, I hash the username they entered and see if that hash exists in the database; if it does, then I log them in. This is easy to do and works just fine by modifying the Login and Register methods in the AccountController. But now I am left with no knowledge of the entered username...
I could just store the username in session, but that seems jankety. What I'd like to do is to update the cookie that gets sent down upon successful login to use the username they entered (and not the hashed value stored in the DB). That way User.Identity.GetUserName() returns the plain text username (and not the hashed username). To the client the process ought to be transparent (and to me as the programmer too).
The question is: how? What's the best place to do this? I'm still relatively green when it comes to the latest ASP.NET Identity stuff. I see in Startup.Auth there's a lot of juicy stuff related to cookies, but I don't see anywhere I can modify the cookie itself upon login and prior to it being sent down.
Is all of this deep within Owin itself?
Thanks in advance,
When user logs in and you compare the hash of username, you can add their real username as a claim to the identity. This is serialised into cookie and available with the user on every request, but not persisted in a DB:
public async Task SignIn(string userName, string password, bool rememberMe)
{
var hashedUsername = getMyHash(username)
var loggedInUser = await userManager.FindAsync(hashedUsername, password);
if (loggedInUser == null)
{
// failed to login
return FailedToLogin(); // whatever you do there
}
// Ok, from now on we have user who provided correct username and password.
// and because correct username/password was given, we reset count for incorrect logins. This is for user lockout
await userManager.ResetAccessFailedCountAsync(loggedInUser.Id);
if (!loggedInUser.EmailConfirmed)
{
return EmailIsNotConfirmed(); // email is not confirmed - display a message
}
if (await userManager.IsLockedOutAsync(loggedInUser.Id))
{
return UserLockedOut(); // user is locked out - display a message
}
var identity = await userManager.CreateIdentityAsync(loggedInUser);
identity.AddClaim(new Claim("OriginalUsername", originalUsername));
var authenticationManager = context.GetOwinContext().Authentication;
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = rememberMe }, identity);
//TODO redirect to a home page
}
Then when you need to display an actual username, not a hash do this:
public static String GetOriginalUsername(this IPrincipal principal)
{
if (principal == null)
{
return String.Empty;
}
var claimsPrincipal = principal as ClaimsPrincipal;
if (claimsPrincipal == null)
{
return String.Empty;
}
var originalUsernameClaim = principal.Claims.SingleOrDefault(c => c.Type == "OriginalUsername");
if (originalUsernameClaim == null)
{
return String.Empty;
}
return originalUsernameClaim.Value;
}
And call this method on User.GetOriginalUsername() in *.cshtml files or in Controllers. Or HttpContext.Current.User.GetOriginalUsername() if you need it somewhere else.
I have a web app being built in express.js with a postgresql db.
I was wondering about how to implement the security, but everyone uses something different ( i guess thats a good thing? ).
Different modules different authentication sequences etc.
What I have at the moment:
1) User form post to for example /login
2) app routes to specific route
3) in route I try the following
var localconstring = "postgres://" + usr + ":" + pass + "#ip:port/db";
var client = new pg.Client(localconstring);
client.on('drain', client.end.bind(client));
client.connect(function (err, client, done) {
The database uses md5 so the pass is already protected by the db.
What should really happen?
Should I salt and hash the username and password and then save the salted/hashed credentials alongside the salt and then use the md5 of the db also?
If so which module?
Should I be logging in like that or try to do a select * from pg_roles/users ??
Thanks a lot!
(regarding the salt and hash if possible some detailed examples as I am pretty knew with authentication security)
Forgot to mention. cookies..
After the authentication I set the following cookies:
res.cookie('user', req.body.lguser.username, { signed: true })
res.cookie('watcher', o, { signed: true })
And look em up afterwards
req.signedCookies.user !== undefined
Is the signed attribute secure?
You should generate a key. This key should be saved on a cookie and on the database. Then when the user makes a petition, you can get the key on the cookie and search the user on the database.
There are libraries that help you on this, take a look at Passportjs:
http://passportjs.org/
First of all md5 is NOT seure anymore, so I would recommend you using 'sha512'.
A snippet would be something like this:
var crypto = require('crypto');
var salt = crypto.pseudoRandomBytes(32);
crypto.pbkdf2(userPassword,salt,1024,32,function(err,finalPassword){
//on the db you save the salt as a field and the SALTEDPASSWORD !!
//in this case the finalPassword
}
So when the user logs-in you get the user from the db by username and do the following:
//after getting the user from DB recalculate the hash
crypto.pbkdf2(passw,user.salt,1024,32,function(err,corrPass){
if(corrPass.toString() == user.password.toString()) // log in the user
//where user.password is the result from the db query
}
And I do recommend using passport like the other dude said, it simplifies all of the cookie stuff.
Hope it helped !
I want to create a change password page for user. I encrypt the password when I save the user in Database (mongodb).
User.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() { return this._password; });
User.method('authenticate', function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
});
User.method('makeSalt', function() {
return Math.round((new Date().valueOf() * Math.random())) + '';
});
User.method('encryptPassword', function(password) {
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
});
I don't know how to decrypt it in order to get the original password back. any help will be appreciated.
The password is hashed, not encrypted, and you can't get the original back -- that's the whole point of hashing, it's a one-way function. You shouldn't ever need to get the original back, as you have no legitimate use for it. To validate a user, you hash the password that they give you in the same way as the stored one, then compare the hashes.
I think the best solution here would be to allow the user to answer some security questions and then be able to reset the password by clicking a link sent to the email in their profile. They might end up setting it to the same password, but that is not your concern. This allows you to not having to worry about unhashing the password.
Of course this is harder if you did not provide for this in the original sign-up form. But if your service isn't actually launched yet, this should be very easy to implement.