Is there a way to have a 'Google Sign In' button for google accounts that are not signed up with Google Plus? - google-oauth

I'm working on an internal website for the company I work for. The website will be only available to company staff. We use Google Apps for Business, so we would like authentication to be done using our google accounts.
I've gone through 'google sign in' samples from here: https://developers.google.com/+/
It works, but the problem we run into is that it requires the user to sign up to Google+. This is a speed bump we would prefer not to have.
Are there any ways around this? Thanks.

It shouldn't be too hard to roll your own sign in using the lower levels of Oauth, eg 'email' scope. It's hard to give a more specific answer because it depends on your architecture (eg. are you predominantly server-side or client-side) and what kind of session do you want to create by the sign in process. For example, if you are client/REST based, you probably don't want any session at all as REST encourages statelessness. On the other hand, if you are more web based, serving static pages, you will want a session.
In simple terms, you will be doing something that generates an access token, and then processing that access token to determine the email address (or Google ID) of the person who created it. You will then establish some sort of session (eg. using session cookies) that identifies future requests from that user.
Feel free to add some more detail to your architecture and I'll try to finesse the answer.
For simple http servlet sessions, it will be something like.
User requests a protected page
servlet detects that there is no session and/or session has no authenticated user
servlet redirects to an Oauth page to request an access code. something like
https://accounts.google.com/o/oauth2/auth?redirect_uri=xxx&response_type=code&client_id=zz&approval_prompt=auto&scope=email
NB research the exact URL, don't rely on this to be exact
If the user isn't logged on, he'll be prompted; if he has multiple logins, he'll be prompted; if he hasn't yet granted email access, he'll be prompted. If none of these conditions are met (the normal case) he won't see anything.
Browser will redirect to the redirect_uri, carrying an access token (or an auth code if this is the first time the user has used the app)
Post the token to the Google userinfo endpoint, and you will receive a decode containing the email address
Store the email into a session object (or retrieve your own user object and store that)
redirect back to the originally requested page. You can use the OAuth state parameter to pass that around
et voila. all future page requests from that user will be within a session containing some user identification.
NB This is just an outline and I may even have missed a step. You will still need to do your own OAuth research.

Apparently not:
(..) if a Google user who has not upgraded to a Google+ account clicks
on the Sign in with Google+ button, the same consent dialog that opens
will take the user into an account upgrade flow.
Weirdly the docs for OAuth2 states:
Google+ Sign-In works for all users with a Google account, whether or
not they have upgraded to Google+.

Related

Keycloak - Multi/2FA Factor - OTP - QR Code - Custom Login Screen - Rest API

