The reference being purely taken from following sites:-
http://syntx.io/integrating-your-java-spring-mvc-webapp-with-facebook-doing-the-oauth-dance/
http://www.oodlestechnologies.com/blogs/OAuth-2.0-implementation-in-Spring-Framework
I've developed String Security OAuth2 Facebook integration example, Now I'm looking forward to developed the Security OAuth2 Google (and later Github) integration example where AppID and Secret will be provided to get "access_token" and "refresh_token" etc to be used to access the protected resources like UserDetails etc..
So, first step will be register App on http://code.google.com/apis/console. So it gives me "Client ID" and "Client secret", also I've configured Redirect URI, Done !
Now I've started writing actual Apache OAuth client, but I'm not sure what parameters I need to provide (similarly I provide for Facebook Integration, those parameters were easily available on facebook,while doing google search, but not found for Google), Please provide me suggestions what values should be given for the following blank parameters -
I think I've provided enough information, so any guidance / help / links is appreciated.
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation("")
.setClientId("3kT21Hlkzzt5eV1")
.setRedirectURI("http://localhost:8080/apache-oltu/google/redirect")
.setResponseType("")
.setScope("")
.buildQueryMessage();
The following code is developed for callback
private void getAccessToken(String authorizationCode) throws OAuthSystemException, OAuthProblemException {
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("")
.setGrantType()
.setClientId("3kT21H5EO3zzt5eV1")
.setClientSecret("1kT21Hdlkzzt5eV1")
.setRedirectURI("http://localhost:8080/apache-oltu/google/redirect")
.setCode()
.buildBodyMessage();
Added the following code to get protected resources like user profile:
request= new OAuthBearerClientRequest("https://www.googleapis.com/auth/userinfo.profile").
setAccessToken(oAuthResponse.getAccessToken()).
buildQueryMessage();
See here for a complete example:
http://mail-archives.apache.org/mod_mbox/oltu-user/201503.mbox/%3CA562FE5D3662044186474F4174F11DAE13044C639F#iowajhnex126.iowa.gov.state.ia.us%3E
I've developed Apache Oltu and Spring integration example and it's working fine at my end.
You need to enable the Google+ API as suggested by #prtk_shah. Thanks.
You need to go to the https://console.developers.google.com/project?authuser=0 and click on your project, in my case it's "apache-oltu", in your open project find option "APIs and auth" --> APIs. search for Google+ API and enable it.
Here you should be able to see this screen.
So, I will modify your code below it should be like this:
(IMP) - Your client ID should be like this, For Ex: (755670439314-jcumfghnkmcm72hf40beikvoatknstml.apps.googleusercontent.com), Please make sure it is correct. Fyi - use as it is provided by google developer console
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation("https://accounts.google.com/o/oauth2/auth")
.setClientId("3kT21Hlkzzt5eV1.apps.googleusercontent.com")
.setRedirectURI("Give your projects redirect URI")
.setResponseType("responsecode")
.setScope("openId profile email")
.buildQueryMessage();
The callback code should be:
private void getAccessToken(String authorizationCode) throws OAuthSystemException, OAuthProblemException {
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("https://accounts.google.com/o/oauth2/token")
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId("give your complete client id")
.setClientSecret("give your secret")
.setRedirectURI("This will be your callback or Redirect URL (Give it correctly)")
.setCode(authorizationCode)
.buildBodyMessage();
Here is what I'm getting in my example, just wanted to show you
Hope this will be helpful.
Related
Trying to create a web client that uses oauth to connect to multiple sso endopints, google mainly. This is on top of a spring boot project, I just keep getting the same error that no code is provided, but I'm not sure how i'm supposed to get a code without the access token first. Here is a simple version of what im trying to run I want localhost/8080 to redir to google to login and comeback to the same page or a different one doesn't matter
#RequestMapping("/google")
fun google(#RequestParam(value = "code") code: String?, model: Model): String {
val clientId = "asdf.apps.googleusercontent.com"
val secret = "1234"
var goog = GoogleAuth.create(Vertx.factory.vertx(), clientId, secret)
goog.authenticate(JsonObject().put("code", code), {
System.out.println(it)
})
return "test"
}
the error is always
"error": "invalid_request",
"error_description": "Missing required parameter: code"
}}
e```
but how can I provide a code first I need some sort of response from the server. I'm pretty familiar with restful oauth and must be missing something
You can't use the GoogleAuth like that. GoogleAuth provides the basic primitives to handle the OAuth2 protocol. As you're not using the vertx-web part you will need to setup a callback endpoint in your application (I guess it's the /google endpoint you listed) but now you miss the whole Oauth2 handshake. Your client (browser) should call Google, which calls your server to validate the code.
So what you're asking here is to re-implement the vert.x web Oauth2Handler using Spring Boot APIs.
I am trying to connect my users with my back end server , i used the example from the official google sign in plugin for flutter :
https://pub.dartlang.org/packages/google_sign_in
the sign process goes fine and i get the username and email ect..
but i need the id Token to authenticate the user with my server.
Ps: Not using firebase , only google sign in.
Can anyone guide me how to get the id Token ?
You can try using this
_googleSignIn.signIn().then((result){
result.authentication.then((googleKey){
print(googleKey.accessToken);
print(googleKey.idToken);
print(_googleSignIn.currentUser.displayName);
}).catchError((err){
print('inner error');
});
}).catchError((err){
print('error occured');
});
You can get access token and id token more simple like this:
final result = await _googleSignIn.signIn();
final ggAuth = await result.authentication;
print(ggAuth.idToken);
print(ggAuth.accessToken);
Or you also can add it to try-catch to handle an error.
try {
final result = await _googleSignIn.signIn();
final ggAuth = await result.authentication;
print(ggAuth.idToken);
print(ggAuth.accessToken);
} catch (error) {
print(error);
}
or try like this if id token was null, it worked for me.
As the docs point out you need oauth2 client id of your backend to request idToken or serverAuthCode.
from firebase google sigin in authentication copy the Web SDK configuration
add paste in the following to res/values/strings.xml, That should work
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_web_client_id">{Web app Client id goes here}</string>
</resources>
The issue may be related to not using firebase. There is a google-services.json file which is given to you when you register your app in firebase, and you can use that with google_sign_in (this is the default way shown in the documentation).
I was getting null for the token value when trying to implement this without the google-services.json, but successfully signing into google.
If you don't want to use firebase, you have to jump through a couple hoops.
In google cloud console, register your app.
Then make sure you are 'in' your app that you just created in the top drop down menu.
in "apis and services" in the sidebar menu, go through the create Oauth consent screen menu, I don't remember having to fill out many fields, so leave them blank if you don't know what to put in.
then go to the "credentials" menu in the sidebar, and click "Create New Credentials", and select OAuth2 client ID. Make a web client, even though you're trying to use it with an android/ios app.
Make a file android/app/src/main/res/values/strings.xml
using the web client we just made, insert <?xml version="1.0" encoding="utf-8"?> <resources> <string name="default_web_client_id">YOUR WEB CLIENT ID</string> </resources> into the strings.xml file.
[edit] make one more client in the google console for android, and put in your local machine's sha1 key. This step is done for you automatically if you're using firebase. In this case, you have to create both the web client and one for your android device. In production, you'd be using a specific client for your production app.
That should do it I believe, might have missed a step.
I also wanted to verify on my backend that the incoming idtoken was valid, so I had to also make a service account (in the apis and services -> credentials page) and use that in my go server.
I'm still struggling to get this to work with ios, but the android side works great.
To retrieve the Is idToken worked for me:
1. The google-services.json file must be placed in /android/app/
2. you need to add to your /android/app/build.gradle
apply plugin: 'com.google.gms.google-services'
3. and to /android/build.gradle
classpath 'com.google.gms:google-services:4.3.4'
And that's it. GoogleSignIn will return a real idToken instead of null.
font: https://github.com/flutter/flutter/issues/12140#issuecomment-348720774
One more clean way to achieve this:
late Map<String, dynamic> userObject = {};
var res = await _googleSignIn.signIn();
var googleKey = await res!.authentication;
userObject.addAll({
'accessToken': googleKey.accessToken,
'idToken': googleKey.idToken,
'displayName': res.displayName ?? '',
'email': res.email,
'id': res.id,
'avatarUrl': res.photoUrl ?? '',
'serverAuthCode': res.serverAuthCode ?? '',
});
I was struggling with this issue for about a month. Turns out I was getting the same access token, even when the user tried restarting the app. This was painful because my app dealt with scopes and in case a user misses to check one or more scopes in his first sign in, the app wouldn't work at all, even if he/she signs in again and gives the permissions.
Workaround which worked for me: I called the googleSignIn.currentUser.clearAuthCache() method followed by googleSignIn.signInSilently(). This returns a GoogleSignInAccount which can be used for further authentication. My guess is that the clearAuthCache() method clears the token cache and hence a new token is created. This should get you a new access token and let your app make valid calls.
I sincerely request Google developers to solve this issue. For now, this workaround is the only thing that worked.
Try this:
When you create your GoogleSignIn object:
GoogleSignIn(
clientId: "YOUR CLIENT ID"
)
i hope it helps ;)
I use this URL to get id_token:
https://login.microsoftonline.com/common/oauth2/authorize?
response_type=id_token%20code&
client_id=MY_CLIENT_GUID_ID_IN_HERE&
redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fopenid%2Freturn&nonce=alfaYYCTxBK8oypM&
state=6DnAi0%2FICAWaH14e
and this return result like this
http://localhost:3000/auth/openid/return?
code=AAA_code_in_here&
id_token=eyJ0eXAi_xxxx_yyyy_in_here&
state=6DnAi0%2FICAWaH14e&
session_state=xxxx_guid_xxxxx
and then i use the id_token to query Graph (use POST man)
i have see this post InvalidAuthenticationToken and CompactToken issues - Microsoft Graph using PHP Curl but make no sense.
OATH 2.0 requires multiple steps. The first request returns an OAUTH Code. The next step is converting that OATUH code into a Bearer Token. This is the step you are missing here.
I would also recommend using the v2 Endpoint which is a lot easier to work with (particularly with Graph). I wrote a v2 Endpoint Primer that walks through the process and may be helpful as well.
You can't use the token directly, there is one more step to exchange the code you get from the response url into token.
Here is my C# code (using Microsoft.IdentityModel.Clients.ActiveDirectory)
public static AuthenticationResult ExchangeCodeForToken(string InTenantName, string InUserObjId, string InRedirectUri, string InApplicationAzureClientID, string InApplicationAzureClientAppKey)
{
Check.Require(!string.IsNullOrEmpty(InTenantName), "InTenantName must be provided");
Check.Require(!string.IsNullOrEmpty(InUserObjId), "InUserObjId must be provided");
if (CanCompleteSignIn) //redirect from sign-in
{
var clientCredential = new ClientCredential(InApplicationAzureClientID, InApplicationAzureClientAppKey);
var authContext = new AuthenticationContext(Globals.GetLoginAuthority(InTenantName), (TokenCache)new ADALTokenCache(InUserObjId)); //Login Authority is https://login.microsoftonline.com/TenantName
return authContext.AcquireTokenByAuthorizationCode(VerificationCode, new Uri(InRedirectUri), clientCredential, Globals.AZURE_GRAPH_API_RESOURCE_ID); //RESOURCE_ID is "https://graph.microsoft.com/"
}
return null;
}
I had this issue today when I was playing with graph API, the problem in my case was how I was generating the token.
I used postman for generating the token wherein the Auth URL section I was adding the resource = client_id whereas it should be the graph URL. After making that change I was able to make the call via postman.
In order for the above to work, please make sure your application in Azure has delegated permissions to access the Graph API.
To receive the access token and use it for profile requests, you don't need anything from server-side, you can implement the oAuth2 just from the client side.
Use the following URL for login:
https://login.microsoftonline.com/common/oauth2/authorize?client_id=YOUR_CLIENT_ID&resource=https://graph.microsoft.com&response_type=token&redirect_uri=YOUR_REDIRECT_URI&scope=User.ReadBasic.All
After successful login, user will redirected to the page with access_token parameter. Then use the following AJAX call to fetch user info:
var token = login_window.location.href.split('access_token=').pop().split('&')[0];
$.ajax({
url: "https://graph.microsoft.com/v1.0/me",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer '+token);},
success: function(data) {
alert('Hi '+data.displayName);
console.log(data);
}
});
Note that you may need to enable oauth2AllowImplicitFlow:true setting from your Azure Active Directory application manifest file.
Set "oauth2AllowImplicitFlow": false to "oauth2AllowImplicitFlow": true.
Lastly, ensure that your app has required permissions for Microsoft Graph which are sign in users and View users' basic profile
An updated answer to get access with new applications:
Register your app in the app registration portal.
Authorization request example:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=offline_access%20user.read%20mail.read&state=12345
Authorization response will look like this:
https://localhost/myapp/?code=M0ab92efe-b6fd-df08-87dc-2c6500a7f84d&state=12345
Get a token
POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=user.read%20mail.read
&code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&grant_type=authorization_code
&client_secret=JqQX2PNo9bpM0uEihUPzyrh // NOTE: Only required for web apps
Use the access token to call Microsoft Graph
GET https://graph.microsoft.com/v1.0/me
Authorization: Bearer eyJ0eXAiO ... 0X2tnSQLEANnSPHY0gKcgw
Host: graph.microsoft.com
Source:
https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph/api/1.0
You can also get an access token without a user, see here:
https://learn.microsoft.com/en-us/graph/auth-v2-service
I have get access token and when I try to post rtm.start, I am getting below error:
{
error = "missing_scope";
needed = client;
ok = 0;
provided = "identify,read,post";
}
I have set the scope to read,post,identify in authorize API. I have read the API document over and over again. Only rtm.start mentioned client scope. But in oauth document I didn't find a client scope. So, what's wrong?
You have to do it before you get the token.
when you do the initial request to connect the app, include &scope="identify,read,post,client"
Under App Credentials get your Client ID and Client Secret.
Goto:
https://#{team}.slack.com/oauth/authorize?client_id=#{cid}&scope=client
replacing #{team} and #{cid} with your values.
When you approve the authorization you’ll goto that real url that doesn’t resolve. Copy the whole url to your clipboard and paste it into a text file. Extract out just the “code” part.
Now goto:
https://#{team}.slack.com/api/oauth.access?client_id=#{cid}&client_secret=#{cs}&code=#{code}"
And you’ll get back a token like:
xoxp-4422442222–3111111111–11111111118–11aeea211e
(from here: https://medium.com/#andrewarrow/how-to-get-slack-api-tokens-with-client-scope-e311856ebe9)
I am working on google Adwords API to upgrade our code for migration from v201302 to v201309.
Any one can suggest me, what code we should use in place of following code ( as ClientLoginTokens now deprecated).
String clientLoginToken = new ClientLoginTokens.Builder()
.forApi(ClientLoginTokens.Api.ADWORDS)
.withEmailAndPassword(configurations.get("email"), configurations.get("password"))
.build()
.requestToken();
Here are the steps that I took to get OAuth2 working. YMMV of course...
Step 1 - Register Application with Google Console API
Log into Google using your email and password above
Head to the Google API Console. You probably get redirected to Google Cloud Console
Under 'APIs & Auth' click on 'Consent screen'. Fill in at least 'Product Name' and 'Email'.
Under 'APIs & Auth' click on 'Registered apps'.
Click 'Register App'. Fill in details ensuring that you select 'Native' as platform.
Under 'OAuth 2.0 Client ID' make a note of the CLIENT ID and CLIENT SECRET values.
Step 2 - Generate Refresh Token
Next step is to generate a refresh token. This is a generate-once-use-multiple-times token that allows your application to obtain new access tokens:
Download GetRefreshToken.java.
Create an aps.properties file to be referenced by the GoogleClientSecretsBuilder()
.forApi(Api.ADWORDS) call. This ads.properties file should contain two lines:
api.adwords.clientId=client-id-from-step1.6
api.adwords.clientSecret=client-secret-from-step1.6
Using web browser log into the Google AdWords MCC.
Run GetRefreshToken.java and follow instructions i.e. copy browser URL into browser, enter code returned into console etc. etc.
You should now have a refreshToken. Copy this refresh token into your ads.properties files like this:
api.adwords.refreshToken=your-refresh-token
PS GetRefreshToken.java has a couple of dependencies. If you are using Maven then here they are (adjust versions accordingly!):
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-oauth2</artifactId>
<version>v2-rev50-1.17.0-rc</version>
</dependency>
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>adwords-axis</artifactId>
<version>1.20.0</version>
</dependency>
Step 3 - Generate Credential
With your refreshToken, clientId & clientSecret in your ads.properties you can now generate a Credential like this:
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.ADWORDS)
.fromFile()
.build()
.generateCredential();
Step 4 - Get AdWords Session
The final step (hats off to you if you have got this far!) is to create an AdWords Session using the oAuth2Credential instance of Credential that you created in Step 3. You can do this by adding two more things into your ads.properties file:
api.adwords.developerToken=developer-token-from-mcc
api.adwords.clientCustomerId=client-id-of-adwords-account-that-you-want-to-access
Then get an AdWords session up using like this:
AdWordsSession awSession =
new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
Step 5 - Grab a coffee and reflect on how easy it is to access the Google AdWords API using OAuth2
This step is entirely optional.
You can not transform your old process identical as before. There are some examples in the Migration Guide from Google. See the Authentication/OAuth 2.0 section:
If you are coming from using ClientLogin, we've added a few features to make it extremely easy to switch over.
Once you've generated a refresh token using the GetRefreshToken.java example of your examples download, and you've copied it into your ads.properties file, you'll be able to create a refreshable token with the OfflineCredentials utility.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
Once authorized, you can set the Credential object into the builder or session:
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
OAuth2 will now be used when making API calls.
You might change Api.DFP to Api.ADWORDS. OAuth 2.0 at Google is fully covered in the Using OAuth 2.0 for Login article.