What data can I save in my database to verify a user with Google sign in API? - google-signin

I need to store data related to a (Google) user in my database. I tried to store the id_token, but later found out that the part after the '.' changed. What can be used instead, or can I just save the part infront of the "." from the id_token?

Thanks Steven Soneff
Use the 'sub' field of the ID token, it is invariant for the Google user https://developers.google.com/identity/sign-in/android/backend-auth#calling-the-tokeninfo-endpoint
The ID token have three parts; the header, body and signature, divided by a '.' (header.body.signature). Each part is encoded with base64. If you decode the body, you will get a JSON like this:
{
"iss":"https://accounts.google.com",
"at_hash":"xxx",
"aud":"xxx.apps.googleusercontent.com",
"sub":"xxx",
"email_verified":true,
"azp":"xxx.apps.googleusercontent.com",
"email":"xxx#gmail.com",
"iat":xxx,
"exp":xxx
}
...you can safely retrieve and use the user's unique Google ID from the sub claim
So you can save the sub in your database to identify your user

Related

Is base64 a good option for encoding custom Document IDS for Firestore?

I am working on creating some users in my firebase app and I would like to provide custom user ids as they are authenticating with an external service.
For example my user ID generation is consisted by 2 parts like so:
AuthService:AuthServiceUsername
That can look in reality like:
Instragram:dimitrioskanellopoulos
But I dont like to have this string used as a user id so I encode it to base64 like so:
const uid = Buffer.from(`instagram:${serviceUserID}`).toString('base64');
Is there any risk for me doing that ? Is base64 ok to be used also in regards to query params?
Firestore document IDs are quite flexible on what's allowed and not. See https://firebase.google.com/docs/firestore/quotas#limits.
But base64 would actually not be safe, since it contains /, which is disallowed in Firestore document IDs

Parsing a HTTP Basic authentication with an email containing a colon character ( ':' )

I'm using the Authorization header with the Basic type for authentication.
I'm following the HTTP Basic authentication specifications which states that the credentials should follow this form -> userIdentifier:password encoded in base64
We are using an email as the user identifier and according to the email format specification, the colon(':') character is permitted.
The colon(':') is also a valid character in the password.
Knowing this, I'm looking for a creative way to parse the credentials part of the header that uses a colon(':') as the separator between userID and password.
In this case it's simple -> francis#gmail.com:myPassword
This is where it gets complicated -> francis#gmail.com:80:myPasswordWith:Inside
francis#gmail.com:80 is a valid email according to the email format specification even though this is not used very often. So where do I know where to split ?
We have made the decision not to accept an email containing a ':'. But we want to notify the user that his email is not valid, how can we ensure that we are splitting the string at the right place ?
Hope I asked my question in a clear manner, don't hesitate to ask for more details
Thank you
Don’t notify the user that the email is invalid. Split according to the RFC 2617 rules (everything after the first colon is the password), then try to authenticate, fail, and return a generic “authentication failure” message.
A situation where john#example.org:80 has password secret and john#example.org has password 80:secret at the same time, seems unrealistic.
If you require your users to register, you probably do it with some other mechanism (forms?) where you can easily separate the username and tell that it is invalid.

Obfuscating a url

