What URL do I use to send users to google oauth2 consent screen - google-api

I am trying to write a simple application to access google's api using user authentication tokens and html requests, however I am struggling to find what URL I send users too in order for them to select a profile and sign in.

URL I send users too in order for them to select a profile and sign in.
The thing is you are confusing authorization and authentication. Oauth2 a user can authorize you to access their data, it has nothing to do with logging in to your application that's OpenID connect.
However what you are probably looking for is the oauth2 consent screen This is the screen where the user consents to your application accessing their data.
https://accounts.google.com/o/oauth2/auth?client_id={clientid}&redirect_uri={redirectURI}&scope={scope}&response_type=code
Remember this is only the first step if they consent then you will be given an authorization code your application must then exchange the authorization code for an access token which you can use to access the api.
You may find this video helpful in understanding the fill Oauth2 dance. Understanding Google OAuth 2.0 with curl
If you are looking to login a user and check their profile something like this would be better
[GoogleScopedAuthorize(PeopleServiceService.ScopeConstants.UserinfoProfile)]
public async Task UserProfile([FromServices] IGoogleAuthProvider auth)
{
var cred = await auth.GetCredentialAsync();
var service = new PeopleServiceService(new BaseClientService.Initializer()
{
HttpClientInitializer = cred
});
var request = service.People.Get("people/me");
request.PersonFields = "names";
var person = await request.ExecuteAsync();
return View(person);
}
The full tutorial and companion video can be found here Asp .net core 3 and Google login

Related

Google Social Login with Auth0 Tokens for [Authorized] API Calls