I have my own Login page where user enters username/password.
This username/password are used to login through Keycloak Rest API.
http://localhost:8080/auth/realms/Demo/protocol/openid-connect/token
input - {username,password,grant_type,client_secret,client_id}
And in response i get access token.
Now i wish to enable Authenticator (Google Authenticator). I have enabled it from backend. Now if user wishes to login thorugh my application, my login page i need to get below details.
1.) Somehow i need to include QR Code that appears on keycloak login page post username/password validation to show on my login screen for the first time login once user enter username/password. So do we have any API which return Keycloak QR code image in response.
2.) Subsequent login i will have OTP field, so need a REST api to pass OTP along with username/password.
Please help with REST API if keycloak has any. Integrating through Javascript.
Similar flow as described in use case 1 here
Just want to use keycloak as a database, doing all operation for me, input will be my screen. I do want redirection of URL's while login in and yet should be standalone deployed.
I've managed to implement this through the rest API of Keycloak. To realize this, you need to extend Keycloak yourself with a SPI. To do this create your own Java project and extend org.keycloak.services.resource.RealmResourceProvider and org.keycloak.services.resource.RealmResourceProviderFactory. You can find more information in the official docs (https://www.keycloak.org/docs/latest/server_development/#_extensions), github examples and other stack overflow posts how to do this.
Once you got this up and running you can implement it like this:
#GET
#Path("your-end-point-to-fetch-the-qr")
#Produces({MediaType.APPLICATION_JSON})
public YourDtoWithSecretAndQr get2FASetup(#PathParam("username") final String username) {
final RealmModel realm = this.session.getContext().getRealm();
final UserModel user = this.session.users().getUserByUsername(username, realm);
final String totpSecret = HmacOTP.generateSecret(20);
final String totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user);
return new YourDtoWithSecretAndQr(totpSecret, totpSecretQrCode);
}
#POST
#Path("your-end-point-to-setup-2fa")
#Consumes("application/json")
public void setup2FA(#PathParam("username") final String username, final YourDtoWithData dto) {
final RealmModel realm = this.session.getContext().getRealm();
final UserModel user = this.session.users().getUserByUsername(username, realm);
final OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromPolicy(realm, dto.getSecret(), dto.getDeviceName());
CredentialHelper.createOTPCredential(this.session, realm, user, dto.getInitialCode(), otpCredentialModel);
}
The secret received with the GET must be send back with the POST. The initial code is the one from your 2FA app (e.g. Google Authenticator). The QR code is a string which can be displayed in an img with src 'data:image/png;base64,' + qrCodeString;
I know this is an old question, but I've recently been looking at something similar, and so thought it would be potentially valuable to share what I have found for others who may be looking into this and wondered what the possibilities are.
TL;DR
You can only really use the existing Keycloak actions to do this or embed the user account management page found at https://{keycloak server URL}/auth/realms/{realm name}/account in an iframe. That's it, I'm afraid. In my opinion it is currently best to just assign actions directly to accounts or use the Credential Reset emails to assign actions; both of these can be done via the Admin API if desired:
Send Credential Reset email containing assigned actions:
https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_executeactionsemail
Set actions directly on the account (include the actions in the requiredActions portion of the user JSON that you send in the body to the endpoint):
https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_updateuser
Background is that as part of a project that I have been working on we wanted to see if we could have an integrated way for users to set up their initial password and OTP device when a new account has been created for them, since the default method of sending them an email from Keycloak using the "Credential Reset" functionality has the limitations that a) it doesn't provide a link to the application itself unless you override the theme, and if you have multiple instances of the application for different users you have no way of knowing which instance to provide the link for, so may have to end up including a list of them, and b) it often doesn't feel truly native to the application, even with changes to the theme. If you're sensible though, I'd suggest you stop and just use this functionality - please see the TL;DR section above for details.
So, in short there is NO API endpoint for receiving a QR code to set up an OTP device. There are two places, however, where the QR code can be retrieved from - the OTP device setup screen when you log in as a user who has had a "Configure OTP" action assigned to their account, and the user's own account management screen.
The first option of the Configure OTP action screen is a non-starter. It only shows up when you log in, and so by definition the user has to log in to Keycloak via the Keycloak login page in order to trigger the page to be displayed. At this point you're already on a Keycloak page instead of one of your app's pages, and so unless you can get very creative with changes to these Keycloak pages via a custom theme, tapping into this page isn't really an option.
The second option is more interesting, but far from ideal. Every user who has logged in has access to an account management page that can be found at https://{keycloak server URL}/auth/realms/{realm name}/account. This page allows you to do things like change your name, password, etc. and it also allows you to add an OTP device if you don't already have one, or delete any existing OTP devices associated with your account. This OTP device tab of the account management page can be reached directly via https://{keycloak server URL}/auth/realms/{realm name}/account/totp.
As I mentioned, there isn't an API that you can access to view the QR code that shows up on this page. The only way it is accessible is via the GET request to https://{keycloak server URL}/auth/realms/{realm name}/account/totp, which returns the HTML for the page I've already mentioned. Okay great, so can we scrape the QR code programmatically and then put it in our own page on our application? Err, no, not really. You see, whilst a lot of the Keycloak API endpoints rightly allow you to send a bearer token (e.g. access token) in the authorization header to access and endpoint, this page will not accept a bearer token as a means of authentication/authorization. Instead it uses a session cookie that is locked down to the Keycloak URL. This cookie is set when you log in to your application via the Keycloak login page, and so is available to this account management page when you navigate to it, having already logged in, and since the account management page uses the same server and domain name as the original Keycloak login page, it has access to the cookie and can let you in. This cookie cannot be sent by your application to e.g. your own REST API to then programmatically call the account management page and scrape the QR code, because your application doesn't have access to it for good security reasons. This might be something you can change in Keycloak somewhere, but if there is I would strongly recommend against changing it.
So if we can't scrape the page from our own server, can we do something on the front-end? Well, as mentioned, your application doesn't have access to the session cookie but if you make a request (e.g. using fetch or axios) in your front-end JavaScript to the account management page then that request will send the cookie along with it, so that could work right? Umm, well actually you will get hit with an error message in this scenario due to CORS. CORS is Cross-Origin-Resource-Sharing and in order to allow the Keycloak page to be accessed then you would have to open up the settings on the server to allow it to be accessed from your website's address. I've seen some articles that look at how you can open up your CORS settings on Keycloak if you wish but I'd be very nervous about doing this. I don't know enough about the internals of Keycloak and how it operates to comment on how much of a security risk this is, but I certainly wouldn't recommend it. There some information here (Keycloak angular No 'Access-Control-Allow-Origin' header is present) on changing the "Web Origins" setting of your application's Keycloak client, but this opens up your application to some serious potential abuse. There is also the MAJOR issue that even if you scraped the QR code, the device isn't actually added to the user's account (even though it appears in the authenticator app) until you enter a code into the page that the QR code is on and click Save. Since there isn't an API endpoint that you can use to complete this operation, I therefore don't think that this option is viable either. I've tried out whether or not you can use the token retrieval endpoint at https://{keycloak server URL}/auth/realms/{realm name}/protocol/openid-connect/token to see if making a request with your username/password/otp code will somehow "register" your device and complete the process, but although you can get a token this way, and it doesn't complain about the otp code, it doesn't actually take any notice of the code because as far as it's concerned the user's account doesn't have a device registered with it. So we have to use the form on the account management page in order to complete this registration process.
So the final way of possibly doing this is.... an iframe. Sorry, yeah it's rubbish but that's all your left with. You can have the iframe point at your account management page, and because the user is logged in then they will be able to see the contents from your application's page. You can use relative positioning, fixed width and height and remove scroll bars to ensure that you ONLY show the QR code and the fields for the one time code, device name, and the Save/Cancel buttons. This, sadly, seems to be the only option at the moment, and due to how nasty and unreliable iframes can be in general - they certainly don't feel native to your application, and you'll need to override your Keycloak theme to get the page in question to look more like your app - I'd recommend steering clear of this and using the standard approach of using Keycloak actions and the Admin API instead.
If you've made it this far, congratulations, you win at Stack Overflow :-)

