Grails using Google authentication with the Spring Security plugin - authentication

Has anybody managed to successfully combine Google authentication with Burt Beckwith's awesome Grails-based Spring Security plugin recently? I wanted to go down that path with Grails 2.4.3, and after some fooling around (and recompiling the donbeave version of the plugin at https://github.com/donbeave/grails-spring-security-oauth-google) I was able to find a combination of references that would compile and run together. I ended up adding the following lines to my BuildConfig.groovy:
compile ':spring-security-core:2.0-RC4'
compile ":spring-security-oauth:2.1.0-RC4"
compile ':spring-security-oauth-google:0.3.1'
I found, however, that the changes created by the initialization command “grails s2-init-oauth” don’t give me all the modifications that I need in order to move forward. I ended up adding a block to my config.groovy that looked like this:
oauth {
providers {
google {
api = org.grails.plugin.springsecurity.oauth.GoogleApi20
key = 'MY KEY'
secret = 'MY SECRET'
successUri = '/oauth/google/success'
failureUri = '/oauth/google/error'
callback = "${baseURL}/oauth/google/callback"
scope = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email'
}
}
}
These config definitions specify a callback in my code (referred to above as ./oauth/google/callback) which didn’t exist. After I brought in a controller from the recommended example (https://github.com/bagage/grails-google-authentification-example), substituted "/springSecurityOAuth/onSuccess" for "/oauth/google/callback", (and registered by redirect URL through the Google Developers Console) I found that my onSuccess method was indeed being called, but the data structures referenced in the controller were wrong, and it seemed as if I would need to largely rewrite the controller logic in order to get everything working. I have to assume that other people want to accomplish Google-based authentication in the same way that I do. Is there an complete operational example somewhere? Or can someone tell me where I’ve gone wrong in my attempt to utilize the standard plug-ins? Thanks for any assistance.

You need to use spring security oauth plugin also. Please refer here https://github.com/cazacugmihai/grails-spring-security-oauth,
When you click on button, it hits the authenticate action inside Oauth controller which gets
authentication()
url of the google. After successful authentication, it hits callback() action Of Oauth controller which then redirects to onSuccess() action of SpringSecurityOauthController which then saves the info to OAuthId domain and finally redirects to the successUri given in config.

Related

What is the RIGHT way to access Google websites from within an electron app? [duplicate]

A user of my app reported an issue today about authorizing the user with Google (using OAuth 2.0). So far the application was opening a new BrowserWindow (node integration disabled, session is separated from the main application). You can see the implementation here since the library is OSS. I am using this to authorize the user to access application data on Google Drive.
Today after logging in I see the following message:
This browser or app may not be secure.
Try using a different browser. If you’re already using a supported browser, you can refresh your screen and try again to sign in.
The learn more link has a section for developers. This section has 2 links. One is how to upgrade the application to PWA. Because the application is an API testing tool it won't be possible to run it in a web browser.
The second link points to a document describing how to migrate to authorization for native application. However described flow requires authorization_code grant. This means I need to include OAuth secret into my application. Electron application, however, is still web application and there's no notion of compiling sources. I would expose client secret to the public which is not secured. Potentially I could build a server application to support it but the app is OSS project. It does not have funding to run a server for authorization.
My question is now how should I implement OAuth 2 for Electron application then. I can't use PWA's and server authorization flow (code grant) is far from ideal in this case.
As Paweł explained, changing the user agent will do the trick. However, you can easily set the user agent by passing an object when loading the URL
win = new BrowserWindow({width: 800, height: 600});
win.loadURL(authUrl, {userAgent: 'Chrome'})
I have tested it and it worked like a charm
Warning: This answer relies on changing the browser's user-agent. As of Jan. 2021, Google disapproves of this and warns not to do this (see EDIT4). Use at your own risk!
The other answers didn't work for me (in Electron 9.0.5), but I eventually found this, which worked:
app.on("ready", ()=> {
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
details.requestHeaders["User-Agent"] = "Chrome";
callback({ cancel: false, requestHeaders: details.requestHeaders });
});
CreateMainWindow(); // your regular code to create root browser window
});
EDIT: Two other approaches, which I haven't tested, but which may also work:
app.on("ready", ()=>{
session.defaultSession.setUserAgent("Chrome");
...
}
app.userAgentFallback = "Chrome";
EDIT2: Trying again sometime later, approach #2 did not work, but #1 still did. Haven't tried #3 yet.
EDIT3: Trying again later still, it seems that none of these workarounds are needed anymore! Google appears to accept sign-in popups from Electron apps again, without modifications to the user-agent. (odd that they'd revert this; perhaps I just did something wrong in my re-attempt)
EDIT4: While approach #1 still works atm, I recently found this blog post: https://developers.googleblog.com/2020/08/guidance-for-our-effort-to-block-less-secure-browser-and-apps.html Apparently Google is restricting usage of Google sign-in in non-standard browsers (which presumably includes Electron) starting in Jan. 2021, and warns developers not to modify their browser's user-agent (which all three of the possibilities I mention do). Use at your own risk! (they don't make clear what outcome will result, but for my own use, I'm opting to use the alternative shown below from now on)
As an alternative to using a Google sign-in popup in your app (which some might be wary of, since Electron apps could in principle insert code into the popup to read the raw password -- not that it matters that much, since Electron apps could just install keyloggers or the like anyway), you could instead open a tab in the user's regular external browser, pointed to a special page that triggers a sign-in popup there, and then just sends the credentials to your Electron app afterward.
Instructions can be seen here (approach 3): https://stackoverflow.com/a/64328193/2441655
After taking a wild guess I decided to alter the user agent string and to remove application name from it as well as Electron/ with version. After this alteration it started working again.
Example implementation:
const win = new BrowserWindow(params);
let ua = win.webContents.userAgent;
ua = ua.replace(/APPLICATION NAME HERE\/[0-9\.-]*/,'');
ua = ua.replace(/Electron\/*/,'');
win.webContents.userAgent = ua;
This assumes the application is using symver and no pre-release tags. Otherwise you would have to tweak the regexp a bit.

Symfony 3.4 Custom Authentication Listener

I have implemented a login form manually in Twig and I am using the default authentication provided by Symfony 3.4 (based on username and password). Users are stored in a database, therefore I have an Entity which extends AdvancedUserInterface. I am using neither FOSUserBundle nor form builder. Just a simple form. It actually works.
The problem is that I want to integrate Google reCAPTCHA in the login process. I know how to check if the captcha is valid and implemented a custom AuthenticationListener (let's call it MyAuthenticationListener).
I know that Symfony uses UsernamePasswordFormAuthenticationListener as its default listener. The problem is that I could not find a way to change the used listener to that I have implemented.
It seems that in Symfony2 it was as easy as adding the following line in the config.yml:
parameters:
security.authentication.listener.form.class:
MyBundle\EventListener\MyAuthenticationListener
However, I cannot find a way for Symfony3. Any suggestions?
I also tried to find a specific bundle for Symfony3, but I actually could not find anything that is correctly integrated with Symfony Security, allowing me to use the recaptcha in a login form.
Thank you
Your question may be answered here:
https://stackoverflow.com/a/50800993/7408561
The solution is based on a custom-listener triggered by SecurityEvents::INTERACTIVE_LOGIN. That event is fired after verification of credentials but before redirecting to default_target_path defined in security.yml. At this position you can verify the request parameter g-recaptcha-response by calling the google recaptcha api with the corresponding secret.
If the verification fails you can throw an exception and you will be redirected to the login page.

Extern auth services with Web API - can't get the sample to work

I can't get the sample External Authentication Services with Web API(C#) to work with Google. I created a project by following the instructions. However, I noticed that my project created a slightly different code in Startup.ConfigureAuth() method.
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "<valid client id here>",
ClientSecret = "<valid secret here>",
});
The code in the sample does not have the initialization part but without it the code will not even compile.
When I run the app I get the option on the Log In screen to use Google as a service to log in. I'm then taken to Google's site and asked to allow my app to use my info. The app's name appears to be correct so I have to assume that ClientId/ClientSecret provided above are correct. However, when I click "Allow" button I'm taken back to the Log In page instead of the Register page as illustrated in the example.Has anyone managed to make the sample work with Google authentication? If yes, could you please share workarounds, if any.Thanks.
I finally found the source of the problem with a help of a post on this site. Unfortunately I lost the link to the post. Anyway, the solution is to make sure that Google+ APIs are enabled in Google Console for the project - they are not enabled by default. The details can be found here (as suggested by the post).

Sitecore with LDAP - authenticate programmatically

I am creating an app inside Sitecore and I only want it available to the users via a direct URL. I want the authentication to occur against LDAP. I tried going directly to the app and let it redirect to the auto login page and redirect me to the app but it didn't do it. Instead it took me to the Sitecore login page.
I'm wondering if it is possible for me to write some code to auto authenticate a LDAP user and redirect to the app page. I want the user to never see the login page or Sitecore desktop or any of the Sitecore screens other than that one app.
Thanks
We accomplished something similar by combining the AD module with some custom code in the Global.asax. Below are a few lines that might be helpful. You'll likely need a bunch of logic to check if the user is already logged in, and whether they are accessing a path you want to auto-login for.
NOTE: Make sure windows authentication is enabled in IIS.
protected void Session_Start(object sender, EventArgs e){
// The user from Windows Authentication in IIS
var user = Context.Request.ServerVariables["LOGON_USER"];
//Log the user in
bool success = Sitecore.Security.Authentication.AuthenticationManager.Provider.Login(user, false);
}
You'll note that the sample I provided goes directly to the provider. You can also call Login at the AuthenticationManager class, and this will also do some other work with cache. In my case, I was trying to bypass that.
UPDATE (2017-06-29):
In newer versions of Sitecore it is not recommended to make changes to the Global.asax. Unfortunately, there is no equivalent pipeline in Sitecore. You can attempt to use httpRequestBegin (where the UserResolver processor is) or httpRequestProcessed, but these will fire on every single request.
One alternative (credit to #Mark Cassidy on SlackChat) is to use the Initialize pipeline and in that processor register to the session start event.
It is possible yes, a quick Google search turned up these:
http://www.nehemiahj.com/2013/01/how-to-enable-single-sign-on-in-sitecore.html
based on the AD Module from Sitecore
http://sdn.sitecore.net/SDN5/Products/AD/AD11/Documentation.aspx
That should give you a good place to start from.

How to make the login/ page in Grails Spring Security 2.0 the inital screen?

I am migrating from grails 2.2.2 to grails 2.3.4 to avoid a bug in 2.2.2 where the text value in the spring security property messages where not displaying, but I am running into all sorts of issues. Stuff that worked before, now it does not.
PROBLEM
When I run the grails app, the initial default page is index.gsp which is standard functionality but after installing and configuring the spring security core, spring security ldap, and spring securiy ui plugins I would like to make the /login/auth my default page.
In the previous release, I had it done via the UrlMappings.groovy config file by simply commenting, replacing or deleting this line
"/"(view:"/index")
for this one
"/"(view:"/login/auth")
My Config.groovy is set so that if the authentication is successfull to take me to the home page
grails.plugin.springsecurity.userLookup.userDomainClassName = 'security.Person'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'security.PersonAuthority'
grails.plugin.springsecurity.authority.className = 'security.Authority'
grails.plugin.springsecurity.requestMap.className = 'security.Requestmap'
grails.plugin.springsecurity.securityConfigType = 'Requestmap'
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/home/'
and my Requestmap entries in the Bootstrap (if they are of any importance for this issue are as follows):
for (String url in [
'/', '/index', '/index.gsp', '/**/favicon.ico',
'/**/js/**', '/**/css/**', '/**/images/**',
'/login', '/login.*', '/login/*',
'/logout', '/logout.*', '/logout/*']) {
new Requestmap(url: url, configAttribute: 'permitAll').save()
}
new Requestmap(url: '/home/*', configAttribute: 'IS_AUTHENTICATED_FULLY').save()
It turns that when i do that... Eureka the login/auth comes as soon as the application is started but when I put the correct authentication credentials it does not seem to authenticate, it does does a 'slight little flicker' and it shows itself again.
However, If I delete this line
"/"(view:"/login/auth")
and put this one back in
"/"(view:"/index")
and then when I restart the application I manually to login/auth and put the correct credentials then it correctly takes me to the home page.
QUESTIONS
Did I miss any config setting anywhere that would make the login/auth the first page (but also allowing me to authenticate)?
I am not sure if this should be a separate posted question, but now by design the login page it's part of the plugin, before it was generated by and part of my code and I could style at my will. Do I have to copy paste the LoginController and the Auth.gsp in my app in order to customize the view or is there a better preferred way?
Thanks in advance.
The authentication mechanism in Spring Security works by keeping track of a referral URL when the login page is shown. And then redirecting to this page on a successful login. If you want the login page to be the first page people see just make the root view require authentication. I'm assuming most, if not all, of your application requires authentication. If this is the case, you don't need to make the login page the root view. Assuming everything under /home/* is locked down then Spring Security will detect that and immediately redirect to the login page when any of the secured pages are requested.
Long story short, you're making it harder than it needs to be.
As to your second question, I do believe you just need to create your own versions of those files in your app to customize them.
Hey I'm not pretty sure about your problem but you can try making the default login url /login/auth by
grails.plugin.springsecurity.auth.loginFormUrl = '/login/auth'