I use Hibernate annotation to encrypt password
#ColumnTransformer(write = "crypt(?, gen_salt(...))")
private String password;
But after updating the entity I see in logs that password re-generated.
password=crypt('$2a$...
How to prevent this field from another encryption while saving the object?
Two possible solutions here, my guess is you should go for the second:
Either you need the clear password for some reason, and then you should use a "decrypt" statement on table read, see example 73 in section 2.3.19.
Or you only need to check if the user has sent the right password, and should use a hash function and not encryption. See the difference between hash and encryption, and when to use each.
Use that configuration
#Column(name = "password", nullable = false, updatable = false)
Related
Say, I want to save/create new item to the DynamoDb table,
if and only if there is not any existent item already that that would contain the referenceId equal to the same value I set.
In my case I want to create a item with withReferenceId=123 if there is not any other withReferenceId=123 in the table.
the referenceId is not primary key! (I don not want it to be it)
So the code:
val withReferenceIdValue = "123";
val saveExpression = new DynamoDBSaveExpression();
final Map<String, ExpectedAttributeValue> expectedNoReferenceIdFound = new HashMap();
expectedNoReferenceIdFound.put(
"referenceId",
new ExpectedAttributeValue(new AttributeValue().withS(withReferenceIdValue)).withComparisonOperator(ComparisonOperator.NE)
);
saveExpression.setExpected(expectedNoReferenceIdFound);
newItemRecord.setReferenceId(withReferenceId);
this.mapper.save(newItemRecord, saveExpression); // do not fail..
That seems does not work.
I the table has the referenceId=123 already the save() does not fail.
I expected this.mapper.save to fail with exception.
Q: How to make it fail on condition?
I also checked this one where they suggest to add auxiliary table (transaction-state table)..because seems the saveExpression works only for primary/partition key... if so:
not sure why there that limitation. in any case if it is primary key
one can not create duplicated item with the same primary key.. why
creating conditions on first place. 3rd table is too much.. why there
is not just NE to whatever field I want to use. I may create an index
for this filed. not being limited to use only primary key.. that what
I mean
UPDATE:
My table mapping code:
#Data // I use [lombok][2] and it does generate getters and setters.
#DynamoDBTable(tableName = "MyTable")
public class MyTable {
#DynamoDBHashKey(attributeName = "myTableID")
#DynamoDBAutoGeneratedKey
private String myTableID;
#DynamoDBAttribute(attributeName = "referenceId")
private String referenceId;
#DynamoDBAttribute(attributeName = "startTime")
private String startTime;
#DynamoDBAttribute(attributeName = "endTime")
private String endTime;
...
}
Correct me if I'm wrong, but from the:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/dynamodb-dg.pdf
Conditional Writes By default, the DynamoDB write operations (PutItem,
UpdateItem, DeleteItem) are unconditional: each of these operations
will overwrite an existing item that has the specified primary key
the primary key - that makes me thing that the conditional write works ONLY with primary keys
--
Also there is attempt use the transactional way r/w from the db. There is a library. That event has not maven repo: https://github.com/awslabs/dynamodb-transactions
As an alternative seems is the way to use 3rd transaction table with the primary keys that are responsible to tell you whether you are ok to read or write to the table. (ugly) as we replied here: DynamoDBMapper save item only if unique
Another alternative, I guess (by design): it is to design your tables in a way so you use the primary key as your business-key, so you can use it for the conditional writes.
--
Another option: use Aurora :)
--
Another options (investigating): https://aws.amazon.com/blogs/database/building-distributed-locks-with-the-dynamodb-lock-client/ - this I do not like either. because potentially it would create timeouts for others who would want to create new items in this table.
--
Another option: Live with this let duplication happens for the item-creation (not including the primary key). And take care of it as a part of "garbage collection". Depends on the scenario.
I have been looking all over the place with no luck to what I am trying to do.
I am looking to hash and salt my user passwords and store them into the DB. The issue is, how do I store them?
I have looked at this http://shiro.apache.org/realm.html#Realm-authentication which I have found similar answers, but it doesn't make sense.
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
...
//We'll use a Random Number Generator to generate salts. This
//is much more secure than using a username as a salt or not
//having a salt at all. Shiro makes this easy.
//
//Note that a normal app would reference an attribute rather
//than create a new RNG every time:
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
Object salt = rng.nextBytes();
//Now hash the plain-text password with the random salt and multiple
//iterations and then Base64-encode the value (requires less space than Hex):
String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, 1024).toBase64();
User user = new User(username, hashedPasswordBase64);
//save the salt with the new account. The HashedCredentialsMatcher
//will need it later when handling login attempts:
user.setPasswordSalt(salt);
userDAO.create(user);
User nor "UserDAO" exists currently from what I'm seeing, and all of these examples seem to use older Shiro examples.
When I look at the "PasswordService" javadoc I read
Account Creation or Password Reset
Whenever you create a new user account or reset that account's password,
we must translate the end-user submitted raw/plaintext password value to a
string format that is much safer to store. You do that by calling the
encryptPassword(Object) method to create the safer value. For example:
String submittedPlaintextPassword = ...
String encryptedValue = passwordService.encryptPassword(submittedPlaintextPassword);
...
userAccount.setPassword(encryptedValue);
userAccount.save(); //create or update to your data store
Be sure to save this encrypted password in your data store
and never the original/raw submitted password.
but what is "userAccount?"
A lot of times the documentation is very vague.
However I did notice there is a "SubjectDAO" Class, but no UserDAO class...
So yeah I'm confused on what to do next, so if anyone could help me I would appreciate it greatly!
Thanks a lot!
Seems like the Documentation is refering User and UserDAO as your own User Model Entity (Table) and User Data Access Layer Entity (Class to Save, Update, Delete and Retrieve). These necessarily not required to be a part of Apache Shiro (Reason some Data Access Layer may be in RDBMS, Some in In-memory dbs, some could even be in properties file, why not?)
You must implement User and UserDAO to save to your own persistence store.
UserAccount also is the Model object you use when you want to register user accounts. Like the Gmail signup.
You must know that Apache Shiro is just a layer for Security (Authentication, Authorization, etc). Persistence must be implemented by you.
Strongly advice you to check out Spring Data JPA and Spring Security.
When you are hashing the password :
DefaultPasswordService passwordService = new DefaultPasswordService();
String encytptedPwd= passwordService.encryptPassword("your password");
Above api will generate password including salt.
Update this password using JDBC native api...
When you are implementing the JDBCRealm
PasswordMatcher credentialsMatcher = new PasswordMatcher();
this.setCredentialsMatcher(credentialsMatcher);
above will set the credential matcher and use SimpleAuthenticationInfo to validate your login.
The PasswordMatcher can be configured to use an ini file too.
I have the following definition:
#Column(name = "password", length = 80)
byte[] password;
When I use EclipseLink to create the tables (mysql) I get a table with a longblob. A tinyblob would suffice.
How do I have to specify the length?
I know that I could add a columnDefinition but I'd like to keep it database/sql agnostic.
If you want specific type for blob column, columnDefinition should be used. Problem with length is that it is only for strings. This is also told in API.
I have a GAE project written in Java and I have some thoughts about the HRD and a problem that I'm not sure how to solve.
Basically I have users in my system. A user consists of a userid, a username, an email and a password. Each time I create a new user, I want to check that there isn't already a user with the same userid (should never happen), username or email.
The userid is the key, so I think that doing a get with this will be consistent. However, when I do a query (and use a filter) to find possible users with the same username or email, I can't be sure that the results are consistent. So if someone has created a user with the same username or email a couple of seconds ago, I might not find it with my query. I understand that ancestors are used to work around this problem, but what if I don't have an ancestor to use for the query? The user does not have a parent.
I'd be happy to hear your thoughts on this, and what is considered to be best practice in situations like these. I'm using Objectify for GAE if that changes anything.
I wouldn't recommend using email or any other natural key for your User entity. Users change their email addresses and you don't want to end up rewriting all the foreign key references in your database whenever someone changes their email.
Here's a short blurb on how I solve this issue:
https://groups.google.com/d/msg/google-appengine/NdUAY0crVjg/3fJX3Gn3cOYJ
Create a separate EmailLookup entity whose #Id is the normalized form of an email address (I just lowercase everything - technically incorrect but saves a lot of pain when users accidentally capitalize Joe#example.com). My EmailLookup looks like this:
#Entity(name="Email")
public class EmailLookup {
/** Use this method to normalize email addresses for lookup */
public static String normalize(String email) {
return email.toLowerCase();
}
#Id String email;
#Index long personId;
public EmailLookup(String email, long personId) {
this.email = normalize(email);
this.personId = personId;
}
}
There is also a (not-normalized) email field in my User entity, which I use when sending outbound emails (preserve case just in case it matters for someone). When someone creates an account with a particular email, I load/create the EmailLookup and the User entities by key in a XG transaction. This guarantees that any individual email address will be unique.
The same strategy applies for any other kind of unique value; facebook id, username, etc.
A way around the HRD's eventual consistency, is to use get instead of query. To be able to do this is you need to generate natural IDs, e.g. generate IDs that consists of data you receive in request: email and username.
Since get in HRD has strong consistency, you will be able to reliably check if user already exists.
For example a readable natural ID would be:
String naturalUserId = userEmail + "-" + userName;
Note: in practice emails are unique. So this is a good natural ID on it's own. No need to add a made-up username to it.
You may also enable cross-group transactions (see https://developers.google.com/appengine/docs/java/datastore/overview#Cross_Group_Transactions) and then in one transaction look for the user and create a new one, if that helps.
Recommend avoiding an indexed field and query unless you have other uses for it. Here is what I have done before (Python) using key_name (since entity ids need to be ints). Easy to use either the key_name or id for other entities that need to link to user:
username = self.request.get('username')
usernameLower = username.lower()
rec = user.get_by_key_name(usernameLower)
if rec is None:
U = user(
key_name = usernameLower,
username = username,
etc...)
U.put()
else:
self.response.out.write(yourMessageHere)
I created table in google Big table datastore ,In that the i set primary key using
#annotations as follows
#Id
#Column(name = "groupname")
private String groupname;
#Basic
private String groupdesc;
I worked corretly,but it override the previous record,how to solve this
for eg
if i entered
groupname=group1
groupdesc=groupdesc
than it accept
after that i enter same groupname it override previous record
for eg
groupname=group1
groupdesc=groups
this record override previous one.
This is simply how the App Engine datastore works: It does not distinguish between insertions and updates. If you're not confident they keys you're generating yourself are unique, you either need to use auto generated keys, or check for existence before inserting a record.