Microsoft Graph /me not working for Personal Account - java

I am working on implementing OneDrive APIs,though for developer account able to get user detail but while trying login through personal account or other account rather developer account,I am getting following response :
protocol=http/1.1,
code=401,
message=Unauthorized,
url=https://graph.microsoft.com/v1.0/me
I have given all of the Application as well as Delegated permissions in the Azure developer console.
Permissions that were set in Azure developer console:
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url("graph.microsoft.com/v1.0/me")
.addHeader("Authorization", "Bearer " + accessToken)
.build();
try {
response = okHttpClient.newCall(request).execute();
Log.e(LOG_TAG, response.toString()); // Do something with the response.
}
catch (IOException e) {
e.printStackTrace();
}
return response;

We have a good quick start and a 30 min walk through tutorial here that would be useful to walk through to understand the permissions side and delegated authentication
https://developer.microsoft.com/en-us/graph/get-started/android
For a user delegated flow, you do not need the application permissions you have consented there. To authenticate /me you only require User.Read as per docs
https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
You can use https://jwt.ms/ and take the access token to validate that the scope is in the token too.

Related

Trying to call Microsoft Graph API in Java after retrieving Access token from Angular app

I have tried to follow some of the examples online, but they are not very helpful and the official Microsoft documentation can be somewhat confusing and all over the place.
I have the token, which includes the nonce in the header.
I have added in the Microsoft Graph dependency in my pom.xml file and everything is set up, but I am not sure how to actually implement the method using the access token and make the calle to get a the signed in user info for example.
https://graph.microsoft.com/v1.0/me
I have set up my app in Azure already and added in the API permissions.
any help or guidance in the right direction would be helpful.
You could refer to the example of signed-in user request, see here.
IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
// for "/me" endpoint
User user = graphClient.me().buildRequest().get();
// for "/users/{id | userPrincipalName}" endpoint
// User user = graphClient.users("{id}").buildRequest().get()
Get authProvider with accessToken, refer to this article:
public IGraphServiceClient getAuthProvider() {
IAuthenticationProvider mAuthenticationProvider;
try {
String accessToken = "xxxxxxxxxxxxx";
mAuthenticationProvider = request -> request.addHeader("Authorization", "Bearer " + accessToken);
} catch (Exception e) {
throw new Error("Could not create a graph client: " + e.getLocalizedMessage());
}
return GraphServiceClient.builder()
.authenticationProvider(mAuthenticationProvider)
.buildClient();
}
For more information, Make API calls using the Microsoft Graph SDKs with Java.

How to send GET request with google OAuth2 and Java to script.google.com web page?

GET is working for me but I get google services authorization page when I send it. I read guides from google but still don't understand how to use Credentials right.
This thing is for managing script files itself and have nothing to do with my problem :/
Would be decent if it is possible in Java
After sign in google you will be redirected on redirect page with google code. Redirect page could be set in google private user console. When you will get google code you could use code for obtaining jwt with GoogleAuthorizationCodeFlow
for example
GoogleAuthorizationCodeTokenRequest googleAuthorizationCodeTokenRequest = codeFlow.newTokenRequest(code)
.setRedirectUri(redirectUrl);
try {
GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeTokenRequest.execute();
} catch (IOException e) {
throw new ExternalAuthenticationException("Invalid google 'code' parameter (disposable)");
}

400 Bad Request when refreshing token via Gmail Java API

