How can I use Google's OpenID and/or OAuth services to login and allow access to APIs with only ever one prompt to the user? - authentication

I am attempting to create a login system for my website that permits both authentication via Google's API and access to any of the OAuth-supported Google Data APIs while ideally only showing the user one prompt ever, no matter if he's creating an account or logging into his existing one. I want to minimize the number of times he's asked for approval.
I am aware that Google provides Hybrid OpenID/OAuth for this purpose, but the issue is that every time I add OAuth extensions to my OpenID request, it never remembers the user's approval for that request. Is there any way for the approval to be remembered when I am doing Hybrid OpenID/OAuth? If I just do OpenID without OAuth extensions, everything is remembered just fine and it doesn't keep bugging the user with the prompt.
Here are the pertinent extensions I'm sending in addition to my OpenID request, which result in me getting an OAuth request token (good) but cause the approval to never get remembered (bad).
PHP syntax:
$args["openid.ns.ext2"] = 'http://specs.openid.net/extensions/oauth/1.0';
$args["openid.ext2.consumer"] = 'www.MYSITE.com';
$args["openid.ext2.scope"] = 'http://www-opensocial.googleusercontent.com/api/people/';
$args["openid.mode"] = 'checkid_setup';
$args["openid.realm"] = 'http://www.MYSITE.com/';
Is it normal for Hybrid OpenID/OAuth to act this way (not remembering the last OAuth authorization)? What is the best way to get around this? I have thought of storing cookies on the user's computer to link to somewhere in my database so I could use the last access token again, etc... (the issue here being I don't know whose token to look up unless I know who the user is...a circular problem). And doing an OpenID-only request to get his user ID to see if he has an account in order to look up his access token, followed by an OpenID+OAuth request (if an access token for him isn't stored) would result in two prompts, which really wouldn't help.
It also seems like Hybrid only supports OAuth 1.0, which I think is fine until 2015, so it's not an issue right now for me. I am assuming they will support OAuth 2.0 in the future.
Is checkid_immediate relevant to this in any way? I'm just not sure how to use this to accomplish what I want.

I would suggest using OAuth 2.0. This supports getting both identity and access to APIs -- so accomplishes the same end goal, but is much easier than OAuth 1 Hybrid.
Take a look here:
https://developers.google.com/accounts/docs/OAuth2Login
The scopes you're trying to access are included in the URL (see "Forming the URL"). The referenced doc lists the scopes required for getting identity/profile information. You can simply add additional scopes to the string, comma-delimited in order to request access to other APIs. The resulting access token will access both the APIs and identity information (via the UserInfo API endpoint mentioned).
That said, what you're trying to do with OpenID 2.0/OAuth 1 hybrid should work-- and the user should see a checkbox for "remembering" the authorization. If you really want to debug this further, it'd be helpful to have a webpage you can point to which kicks off this authentication+authorization flow so we can see what's happening.

I figured out that checkid_immediate (and x-has-session, not sure if that's needed or even working) is allowing me to determine whether or not a user is logged in without prompting him, and if he is, it is giving me a claimed_id by which I can identify the user. That's exactly what I needed. The original question is solved, but I do want to figure out how to use identify with OAuth 2.0 because I have already implemented that.
Furthermore, I've noticed that when using OpenID/OAuth that the user still gets asked to authorize OAuth even after he's authorized OpenID. I can't see the advantage to the hybrid approach from the user's perspective.
If the user is logged out of Google, that's a total of three prompts just to sign up for my website and grab his name and profile image.

If anyone wondered, here are the steps necessary to get Hybrid OpenID/OAuth completely working (an overview). I was confused thoroughly throughout this process, so I hope this helps someone.
Do normal OpenID handshake and add on AX extensions for OAuth 1.0.
Use 'checkid_immediate' to permit probing for an active Google session without prompting the user. Use *claimed_id* as a unique identifier to link the user to your database.
If 'setup_needed' is returned, use 'checkid_setup' so the user is prompted and verified before continuing.
This leaves you with two possibilities. *checkid_immediate* returning immediately giving you a claimed_id, or a claimed_id coming through after *checkid_setup* (basically sign-up) succeeds.
Hybrid OpenID/OAuth 1.0 will give you an authorized request token.
Use the authorized request token to get an access token (you only need to call OAuthGetAccessToken)
Use that OAuth 1.0 access token to do whatever you want.
I was successful in using OAuthGetAccessToken to get an access token from the authorized request token my Hybrid OAuth dance, omitting the 'oauth_verifier' parameter (irrelevant to Hybrid).
I was successful in using OAuthGetAccessToken to get an access token after my Hybrid OAuth dance, omitting the 'oauth_verifier' parameter (irrelevant to Hybrid).
In a PHP/Zend environment:
$config = array(
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken',
'consumerKey' => $consumer_key,
'consumerSecret' => $consumer_secret
);
$consumer = new Zend_Oauth_Consumer($config);
$zendRToken = new Zend_Oauth_Token_Request(); // create class from request token we already have
$zendRToken->setToken($requestToken);
try{
$accessToken = $consumer->getAccessToken(array(
'oauth_token' => $requestToken,
// 'oauth_verifier' => '', // unneeded for Hybrid
'oauth_timestamp' => time(),
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_version' => '1.0'
), $zendRToken);
} catch (Zend_Oauth_Exception $e){
echo $e->getMessage() . PHP_EOL;
exit;
}
echo "OAuth Token: {$accessToken->getToken()}" . PHP_EOL;
echo "OAuth Secret: {$accessToken->getTokenSecret()}" . PHP_EOL;

Related

Amplify federated saml sign in not authenticated

So I'm not quite understanding why this isn't working. Some background; We have a SAML identity provider in our user pool, its a registered identity in our identity pool as well which i see when i go to dashboard. I am pretty frustrated form the lack of central documentation for Amplify, it's incredibly difficult to find anything online and I just keep trying things I see and they don't work.
What I already have:
I already have it working in the sense that I get an access_token back from the SAML provider, and that all works fine. So I know it's working fine (the login part), but the issue I am having is basically updating Amplify to now have the user in session so we can take advantage of functionality within Amplify that lets you refresh tokens when they expire.
Essentially, this is the flow I am using, from different sources I've found online:
await Auth.federatedSignIn({ provider });
this line of code can either be google, facebook or our custom SAML one we made. I already know this works, bc again, I already get my access token. So now, this is where my confusion starts. Obviously this function call here will take the user away from the page, hence we cant await this call, or i mean, you can, but it wont return the user on page reload. Which is fine, that part makes sense. So I have a function when the component is loaded that checks to see if theres a access_token in the url hash, which works as well.
Now, the issue is, Amplify doesn't know we signed in. We have "logged in" in the sense that yes, we have a valid JWT token now from the url hash access_token but the local Amplify does not know that this user is logged in.
So this is what I am talking about with the lack of documentation, perhaps I am crazy but I can't find a central source for how to handle this anywhere. I figured, once we have an id_token perhaps we can take advantage of Amplify Auth's federatedSignIn but now instead of just passing in a provider, they do have an option to send in a provider name, an id token, and expiree time and a user object, as noted here
As you can see there's different ways you can use this function, so I figure now that I have the id_token back from the response, I can use this method to actually tell Amplify that yes I am indeed logged in. As such:
await Auth.federatedSignIn(
provider_name,
{
token: id_token,
expires_at: expires_in,
},
user
)
When this fires I get the following error:
issue with access token NotAuthorizedException: Invalid login token. Issuer doesn't match providerName
Now I have verified 100% that the providerName is correct. This is the SAME provider name we pass in the original federatedSignIn call. the id_token is also the jwt id_token we get back from the Cognito and the SSO provider. the expiree is also 3600 so im assuming thats valid, and if it wasnt, the error would be different. I am just lost as to what I need to do at this point.
How can I have amplify recognize a federated sign in user? Since all we get back is a access_token and im beginning to think im not using the federatedSignIn method properly.

User registration/authentication flow on a REST API

I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.

Facebook Login without JSSDK, how to get token if already authorized previously

So I am updating an older desktop app (written in VB, .net 4.0) with facebook integration and followed the guide found here, and have been able to successfully get a token (by parsing the uri of the embedded webview if it contains "token="). Now my problem is if I try to login with a facebook account that has already approved the app in a prior session, the webview just gets redirected to https://www.facebook.com/connect/login_success.html without any token information.
Do I HAVE to log all of the tokens I generate manually (ie on successful token generation, I can call their profile info, use their FB ID as key and save the token)? Even if I do, since the email and password is input directly into the facebook login window, how do I check if the user already has a token?
Thanks in advance
The access token can change any time, you need to get it everytime. After getting the token, I immediately get the user information https://graph.facebook.com/me?access_token=??? and use that ID to find their database information.
I couldn't quickly find facebook information but on google's oauth information it says "The access token is also associated with a limited scope that define the kind of data the your client application has access to (for example "Manage your tasks"). An important goal for OAuth 2.0 is to provide secure and convenient access to the protected data, while minimizing the potential impact if an access token is stolen."
https://code.google.com/p/google-api-php-client/wiki/OAuth2
Ok so I finally figured it out myself. My mistake was apparently requesting the access_token directly (ie https://www.facebook.com/dialog/oauth?response_type=token...) to try and save time.
I fixed it by making a request for a 'code' instead (ie https://www.facebook.com/dialog/oauth?response_type=code), which I then use to make a second request to retrieve an access token as documented here: https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/, "Exchanging code for an access token" section a bit lower on the page.
Hope this helps someone in the future, this was very frustrating on my part.
Regards,
Prince

How to identify a Google OAuth2 user?

I used Facebook login to identify users. When a new user comes, I store their userID in my database. Next time they come, I recognized their Facebook ID and I know which user it is in my database.
Now I am trying to do the same with Google's OAuth2, but how can I recognize the users?
Google sends me several codes and tokens (access_token, id_token, refresh_token), however none of them are constant. Meaning if I log out and log back in 2 minutes later, all 3 values have changed. How can I uniquely identify the user?
I am using their PHP client library: https://code.google.com/p/google-api-php-client/
As others have mentioned, you can send a GET to https://www.googleapis.com/oauth2/v3/userinfo, using the OAuth2 bearer token you just received, and you will get a response with some information about the user (id, name, etc.).
It's also worth mentioning that Google implements OpenID Connect and that this user info endpoint is just one part of it.
OpenID Connect is an authentication layer on top of OAuth2. When exchanging a authorization code at Google's token endpoint, you get an access token (the access_token parameter) as well as an OpenID Connect ID token (the id_token parameter).
Both these tokens are JWT (JSON Web Token, https://datatracker.ietf.org/doc/html/draft-ietf-oauth-json-web-token).
If you decode them, you'll get some assertions, including the id of the user. If you link this ID to a user in your DB, you can immediately identify them without having to do an extra userinfo GET (saves time).
As mentioned in the comments, these tokens are signed with Google's private key and you may want to verify the signature using Google's public key (https://www.googleapis.com/oauth2/v3/certs) to make sure they are authentic.
You can see what's in a JWT by pasting it at https://jwt.io/ (scroll down for the JWT debugger). The assertions look something like:
{
"iss":"accounts.google.com",
"id":"1625346125341653",
"cid":"8932346534566-hoaf42fgdfgie1lm5nnl5675g7f167ovk8.apps.googleusercontent.com",
"aud":"8932346534566-hoaf42fgdfgie1lm5nnl5675g7f167ovk8.apps.googleusercontent.com",
"token_hash":"WQfLjdG1mDJHgJutmkjhKDCdA",
"iat":1567923785,
"exp":1350926995
}
There are also libraries for various programming languages to programatically decode JWTs.
PS: to get an up to date list of URLs and features supported by Google's OpenID Connect provider you can check that URL: https://accounts.google.com/.well-known/openid-configuration.
I inserted this method into google-api-php-client/src/apiClient.php:
public function getUserInfo()
{
$req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo');
// XXX error handling missing, this is just a rough draft
$req = $this->auth->sign($req);
$resp = $this->io->makeRequest($req)->getResponseBody();
return json_decode($resp, 1);
}
Now I can call:
$client->setAccessToken($_SESSION[ 'token' ]);
$userinfo = $client->getUserInfo();
It returns an array like this (plus e-mail if that scope has been requested):
Array
(
[id] => 1045636599999999999
[name] => Tim Strehle
[given_name] => Tim
[family_name] => Strehle
[locale] => de
)
The solution originated from this thread: https://groups.google.com/forum/#!msg/google-api-php-client/o1BRsQ9NvUQ/xa532MxegFIJ
It should be mentioned, that the OpenID Connect API returns no id attribute anymore.
It's now the sub attribute which serves as a unique user identification.
See Google Dev OpenID Connect UserInfo
"Who is this?" is essentially a service; you have to request access to it as a scope and then make a request to the Google profile resource server to get the identity. See OAuth 2.0 for Login for the details.
Altough JWTs can be validated locally with the public key, (Google APIs Client Library downloads and caches they public keys automatically) checking the token on Google's side via the https://www.googleapis.com/oauth2/v1/tokeninfo endpoint is necessary to check if the access for the applicaton has been revoked since the creation of the token.
Java version
OAuth2Sample.java

Authorizing for Google ToDo List (AuthToken, secid)

I'm trying to get access to the Google's todo feed with this url:
https://www.google.com/calendar/tdl?secid=<SECID>&tdl={%22action_list%22%3A[{%22action_type%22%3A%22get_all%22%2C%22action_id%22%3A%221%22%2C%22list_id%22%3A%2215052708471047222911%3A0%3A0%22%2C%22get_deleted%22%3Afalse}]%2C%22client_version%22%3A-1}
If I open this in my browser with a correct secid, it shows me right what I want.
Now, the question is: how do I get secid programmatically (specifically, in a java program)? I have access to the authToken (from CalendarService), but I have no clue how to use it to authorize my access to the URL above.
I tried to use the url http://google.com/accounts/ServiceLogin, but I didn't find any examples.
Any help, please?
From what I read secid is a session ID obtained from browser's cookies. Whereas your case uses Java which implies a server app. If that is the case, you want to drop the idea of using secid entirely.
Instead, you want to check out Google's OAuth2 documentation. If you are using Java, most likely you would be interested in the web-server OAuth flow. Pay special attention to the sequence diagrams.
The key steps include:
1) Obtain an authorization code from Google OAuth with the user's consent. For that, you redirect the user to Google with the appropriate scope. Check the list of calendar scopes for your case. Once the user consents, Google redirects back to you with an authorization code.
2) Call Google OAuth with the authorization code and your app's credentials to exchange for an access token.
3) Call Google's Calendar API using the access token.
And if you use Google's Java client as suggested by #ChaosPredictor, chances are some of the steps are already wrapped into the Java client (and your code will be much simpler).