Anyone here implemented social login through Google for Auth0? I have an issue with the tokens (access and id) being returned after validating with Google.
Here's my code:
var waGoogle = new auth0.WebAuth({
domain: 'testApplication.auth0.com',
clientID: '************',
redirectUri: 'http://localhost:8080/'
})
waGoogle.authorize({
connection: 'google-oauth2',
responseType: 'id_token token'
}, function(err, authResult){
if(err){
console.log('Google Login Error')
console.log(err)
}
});
Google screen shows up, I log in and I am redirected back to my application. From the application, I parse the URL so that I can get the access and id tokens.
let getParameterByName = (name) => {
var match = RegExp('[#&]' + name + '=([^&]*)').exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var access_token = getParameterByName('access_token')
var id_token = getParameterByName('id_token')
Issue I am having is that none of the tokens allow me to call my APIs (asp.net web api) which are decorated with the [Authorize] attribute. It returns a:
401 (Unauthorized)
I know that my API is working, as using the normal
Username-Password-Authentication
method where I also obtain an access token, my api calls are just pulling through.
Are there any next steps which I need to do after obtaining the access and id_token from Google? Do I need to make an additional call to Auth0 to obtain the proper access token to be able to call my web api?
Thanks.
The token you are looking for is called an IdP (Identity Provider) Token. This is different from the one issued to you after logging in. There are pretty good instructions on the Auth0 site that walk you through the process of getting that token.
Here is the overview of IdP tokens
Here is a step-by-step guide to calling the Identity Provider
The tl;dr:
To access the IdP token you need to call the Auth0 management API from your server. For that, your server will need a management token. Then use that token to access the endpoint /api/v2/users/[USER_ID]. In the object sent back from Auth0, look for the google identity and extract that token.
Also note, you should probably keep that token on your server if you can. If you can keep those power tokens away from your client your users will be happy.

Google APIs for Web sign in and query user data

I'm trying to implement a process which combines Google sign-in on client side (Web page) with server side verification and query user data (Java server).
What I did:
In Google developer console, added an OAuth 2.0 client IDs credential.
Implemented the sign-in on the web page and got the ID token after successful login.
Implemented the authentication with a backend server as explained here:
https://developers.google.com/identity/sign-in/web/backend-auth. This part also works and I can verify the authentication and get the user's e-mail address.
What I need to do now is getting the user's profile information, i.e. first and last name and access the app folder, to store relevant application data.
This is my server side code. I marked the part where I need help:
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(HTTP_TRANSPORT, JSON_FACTORY)
.setAudience(Arrays.asList(service.getClientId()))
.build();
GoogleIdToken idToken = null;
try {
idToken = verifier.verify(token); // token is the ID token received from the client
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (idToken != null) {
GoogleIdToken.Payload payload = idToken.getPayload();
payload.getEmail() <== This works
/*
Here I need to query Google API per the available application scopes: profile, app storage etc.
*/
}
Is it possible to use the API at this stage? If not, can I request access token here? Should I use the Client ID or do I need a different type of credential (like API key or Service account)?
ID Token represents authentication, not authorization. So you won't be able to access Google APIs just with ID Token.
In order to make requests to Google APIs from server side, do following on client side.
var auth2 = gapi.auth2.getAuthInstance();
auth2.grantOfflineAccess({
scope: 'SCOPES_COMES_HERE'
}).then(function(resp) {
// send `resp.code` to server to exchange it with
// credentials (access_token, refresh_token
});
The code is the key to exchange with access_token.
You might be inclined to implement authentication and authorization at the same time, but Google's recommendation is to separate them and request permissions as they are needed (incremental authorization). Leave the current code and add above + server side that handles code to exchange with access_token.
Detailed doc: https://developers.google.com/identity/sign-in/web/server-side-flow

WP7 C# Retrieve access tokens of Google OAuth 2.0 request

I followed this guide to use Google OAuth 2.0 authorization, but I can't understand how to implement request to retrieve access and refresh token in my Application. The code, as that guide say, is the current:
// Request an access token
OAuthAuthorization authorization = new OAuthAuthorization(
"https://accounts.google.com/o/oauth2/auth",
"https://accounts.google.com/o/oauth2/token");
TokenPair tokenPair = await authorization.Authorize(
ClientId,
ClientSecret,
new string[] {GoogleScopes.CloudPrint, GoogleScopes.Gmail});
// Request a new access token using the refresh token (when the access token was expired)
TokenPair refreshTokenPair = await authorization.RefreshAccessToken(
ClientId,
ClientSecret,
tokenPair.RefreshToken);
Where and how can I call this function in a generic Windows Phone application?
(Sorry if there this question it's duplicate, but I try to search and I only find as answers links to generic Google Apis guide)
You call it when it's necessary (when you need to get tokens). After that use official Google libraries to get access to API and provide them data from TokenPair. Plus, remember to get this (https://github.com/pieterderycke/MobileOAuth/blob/master/MobileOAuth/GoogleScopes.cs) in your project, so you can use GoogleScopes.

How to reset google oauth 2.0 authorization?

I'm using Google APIs Client Library for JavaScript (Beta) to authorize user google account on web application (for youtube manipulations). Everything works fine, but i have no idea how to "logout" user from my application, i.e. reset access tokens.
For example, following code checks user authorization and if not, shows popup window for user to log into account and permit web-application access to user data:
gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: false}, handleAuth);
But client library doesn't have methods to reset authorization.
There is workaround to redirect user to "accounts.google.com/logout", but this
approach is not that i need: thus we logging user off from google account not only from my application, but also anywhere.
Google faq and client library description neither helpful.
Try revoking an access token, that should revoke the actual grant so auto-approvals will stop working. I assume this will solve your issue.
https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke
Its very simple. Just revoke the access.
void RevokeAcess()
{
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
org.apache.http.HttpResponse response = client.execute(post);
}
catch(IOException e)
{
}
}
But it should be in asyncTask
It depends what you mean by resetting authorization. I could think of a three ways of doing this:
Remove authorization on the server
Go to myaccount.google.com/permissions, find your app and remove it. The next time you try to sign in you have to complete full authorization flow with account chooser and consent screen.
Sign out on the client
gapi.auth2.getAuthInstance().signOut();
In this way Google authorization server still remembers your app and the authorization token remains in browser storage.
Sign out and disconnect
gapi.auth2.getAuthInstance().signOut();
gapi.auth2.getAuthInstance().disconnect();
This is equivalent to (1) but on the client.
Simply use: gapi.auth.setToken(null);
Solution for dotnet, call below API and pass the access token, doc - https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke
string url = "https://accounts.google.com/o/oauth2/revoke?token=" + profileToken.ProfileAccessToken;
RestClient client = new RestClient(url);
var req = new RestRequest(Method.POST);
IRestResponse resp = client.Execute(req);