Securing non authenticated REST API

I have been reading about securing REST APIs and have read about oAuth and JWTs. Both are really great approaches, but from what I have understood, they both work after a user is authenticated or in other words "logged in". That is based on user credentials oAuth and JWTs are generated and once the oAuth token or JWT is obtained the user can perform all actions it is authorized for.
But my question is, what about the login and sign up apis? How does one secure them? If somebody reads my javascript files to see my ajax calls, they can easily find out the end points and the parameters passed, and they could hit it multiple times through some REST Client, more severely they could code a program that hits my sign up api say a thousand times, which would be create a thousand spam users, or they could even brute force the login api. So how does one secures them?
I am writing my API in yii2.
The Yii 2.0 framework has a buil-in filter called yii\filters\RateLimiter that implements a rate limiting algorithm based on the leaky bucket algorithm. It will allow you to limit the maximum number of accepted requests in a certain interval of time. As example you may limit both login and signup endpoints to accept at most 100 API calls within a 10 minutes interval of time. When that limit is exceeded a yii\web\TooManyRequestsHttpException exception (429 status code) will be thrown.
You can read more about it in the Yii2 RESTful API related documentation or within this SO post.
I didn't use it myself so far but from what I did read about it in official docs, and I mean this:
Note that RateLimiter requires
$user
to implement the
yii\filters\RateLimitInterface.
RateLimiter will do nothing if
$user
is not set or does not implement
yii\filters\RateLimitInterface.
I guess it was designed to work with logged in users only maybe by using the user related database table, the default one introduced within the advanced template. I'm not sure about it but I know it needs to store the number of allowed requests and the related timestamp to some persistent storage within the saveAllowance method that you'll need to define in the user class. So I think you will have to track your guest users by IP addresses as #LajosArpad did suggest then maybe redesigning your user class to hold their identities so you can enable it.
A quick google search let me to this extension:yii2-ip-ratelimiter to which you may also have a look.
Your URLs will easily be determined. You should have a black list of IP addresses and when an IP address acts suspiciously, just add it to the black list. You define what suspicious is, but if you are not sure, you can start with the following:
Create something like a database table with this schema:
ip_addresses(ip, is_suspicious, login_attempts, register_attempts)
Where is_suspicious means it is blacklisted. login_attemtps and register_attempts should be json values, showing the history of that ip address trying to log in/register. If the last 20 attempts were unsuccessful and were within a minute, then the ip address should be blacklisted. Blacklisted ip addresses should receive a response that they are blacklisted whatever their request was. So if they deny your services or try to hack things, then you deny your services from them.
Secure passwords using sha1, for example. That algorithm is secure-enough and it is quicker than sha256, for instance, which might be an overkill. If your API involves bank accounts or something extremely important like that, important-enough for the bad guys to use server parks to hack it, then force the users to create very long passwords, including numbers, special characters, big and small letters.
For javascript you should use OAuth 2.0 Implicit Grant flow like Google or Facebook.
Login and Signup use 2 basic web page. Don't forget add captcha for them.
For some special client such as mobile app or webServer:
If you sure that your binary file is secure, You can create a custom login API for it. In this API you must try to verify your client.
A simple solution, you can refer:
use an encryption algorithm such as AES or 3DES to encrypt password
from client use a secret key (only client and server knows about it)
use a hash algorithm such as sha256 to hash (username + client time + an other
secret key). Client will send both client time and hash string to
server. Server will reject request if client time is too different
from server or hash string is not correct.
Eg:
api/login?user=user1&password=AES('password',$secret_key1)&time=1449570208&hash=sha256('user1'+'|'+'1449570208'+'|'+$secret_key2)
Note: In any case, server should use captcha to avoid brute force attack, Do not believe in any other filter
About captcha for REST APIs, we can create captcha base on token.
Eg.
For sign up action: you must call 2 api
/getSignupToken : to get image captcha url and a signup token
respectively.
/signup : to post sign up data (include signup token and
captcha typed by user)
For login action: we can require captcha by count failed logins base on username
Folow my api module here for reference. I manager user authentication by access token. When login, i generate token, then access again, client need send token and server will check.
Yii2 Starter Kit lite