I'm working on an asset management website where in whenever an asset is issued to a user the system would send an email notification with a url in it that would show the user all the assets issued to him. I could have used the query string to pass the user ID but again people could abuse it to view assets issued to other users. My client doesn't wants the user to authenticate themselves when they click on the link. So i need something that would hide the parameters being passed in the query string or at least make them obscure. I've read about url encoding, GUID etc. but i'm not sure what to do. I'm just a beginner. Please pardon my ignorance and point me in the right direction.
Taken what you have said, that you're just a beginner, and assuming that this will be public, you can do the easiest way:
Create a new table in your database and called for example tbl_links, as columns just add 3
user_id (foreigner key to the user table)
guid (primary key, unique)
settings (nvarchar(250)
When you need to send an email, create a new row for the user, for example:
Guid guid = Guid.New();
String settings = "date_from:2012/01/01;date_to:2013/01/01";
And insert it one the database, where the link that you put in the email, should have the guid, for example, http://domain.com/info/?g=....
You could append Json to that settings column and parse it into an object again in the code, ask a new question if you want to take this route.
I personally use a security algorithm to pass only the user_id but you did said you're a beginner, so I only showed you the easy and still valid way.
P.S. for security reasons, you should say in the email that your link is only valid for the next 4 hours or so you can prevent people from generating GUIDs in order to try and get some information.... Simple add a create_date column of type datetime and use that to see if the link already expired or not...
For obscuring URL parameters, you want to use a modified Base64 encoding. Please keep in mind that obscurity is not security, and Base64 encoding something does not in any way make anything secure.
If you're intending to use this for authentication purposes, I think you should reconsider. Look into public key encryption and digital signatures as a starting point.
Trying to secure access to a URL is not the right approach. Give the urls away freely and authenticate your users instead.
I would also highly recommend using SSL for serving up this data.
Security through obscurity fails 100% of the time once the obscurity is not longer obscure.
What you can do is to add some prefix and suffix to the id and the encrypt that string. Something like this:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
string prefix = "lhdsjñsdgñdfj";
string suffix = "dfknsfñn3ih";
var strToEncode = prefix + "|" + id + "|" + suffix;
var encoded = EncodeTo64(str);
var decoded = DecodeFrom64(encoded).Split('|');
if( decoded.length != 3 || decoded[0] != prefix || decoded[2] != suffix )
throw new InvalidArgumentException("id");
var decodedId = decoded[1];

Sending encrypted text in Url

I have a very simple (rather stupid) question, I hope someone can clear my mind on this :)
I want to send an email to my site user once he clicks a button. This email will contain a link with the userID of a user in the link URL (as query param of a link).
Once the user clicks this email link, my server side code will parse and decrypt the userID query string key to get the user ID and perform some action on it.
I cannot use base64 encoding as it can be reversed and 'hackers' can get to know the real userID. I have to encrypt the ID but when I am using AES alogrithms for encryption, the encrypted text is not "understandable" by the browser, ie I cannot pass the encrypted userId text as a part of the URL because it contains un-encoded characters like "/" which the browser cannot by pass. One option I can think of is to base64 encode the encrypted text once I send it across via URL. Then I can bease64 decode and decyrpt it.
Is this approach better than using Uri.EscapeDataString() on the encyrpted text?
You should continue to base64 encode the AES data, as at that point it is likely binary rather than a string that can be escaped. You should also check that you are using url safe base64 encoding.
Use a one-way hash like SHA1 or MD5, and use JavaScript to send the values as encrypted. Then, if a hacker intercepts the request, they would only have the hashes and not the actual values. They could still send the hashes to login, though; one solution is to include a JavaScript parameter (generated via your server-side language) based on IP (but not possible for a hacker to find the formula for), and use it to salt the username and password hashes.
Then on server-side you would do (in PHP, in this case):
$ipHash = sha1("random" . $_SERVER['REMOTE_ADDR'] . "salt_here10381") // place this as a hidden element in the form and use it in the JavaScript to calculate the hash
$userHash = $_POST['userHash'];
$passwordHash = $_POST['passwordHash']
// TODO: Escape $ipHash, $userHash, $passwordHash
$results = mysqli->query("SELECT * FROM `users` WHERE SHA1(CONCAT('" . $ipHash . "', `user`)) ='$userHash' AND SHA1(CONCAT('" . $ipHash . "', `password`)) = " '$passwordHash'");
Then, if a hacker wanted to login with the hash and username they found, they would need the same IP of the user originally logging in whose credentials were intercepted.
Note that this assumes you have passwords stored in your database as plain-text, which you should never do.
For hashing with SHA1, on client-side, take a look at this.
To answer your specific question (I see I got a bit off topic, oops,) it would be acceptable to base64encode the hashes when you send them to the server. If possible, try to send it as POST data and save it in a cookie or session variable.
I think of a simple solution you try to generate a random number(make it as a key) and for the encryption use some simple technique of yourself like XOR 'ing the ASCII value of the characters in the user name with the key that you have generated .so the long random key results in a greater result.
When creating the email you need to encrypt the user ID, then base64 encode it, then URL encode it. Put this as the userID param in the link.
When decrypting the email you do the same in reverse; get the userID param, URL decode it, base64 decode it then decrypt it.
Remember to use a different intitialisation vector every time you encode a user ID. You will need to put the initialisation vector in the emailed link as a URL parameter too in order to decrypt it.

Generation of Email Validation Links

For a Web Application I'd like to generate an email validation link and send it to the user. Like on many public websites, the user should click it to validate his email address. Looks similar to this:
http://www.foo.bar/validation?code=421affe123j4h141k2l3bjkbf43134kjbfkl34bfk3b4fkjb43ffe
Can anybody help me with some hints about the proper generation of those validation tokens? Googling best practices turned out to be more difficult than I though it would be. The links should:
... not require the user to log in first.
... not reveal any login credentials to keep the application secure
... allow me as a developer to efficiently validate the token. I'm pretty sure I need a way to extract the user identifier out of the code to meet this criteria. Don't I?
Furthermore, would you go for a random code, which is saved somewhere, or a generated code which I can recalculate for validation?
Thanks for any replies!
Matthias
P.S. I'm working with ASP.NET 3.5, in case there's an out-of-the-box feature to perform this.
Some suggestions to get you started:
Use GUIDs
Use some sort of salted hash (MD5, SHA1, etc)
Use a random string of characters (the more characters the less likely you'll have collisions)
Store it in a database temporarily, and timestamp it so that it expires after a certain period of time
The simplest way to do it is generate a GUID, store that in the database tying it to their user account and then give them a time-frame within which to click a link with that GUID in.
That validates they are the correct person without making the URL calculable whilst making it resistant to dictionary style attacks.
I construct the hash in a way that can be re-created:
code = MD5( my_hash + user_email + register_timestamp )
Then send a link to http://example.com/validation/?code = 4kj34....
Validation does a lookup like:
SELECT id
FROM users
WHERE
MD5( CONCAT( my_hash, user_email, register_timestamp ) ) = code
AND activated = 0
If you get a single result, update their 'activated' field and sign them in. You can also do some math on their 'register_timestamp' field for a poor man's TTL
I would probably use a Guid. Just create a Guid (by calling Guid.NewGuid()), store it as the validation token for that user, and include it in the validation link.

Resources