Spring Social Twitter Oauth

I want to use spring social to develop an twitter app which will update status and upload photos.I am not able to understand how to do Oauth authentication using Spring social.All examples I saw talks about hardcoding the accesstoken which would work only for that particular user.I dont want to hardcode anything except the app keys.
Kindly some one explain me how to do Twitter Oauth using spring social.I went through the official documentation of spring framework but got confused when I saw the other examples..
Thanks
I saw talks about hardcoding the accesstoken which would work only for that particular user.I dont want to hardcode anything except the app keys.
"app keys" a.k.a. consumer { key, secret } pair authorizes your app to use Twitter APIs that do not require user authentication. Think about it as you app browsing a twitter website without being logged in. Hence you'd have an ability to search, get timelines, etc.. => read only.
In case you'd like to post something back, you'd have to make you app do that on behalf of a real Twitter account / user. Think about someone writing a Twitter client => it can be downloaded by many different users, hence it needs two things to function properly:
Be a registered Twitter application => have consumer { key, secret } pair
Be able to post tweets / images on behalf of the user => have access { token, secret } pair
In order to get that access { token, secret } pair, you'd have to have an "OK" from that user/account.
That is where OAuth comes in => it sends the user to the confirmation page, where he clicks "OK, I allow this app to post on my behalf". This "OK" then gets converted to the OAuthToken that your app can use.
If all you want is to post updates on behalf of yourself, then you need to approve your own Twitter app, and persist that OAuthToken to be used by your app.
Unfortunately Twitter does not yet support OAuth 2.0, hence you'd have to do more... You'd have to do OAuth 1.0a.
Spring Social documentation describes the OAuth 1.0a flow here, where you can see the flow visually.
On order to "code" this flow using Spring Social APIs, you should first request access {token, value} pair ( there is a convenience ConnectController for it btw ):
TwitterConnectionFactory connectionFactory =
new TwitterConnectionFactory( "consumerKey", "consumerSecret" );
OAuth1Operations oauthOperations = connectionFactory.getOAuthOperations();
OAuthToken requestToken = oauthOperations.fetchRequestToken( "https://my-callback-url", null );
String authorizeUrl = oauthOperations.buildAuthorizeUrl( requestToken, OAuth1Parameters.NONE );
response.sendRedirect( authorizeUrl );
And once it comes back (to your callback URL) you can use OAuth1Operations to get OAuthToken which is exactly that pair.
// upon receiving the callback from the provider:
OAuthToken accessToken = oauthOperations.exchangeForAccessToken(
new AuthorizedRequestToken(requestToken, oauthVerifier), null);
Now, as you have all you need, you have choices:
Create a TwitterTemplate from that OAuthToken:
String consumerKey = "..."; // The application's consumer key
String consumerSecret = "..."; // The application's consumer secret
String accessToken = accessToken.getValue();
String accessTokenSecret = accessToken.getSecret();
Twitter twitter = new TwitterTemplate( consumerKey, consumerSecret, accessToken, accessTokenSecret );
Create a Twitter Connection object
Connection<Twitter> connection = connectionFactory.createConnection( accessToken );
Once you get the Connection, you might want to persist it via ConnectionRepository as shown here, so you don't have to go through obtaining access token again.
Here is Connection API.
The previous answer is good, but is only part of the story...
There are at least 3 levels at which you may work with Spring Social: (1) Using the TwitterTemplate directly, in which case you'd need to obtain the access token and secret through some means of your own, (2) use OAuth1Template, perhaps through TwitterConnectionFactory as the previous answer showed, to get the access token and from that create the TwitterTemplate, in which case you'd have to handle the redirects and callbacks yourself or (3) use Spring Social's ConnectController to handle everything for you.
Using ConnectController involves the least amount of OAuth work on your part. You just configure the appropriate pieces in Spring and ConnectController takes care of the rest. See http://static.springsource.org/spring-social/docs/1.0.x/reference/html/connecting.html for details.
I encourage you to have a look at the Spring Social Showcase sample at https://github.com/SpringSource/spring-social-samples. It uses ConnectController to handle by Twitter and Facebook connections. And, of course, you're welcome to ask questions on the Spring Social forum at http://forum.springsource.org/forumdisplay.php?82-Social.

Resources