OAuth2 Login for Google Calendar API

I'm making a website for a football club. they have one google calender (and just one google account). on the website I'd like to have a list of upcoming events. So I've to access to Google Calendar via Google API. For Authorisation I've to use OAuth2. Is it possible to login with OAuth2 automatically so that the website visitors don't have login always via redirect (to google login site)? For example I make a the login via Java, instead of a user login? Because it's no so comfortable if every user of the website have to login, for just viewing the club calendar.
Not sure it is possible,
Important note concerning your design: if you login automatically to the club's account, it means that everyone that uses this website is logged in to Google Calendar on behalf of the club's user name. hence, everyone can CHANGE the calendar, delete events, etc.
Are you sure you want this to happen?
(you can set the login params to "read-only", but even then, it means that the club shows ALL his calendar to everyone. there is no privacy...)
I suggest that every user logins with his own creds, and the club's calendar can invite all registered users to his events....
Of course, you can do it, and even without giving the access to the visitor if you're doing this on the server side.
You need to do a initial step by hand.
After this step you get a refresh token, with this token you can regenerate the access token which you need to access to the calendar API, for instance to get the upcoming events.
You need to regenerate the access token if the previous access token is expired. In this case you also get an new refresh token. You need to save it, into a database or JSON file.
To get a refresh token you need to pass this options on authorization:
access_type: "offline"
approval_prompt: "force"
Without these options you only get an access token, no refresh token.
Here is the documentation: https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl
And here a kind of tutorial: http://www.tqis.com/eloquency/googlecalendar.htm

Devise: Migrate Google Open ID to Google OAuth

