I have been following https://github.com/microsoftgraph/msgraph-sdk-java project for getting all the mails using Microsoft Graph API. This project works fine based on my changed configuration.
However, this follows OAuth authentication and I have to configure redirect url, and while running project, I got authentication code as query param on given url.
I stuck at two points :
How to by pass redirect_url concept, since my application is going to run in background. so, is there any way, I can auto capture this authentication code?
By trading authentication code, I receive access_token having 3600 expiry using below method.
OAuth2AccessToken mAccessToken = mOAuthService.getAccessToken(authCodeFromURL);
In above object, receiving below JSON, which does not have refresh token.
{
"token_type": "Bearer",
"scope": "Files.ReadWrite openid User.Read Mail.Send Mail.ReadWrite",
"expires_in": 3600,
"ext_expires_in": 3600,
"access_token": "encryptedCode",
"id_token": "encryptedCode"
}
I have tried to get the new access token with below method from SDK by using id_token, but it is not working, gives me invalid.
OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(idToken);
Invalid JSON :
{
"error": "invalid_grant",
"error_description": "AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID: 03690b71-4056\r\nCorrelation ID: b70a7b7b-963b-4cd6\r\nTimestamp: 2019-05-22 08:24:33Z",
"error_codes": [9002313],
"timestamp": "2019-05-22 08:24:33Z",
"trace_id": "03690b71-4056-49b9",
"correlation_id": "b70a7b7b-963b-4cd6"
}
What is id_token?
How can I refresh this access_token? Or Is there any other way/method to do it?
Kindly note, I am looking for solution with Java SDK.
Related
I'm making a Java application to send Mail as any user in a Microsoft tenant, with Graph APIs, so I'm using the client credentials flow (no login, automatic send).
I've registered an app in Azure AD giving the following application permissions (not delegated), checking out the admin consent for every item:
Mail.Send
Mail.ReadWrite
User.Read.All
For semplicity, I've tried also with calls in Postman, but I have the same issue as in the Java app. I take for granted that I have got a valid access token (If I try with an invalid one, I get a 401: Unauthorized). The following is the decoded access token that I get from https://jwt.ms/, with all the scopes included:
...
"roles": [
"Mail.ReadWrite",
"User.Read.All",
"Mail.Send"
],
...
This is my code in Java:
String user = "/users/<my user id or my user principal name>";
UserRequestBuilder defaultUser = new UserRequestBuilder(graphClient.getServiceRoot() + user, graphClient, null);
//graphClient.me()
defaultUser
.sendMail(UserSendMailParameterSet
.newBuilder()
.withMessage(message)
.withSaveToSentItems(saveToSentItems)
.build())
.buildRequest()
.post();
I can't use the "me" target (me() method) because this is client credentials flow, so there isn't a logged user. I need to specify the sender in this way: /users/{id | userPrincipalName}/sendMail.
This is how the call in Postman is composed:
Method: POST
URL:
.https://graph.microsoft.com/v1.0/users/{my user id or my user principal name}/sendMail
AUTHORIZATION:
Bearer Token (my access token)
HEADERS:
Content-Type: application/json
BODY(JSON):
{
"recipient": <recipient email>,
"subject": "This is a test mail",
"from": <mail that created the tenant, app and access token>,
"text": "This is the messge body..."
}
That's the response from the server (in both Postman and Java app):
STATUS: 405: Method Not Allowed
BODY:
{
"error": {
"code": "Request_BadRequest",
"message": "Specified HTTP method is not allowed for the request target.",
"innerError": {
"date": "2022-08-05T07:17:34",
"request-id": "XXXXXXXX-6075-4d13-83ed-XXXXXXXXXXXX",
"client-request-id": "XXXXXXXX-6075-4d13-83ed-XXXXXXXXXXXX"
}
}
}
Note 1:
I got my user id and my user principal name also with a Postman call using my access token,
exploiting the User.Read.All permission, with the following call:
https://graph.microsoft.com/v1.0/users
That's the response:
...
"userPrincipalName": "XXXXXX_XXXXXX.XXX#EXT##sendClientCredMail.onmicrosoft.com",
"id": "XXXXXXXX-4457-4944-bb22-XXXXXXXXXXXX"
}
]
}
Note 2:
Note that if I use the "principal name" in the call, I get a 405, if I use the "id" instead I get a 404: Not Found
Thanks in advance for any help, I've been trying for hours!
SOLVED
As Optimal said in the comments, the issue was that the user didn't have a licensed mailbox.
When I assigned a "Microsoft 365 Business Premium" license to that user, my code worked fine.
Check the licenses both on portal.azure.com for assignments, and on admin.microsoft.com for the active mailbox
Kind regards
What I'm trying to do is create a simple Microsoft Azure app that fetches all the contacts with Microsoft Graph. I THINK I understand how it should work, but seeing as I fail to actually make it work, I need some help.
I managed to fetch user data same as documented on their documentation site, but when following similar steps for contacts, I keep getting NoPermissionsInAccessToken.
My general workflow is to retrieve a token using:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
?client_id={clientId}
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fdetail
&response_mode=query
&scope=openid+offline_access+profile+user.read+Mail.ReadWrite+Contacts.ReadWrite
With this I have acquired authorization code, refresh token and such. Now I plug that token into AuthorizationCodeProvider same as provided in example:
AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(
clientId,
Arrays.asList("openid", "offline_access", "profile", "user.read", "Mail.ReadWrite", "Contacts.ReadWrite"),
code,
"http://localhost:8080/detail",
NationalCloud.Global,
tenant,
secret);
IGraphServiceClient graphClient = GraphServiceClient
.builder()
.authenticationProvider(authProvider)
.buildClient();
IContactCollectionPage contacts = graphClient.me().contacts()
.buildRequest()
.get();
But when the application tries to execute get() from the last function it throws the following:
401 : Unauthorized
Strict-Transport-Security : max-age=31536000
Cache-Control : private
x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"West Europe","Slice":"SliceC","Ring":"5","ScaleUnit":"000","RoleInstance":"AGSFE_IN_53"}}
client-request-id : e393d9d1-1eae-44b2-9956-2b97c0105b42
request-id : fecedee8-8b69-44b1-b300-5c9f71d3c427
Content-Length : 284
Date : Thu, 13 Feb 2020 13:12:27 GMT
Content-Type : application/json
{
"error": {
"code": "NoPermissionsInAccessToken",
"message": "The token contains no permissions, or permissions can not be understood.",
"innerError": {
"request-id": "fecedee8-8b69-44b1-b300-5c9f71d3c427",
"date": "2020-02-13T13:12:27"
}
}
}
As far as I know I have given the application all the necessary grants through portal.azure.com. Went to app registration, my application, API permissions, and added delegated Contacts.ReadWrite permission that is documented to be necessary.
Any idea what I can do to make this thing work?
When you call https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize it is returning an Authorization Code, not an Access Token. You need to exchange that Auth Code for an Access Token via https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token.
You can find step-by-step instructions for retrieving a token in the documentation.
Your app uses the authorization code received in the previous step to request an access token by sending a POST request to the /token endpoint.
I am using FusionAuth for authentication. I have created one application in the FusionAuth. It has oAuth configured.
http://localhost:9011/oauth2/authorize?access_type=offline&prompt=consent&response_type=code&client_id=9ecc54b7-6f79-4105-a208-ca61e6157b58&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fipos%2Frest%2FfusionAuth%2FcallBack
This is my authorization url to one the FusionAuth login page.
Once I hit the link and enter the user name and password, I get the call back on configured call back url in my java jersey api.
I get the following details in the call back request.
code - dZgq5Xd0YmAQXZ2JIzkih832iojimgLUPwT7yoH9-TY
locale - en_US
userState - AuthenticatedNotRegistered
Here I am using Scribe Java library for OAuth authentication
I make call to get the access token call usnig the Scribe java libary with the given authorization code and grant_type is authorization_code.
Here this call get success and I get the below detail in the response.
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImRRZTA1Uk1vN19oVjZUUnpLVUQ1aXpRU2NSOCJ9.eyJhdWQiOiI5ZWNjNTRiNy02Zjc5LTQxMDUtYTIwOC1jYTYxZTYxNTdiNTgiLCJleHAiOjE1Nzc3MTg0NjgsImlhdCI6MTU3NzcxODM0OCwiaXNzIjoiYWNtZS5jb20iLCJzdWIiOiI3ZWE3OWRhZi1hZjExLTQ1MTUtODljYS1iOGFjYTFjN2I5YTEiLCJhdXRoZW50aWNhdGlvblR5cGUiOiJQQVNTV09SRCIsImVtYWlsIjoiZGhhdmFsYmhvb3Q5M0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiZGhhdmFsYmhvb3QifQ.eA0Xi6nEZhWaTMd-P26ESdE3NsyXNRNVBKBdBvHxvzfHgXYJiN2pf-16mY8JK-4-1g3vZF7Cwv-SkP4iZAIJCYYc3uBW8Qlcjjn9cyi7_RggBBBsErcs2acRIt-D5NpnVJfkxHwGAs9fO6a2Win98GGYyv1nzBG9OhWkyZJTy4QxzlgXNrkQIzTuzRwLkRFzKCT95pqfsOYb_MXPuAksg5q1SHIj8qtbO7EO-vMbpmiok1C-Wflbiq2X_tq17QBKbO4JAMLm9_pCZse1tqLyNP4fIh3VHTz7OdbbXvug2Tpk_yTWLVL_29XC87-91R5iXeezLjADkdi1yXMUdHioOw",
"expires_in": 119,
"token_type": "Bearer",
"userId": "7ea79daf-af11-4515-89ca-b8aca1c7b9a1"
}
Here, I do not get the refresh_token, in any case, user first time login or in any case.
This is JWT token and I had reduced the expiry time to 120 seconds.
In application OAuth setup I enable Generate refresh tokens option.
The only problem here I have is, I do not receive the refresh token.
Help me with this.
Thank you.
To obtain a Refresh Token as a result of the Authorization Code Grant, you'll need to request the offline_access scope.
https://fusionauth.io/docs/v1/tech/oauth/endpoints#authorization-code-grant-request
You can modify your request as follows (line breaks added for readability)
http://localhost:9011/oauth2/authorize?
scope=offline_access
&prompt=consent
&response_type=code
&client_id=9ecc54b7-6f79-4105-a208-ca61e6157b58
&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fipos%2Frest%2FfusionAuth%2FcallBack
As a side note, adding prompt=consent is fine, but it will not affect the request as this is not yet available in FusionAuth. Please upvote the feature request if this is something you'd like to see in an upcoming release. https://github.com/FusionAuth/fusionauth-issues/issues/411
I am testing the Microsoft Graph beta endpoint that sends invitations to guest users to join the tenant. The endpoint I am using is :
https://graph.microsoft.com/beta/invitations
Body:
{
"invitedUserEmailAddress": "abc#xyz.com",
"inviteRedirectUrl": "https://myDomain"
}
I am passing the bearer token in Authorization header that I got for the local admin user through the ADAL4J api. However, this call gives me a 401 Unauthorized error. Following is the response:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "91f8129e-70cc-467d-a45b-9309e55788d6",
"date": "2017-02-10T08:46:09"
}
}
}
Any clue on how to get this request working? On Github I have gone through other discussions(eg) where users are facing the same issue.
The token sent was obtained with resource as "https://graph.windows.net". The expected resource/audience for Microsoft Graph API is "https://graph.microsoft.com". Update your application manifest to include Microsoft Graph as a resource and request the required permissions. Then request token with above mentioned resource/audience.
I am excatly in the same situation as #adarsh hegde. But I am targetting an azure B2C instead.
I can get the token for the windows graph (using resource "https://graph.windows.net"), and I am able to create users whithin my web app that is registered with the right permission.
What I did is to acquire token for graph.microsoft.com on the same time, but this token doesn't let me use invitations giving me the same error as you :
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "91f8129e-70cc-467d-a45b-9309e55788d6",
"date": "2017-02-10T08:46:09"
}
}
}
UPDATE:
So here are the steps that I've done so far:
ADB2C directroy
Web app with OpenID registered in there with required permissions to manage users in the AD following this link
When admin is logged in, the Web app in trusted mode is able to let him manage users (create/add/etc...)
Now what I want to use is the InvitationManager part of the MS graph (graph.microosoft.com) to be able to send invitation mail. can I redeem the code received in the OpenIdConnectAuthenticationNotifications to get access token for the MS graph? knowing that I already do that but for AD graph (graph.windows.net)
Thanks for the help
I am new to the Facebook API. What I am trying to do without success is from my laptop create a new access token for myself through the Facebook API.
Below is the URL I am using to create this new access token:
String url = "
https://graph.facebook.com/oauth/authorize?client_id=##########&client_secret=##########&redirect_uri=http%3A%2F%2Fintelligentretrieval.com"
When I use my client id and then the client_secret (I assume this is the client password) then I get an error
{
"error": {
"message": "Missing redirect_uri parameter.",
"type": "OAuthException",
"code": 191
}
}
What exactly is the problem with this and the reason for the error?
Facebook requires a redirect_uri so I decided to dot it to my company site home page.(I figure this isn't the best place to redirect it but where should I redirect this?)
I want to redirect the result (generated access token) to my laptop from where I am making this URL request.
What exactly is the problem with this?
Is this possible with a browser like Chrome?
Is this possible using java?
Also is it possible to extend the access token expiration to 60 days with this url?
Please let me know if there is any confusion with any part of this post or if the answer can be found elsewhere.