Hi I'm trying to implement sending/receiving email using Google's gmail api on my server:
private GoogleCredential authorize(HttpTransport httpTransport, JsonFactory jsonFactory ) {
try{
Resource resource = new ClassPathResource("my_key_in_json_format.");
InputStream input = resource.getInputStream();
GoogleCredential credential = GoogleCredential.fromStream(input);
credential.createScoped(GmailScopes.all());
credential.refreshToken();
return credential;
}catch(IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
But I'm getting the following exception when the credential tries to refresh token:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_scope",
"error_description" : "Bad Request"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:394)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:493)
at com.snobo.util.GmailService.authorize(GmailService.java:79)
I've tried changing the scope parameters to:
Collection<String> SCOPES = Collections.unmodifiableCollection(Arrays.asList(new String[]{GmailScopes.GMAIL_READONLY}));
And it also failed the same when refreshing token. Google's online document is not really Java friendly. Anyone run into similar issues?
I found the answer to my problem based on this thread after searching around:
400 Bad Request on Gmail API with php
"You should not be using a service account if you just want to access one account (your own). Service accounts are their own account and they're not Gmail accounts. They work well for APIs that don't need a user (e.g. maps, search) or when you are using a Google Apps for Work domain and want delegation enabled for all users in the domain (by domain admin, so you don't need individual user authorization)."
I have modified my implementation to use oauth web flow now. I'm really disappointed on Google's documentation as this matter should be addressed outright and as concise as possible. I'm sure "Service Account" and "domain wide delegation" mis-led many developers to use the Service Account approach for many types of personal/individual account application.

Google Drive API Authentication - how to do it and how to implement it?

I'm trying to get the title of a document using the file ID. Here's the code:
private static void printFile(Drive service, String fileId) {
try {
File file = service.files().get(fileId).execute();
System.out.println("Title: " + file.getTitle());
} catch (IOException e) {
System.out.println("An error occured: " + e);
}
}
}
However, when I run it I receive a 403 forbidden error that states, "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
I assume that I have to authenticate, but seeing as I'm completely new to Google Drive API and also java, I'm confused as to how to do this (forgive me). I found this webpage: https://developers.google.com/drive/web/auth/web-server which explains how to authenticate but I'm still confused. The page lists multiple classes that do thing such as exchange the authorization code for an access token and use OAuth 2.0 credentials.
My question is do I need to use all of these classes to authenticate? And how do I implement them into my code?
Here is a brief explanation at the http level.
Any Google Drive REST API call requires an http Authorization: Bearer xxxxxx to be set. If there is no such header, you'll get the 403 you're experiencing
The xxxxx is an access token. There are a myriad ways to get one of these depending on the user experience you want to implement and whether you're trying to access the user's Drive files or the application's. Read the Google docs and experiment with the OAuth Playground.
The Google Java library attempts to abstract all of the above. Whether it does a good job or not is for you to decide. Personally I've had more success calling the REST API directly.

how to get access token using gdata in java

I am developing a Java Application where I am implementing 3-legged OAuth using google gdata in Java. This application is registered on Google App Engine. At the first stage, I am getting the unauthorized request-token successfully. I am storing that token in session and create a link using createUserAuthorizationUrl(oauthParameters). Then on clicking the link, it redirect me to "Grant Access Page".
Now, even though I grant access, it doesn't show me this page. But, it redirects me to my callback url. However, this seems proper. But, it also doesn't add the entry under My Account. Here, I am storing the oauth_token in session.
When getting redirected, the url of that page contains oauth_token & oauth_verifier, both ! Now, on this callback url, I have a submit button & set action of for to an accessTokenServlet.java. The code of this servlet is as follow :
Now I am sending request to fetch Access Token. My code is :
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthParameters.setOAuthToken(request.getSession().getAttribute("oauth_token").toString());
oauthParameters.setOAuthTokenSecret(request.getSession().getAttribute("oauth_token_secret").toString());
try {
String accessToken = oauthHelper.getAccessToken(oauthParameters);
out.println("Access Token : " + accessToken);
} catch (OAuthException e) {
//System.out.print("Response Status : " + response.getStatus());
out.println("Exception : ");
e.printStackTrace();
return;
}
While clicking on submit button, it prints "Access Token : " & nothing ! No token returns !
I am getting wrong at the stage of authorizing the request token itself. But, I am not getting, what problem got generated ?
The page with the verifier you linked to should only happen if you pass in an oauth_callback of oob — this indicates that you will be moving the verifier out-of-band. I strongly recommend against using oob for anything but debugging. Instead, you should be setting a callback URL and getting the verifier out of the query string.
In the code above, I don't see anything that sets the verifier in the OAuth parameters, so that's likely your problem. You're also not doing much in the way of error handling, and that's a really important piece of the OAuth flow — for example, once you've got it working, try canceling the OAuth process and see how your application handles it.
You will only see the entry in your issued tokens list after you've fully completed the process and obtained an upgraded access token.

Categories