Does anyone have clues about how to do this? I'm basically trying to replace the strategy for "Connect With Google" from OpenID to OAuth. The challenge is identifying an old user (user on Google open ID) when a user signs in under the new OAuth scheme.
I have a working implementation which relies on email address as the primary key, as the open ID strategy captures that. The problem is, I don't want to ask for email in the OAuth flow. The ideal value is simply Google user ID, but the Open ID strategy doesn't seem to capture that.
So I have open ID tokens like https://www.google.com/accounts/o8/id?id=AfSCwGQ4PUaidXSQddJugXKLqU5V0MrXFhJM6UHybPw and trying to understand if I could get a Google ID from that.
UPDATE: I explained here how I ended up doing this migration - http://softwareas.com/migrating-user-accounts-from-google-openid-to-google-oauth-to-google-plus
We don't have a strategy ready today that avoids the user seeing another approval page.
However, rather than attempt to do an OAuth1 based hybrid flow and have to add all that legacy code to your server, I'd suggest you simply correlate on email address and move to OAuth2 login. I'm assuming you're like the majority of sites that end up asking for email address because they usually want it for account recovery. Just make sure you get the email address from OpenId as one of the signed parameters.
Then use the userinfo.email scope and OAuth2 https://developers.google.com/accounts/docs/OAuth2Login and you should be able to migrate with less developer pain.
In addition, we're in the process of adding support for OpenIDConnect and it supports a parameter of login_hint so you'd add &login_hint=bob#gmail.com to your authorization URL and it will steer the approval to the right account. This is not documented right now but it may be useful for you to try it. The user's browser could be logged into Google with a number of accounts and you want to try to get the right one. Always check the email you get from the OAuth2 flow to make sure it matches since this is just a 'hint'.
Users will still have to re-authorize for OAuth2, but we have plans to skip this reauthorization in the future. The main point is to plan on using OAuth2 and we hope to deliver a seamless migration soon and you'll be on a supported protocol.
Google uses directed identifiers for OpenID that are unique per relying party and are explicitly designed to conceal any correlatable identifier for the user. So the short answer is, no there's no way to get a Google ID that corresponds with a given Google OpenID.
One option, however, might be to use Google's OpenID+OAuth Hybrid flow. This allows you to get an OAuth token as part of a normal OpenID flow, which could then be used to get the user's ID from the OAuth2 Login API, which you can then associate with their existing account. Once you've done that for all of your existing users, then switch to using the OAuth2 Login directly.
The trick, of course, with this approach is getting all of your users to login again so that you can send them through the new flow. That will come down to how long you're willing to wait to migrate accounts, and whether you're willing to prod existing users by emailing them and asking them to login again (similar to a forced password reset).

How safe am I signing into Google Spreadsheets with yeroon.net/ggplot2

I am impressed by what I have seen of yeroon.net/ggplot2 which is a web interface for Hadley Wickham's R package ggplot2. I want to try it out on my own data. The part that has me very excited is that one can use data stored in one's own Google spreadsheet as the data. One just signs into their Google Account so that yeroon.net/ggplot2 can access the spreadsheet list. I have been hesitant to do it. If I sign in whilst on yeroon.net am I handing over my username and password to a third party? It would not be wise of me to divulge my google password to third parties since Google is fast becoming my repository of everything.
How do I know if Jeroon's application is using ClientLogin or OAuth? My understanding is very basic and may be wrong but nevertheless here it is. OAuth would be better since it does not actually pass the password onto the third party application.
I am the creator of the yeroon.net/ggplot2, someone pointed me to this topic. I'll try to explain how the system currently works.
The application is using AuthSub authentication. The moment you sign into your Google account, a Google session is created. This session only has access to the Google documents and Google spreadsheet services that you gave permission for on the Google login page, so not to e.g. your mailbox.
Once you logged in, you retrieve a session token from Google: a unique key that belongs to the session and can be used to make requests to access your Google data. The session token is stored as a cookie on your browser until you close it. Every time you make a request to yeroon.net servers, this token is added to the request.
Using this token, the yeroon.net servers can access your google data, e.g. to retreive a spreadsheet. The token is not stored on the server, although I understand that you have to take my word on this. Also it is not possible to find out your username or password from the session token; it can only be used to retreive data, as long as the session lives.