Dynamics CRM 401 with token provided - node.js

I'm working on a dynamics crm integration for a Single-Tenant Server-to-server authentication. This is required to obtain tokens invisibly as the data will be used to create customer facing ui.
Therefore I’m getting a token back from Azure using the client_credentials grant type. However when I attempt to use this token to access any dynamics endpoint (such as those documented here: https://msdn.microsoft.com/en-us/library/mt607871.aspx)
All I get back is a 401 - access denied.
I’ve done the following:
Create an Azure application
Created and stored a key
Enabled permissions for Dynamics CRM online
I’ve seen some suggestion that I need a service user in the CRM itself to provide access, however when I try and create one the options described do not appear. (such as here: https://msdn.microsoft.com/en-us/library/mt790170.aspx#bkmk_ManuallyCreateUser )
Can you suggest any steps I might be missing here?
Heres a sample call using the token
{ method: 'GET',
url: 'https://<snip>/api/data/v8.2/accounts?$select=name&$top=3',
headers:
{ Authorization: 'Bearer <snip>',
Accept: 'application/json',
'OData-MaxVersion': '4.0',
'OData-Version': '4.0' }
}
EDIT:
Please note that I am using node.js here and C# / .net based answers are probably not going to be massively helpful

Here is a post on how to configure server to server auth. Assuming you ran through all the steps except creating the application user, you can do so by:
In CRM Navigate to Settings->Security->Users
Change the view from "Enabled Users" to "Application Users"
From the new user form change the form from "User" to "Application User".
You should now be able to create your application user.

Related

Generate Embed Token using Power BI REST API 403 error

We are currently working on Embedding Power BI Reports into our web application. To achieve that we are following the instructions on official power bi documentation:
https://learn.microsoft.com/en-us/power-bi/developer/embed-service-principal#get-started-with-a-service-principal
We are on the “app owns data” case thus we will user service principal. There is also “access with master account” option but I could not find a way to generate token via REST API, it works only via .NET samples provided which is not compatible with out stack. Moreover, in all the samples I have examined, token is retrieved from the security context of currently logged in user(So not via REST API). So “access with master account” is not an option for us.
We followed the steps in the link above one by one:
Registered a server-side web application.
Created a security group in Azure AD and added our new server side
web application to this group.
Enabled service principal (as power bi admin) for the new security
group we created.
Created and published our reports.
Added the service principal as an admin to the workspace (new
workspace ) that we have created.
On step 6 where we embed the report in our applications we are having issues. Here is what we do:
Generate Access Token For Service Principal.
URL: https://login.microsoftonline.com/{$tenantId}/oauth2/v2.0/token
Request Body:
grant_type: client_credentials
scope:https://graph.microsoft.com/.default
client_id:${clientId} (from our created server-side web application) >
client_secret:${client_secret} (from our created server-side web application)
Header: Content-Type:
application/x-www-form-urlencoded
Response: {
"token_type": "Bearer",
"expires_in": 3600,
"ext_expires_in": 3600,
"access_token": "eyXXXXXXXXXXXXXXXXX....XXX" }
Generate Embed Token using Power BI REST API
URL:
https://api.powerbi.com/v1.0/myorg/groups/${groupId}/reports/${reportId}/GenerateToken (groupId and reportId fetched from power bi dev portal where we have our reports)
Request Body: { "accessLevel": "View", "allowSaveAs": "false" }
Header: Content-Type: application/json
Charset:utf-8 Accept: application/json
Authorization: Bearer ${access_token_from_step1}
Response: HTTP 403 (which means forbidden)
Unfortunately we are stuck at this point. We can not generate embed token which we will use to embed our reports/dashboards into our application. Although we have been through lots of online docs/discussions we could not find a solution. So here is what we need help.
Notes:
-We are creating/publishing reports using Power BI Desktop and our power bi pro account. (Although we are trying to embed them using service principal)
-We have run into this stackoverflow answer that claims we need to use resource owner flow instead of client credentials flow. But I believe it is against power bi documentation that states service principal can be applied without using any user/password.
The scope you defined when generating Access Token For Service Principal is not correct.
Try to use https://analysis.windows.net/powerbi/api/.default instead of https://graph.microsoft.com/.default
Note: There are many limitations when use service principal.

Getting token in Office 365 Oauth2 authentication

I am implementing Oauth 2 authentication for Office 365 account in a java based server side application. After reading the documentation, I have done the following things:
I have office 365 subscription.
I have created an app in Azure
Actve directory, that is necessary to authenticate web app using
office 365 account.
I have client ID and secret. I have also
given all permission to the Azure app.
I am requesting authorization code using the Url:
https://login.microsoftonline.com/common/oauth2/authorize?client_id={client_id}&response_type=code&redirect_uri={redirect url}&response_mode=query
As a response of this, I am getting authorization code as expected:
http://localhost:8080?code={authorication code}&session_state=259479e4-84aa-42ea-91e9-9e919cc99587
Now I need to get token along with the user name (user ID from which the user in logged in), as I need the user name for further processing. For this, I am using the method described here:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-protocols-oauth-code/
That is using a POST request like this:
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMw-DjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpi-zY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
Now the problem is that, when ever I send this post request, I always get error with error code some times 400 or 402 etc. I also user POST man in chrome to check the response of the call. It always return error like that:
{
"error": "invalid_grant",
"error_description": "AADSTS65001: The user or administrator has not consented to use the application with ID. Send an interactive authorization request for this user and resource.\r\nTrace ID: b834315e-ccb3-4533-b7c9-4af7b34054b9\r\nCorrelation ID: 784f18da-5479-4b69-b939-0067abfcc460\r\nTimestamp: 2016-08-02 07:28:22Z",
"error_codes": [
65001
],
"timestamp": "2016-08-02 07:28:22Z",
"trace_id": "b834315e-ccb3-4533-b7c9-4af7b34054b9",
"correlation_id": "784f18da-5479-4b69-b939-0067abfcc460"
}
(Note: I have registered all the apps using administrator login)
I have tried a lot to find out whats is going wrong here. I have added multiple apps in Azure Active directory but I am always getting similar response.
I request professionals to help me. . . ! Actually I want to allow user to click on a button in office 365 web add-in and use oauth2 authentication to login to our system. It will be great in somebody suggest me some good tutorial to successfully implement this.
If you were requesting the access token for the Office 365, the resource parameter in the send request should be https%3A%2F%2Foutlook.office.com.
And also you can use the Microsoft Graph as Philip suggested. You can refer here about how to choose the endpoint.
Receiving the error codes "interaction_required" or "invalid_grant" error codes means there is an issue with the "Refresh token" and it advised to:
Discard current refresh token
Request new authorization code

Authorization_IdentityNotFound Error while accessing graph API

I have searched with the error which I found, Did not find any matching questions. So posting question. Appreciate if some one provides some pointers to proceed.
My goal is to access graph API in my desktop client. I have started using fiddler to experiment.
I have followed instructions provided at https://graph.microsoft.io/en-us/docs/authorization/app_only
registered Web APP using Application Registration portal using my Microsoft work account.
Provided 'Read all users' full profiles in Delegated permissions
Requested token and Used the token in Authorization header to call the graph API, Getting following error.
https://graph.microsoft.com/v1.0/users
119
{
"error": {
"code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
"innerError": {
"request-id": "4c3a7bc6-e3d8-453c-adc9-5a12fec3b0ee",
"date": "2016-05-11T00:46:23"
}
}
}
In my case, I got the same error after I used Quickstart (step 1), then configured automatically .net sample (step 2), then download the code sample (step 3) as shown in the picture below.
All steps was done successfully except step 3. Microsoft code generate, generate app id, and app secret in project successfully but the tenant was set to common in appsetting.json as seen in image below.
I thought it was a valid thing, but later found out that this caused the issue.
Solution:
I copied the Directory (tenant) ID, than replace common with tenant Id, and it worked. I am not sure if this is a bug in Azure Quickstart code generation.
This sample helped me understand the flows around app-only permissions.
https://blogs.msdn.microsoft.com/tsmatsuz/2016/10/07/application-permission-with-v2-endpoint-and-microsoft-graph/
Key takeaways for me:
Ensure you set up the app and specify the Application Permissions needed
Do have an admin grant the app permission to run against the relevant directory.
Get the relevant token:
Notice the scope in the request below is https://graph.microsoft.com/.default
POST https://login.microsoftonline.com/{tenantname}.onmicrosoft.com/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=6abf3364-0a60-4603-8276-e9abb0d843d6&client_secret=JfgrNM9CcW...&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
Use the token to request the relevant graph resource, eg:
GET https://graph.microsoft.com/v1.0/users/demouser01#[tenant-name].onmicrosoft.com/drive/root/children
Accept: application/json
Authorization: Bearer eyJ0eXAiOi
For me, I had not given admin consent. This is a critical step. My mistake was in thinking that by granting the app permissions, this was giving admin consent, but its not the same thing.
From step 3 on this site: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service
I just pasted their call into a browser after filling in the tenant and client id, then signed in, and everything worked.
GET https://login.microsoftonline.com/{tenant}/adminconsent
?client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
while generating new access token, make sure to replace tenant_id with the actual tenant id
https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token
You'll find that this document is a better set of instructions for app-only apps.
There are two issues from your description that stand out.
You'll need to make the call with an X509 certificate for app-only flows.
You need to set up app scopes, rather than delegated scopes on your app - delegated scopes are for delegate flows rather than app-only flows.

API '500' Error when delegating admin access on MySite (OneDrive / Office365)

I would value some advice as we are facing an issue with the Office 365 API where it returns 500 errors, when we request delegated administrative access to the Office 365 MySites Site Collection.
The use case scenario is the following:
We have independent organizations, 'A' and 'B' , which both own their respectives Azure Active Directroy accounts and O365/Azure subscriptions.
Organiation B wishes to utilise an application provide Organisation A which requires delegated administrative access to it's Office365 MySites Site Collection.
Organisation B successfully adds the app to their Active Directory Account by using the OAuth2 authorization process, granting the permissions that the application requires over their company active directory.
The final part is delegating access of an admin account in Organisation B to the Mysites site collection in Organisation B's Office 365 account. If we utilise the manual process via the administrative panel all works well, although programatically via the API we receive a '500' error.
We are using the following call to programmatically add the user as site collection administrator: (please note: I have used [ dummmy id's] below )
Endpoint URL:
https://<..org_a..>.my.sharepoint.com/personal/[[user_OrganisationA_com]]/_api/web/siteUsers/getByEmail(#u)?#u='[[info#_OrganisationA.com']]
Method: POST
Body: {'__metadata':{ 'type': 'SP.User' }, 'IsSiteAdmin':'true'}
HTTP Headers:
• "Content-Type": "application/json; odata=verbose"
• "X-HTTP-Method": "MERGE"
• "Authorization": "Bearer <OAuth2 token>"
• "Accept": "application/json"
On the request above we are trying to add info#_organisationB.com as site collection administrator to UserC's personal site in One Drive for Business service (UserC is identified by the email UserC#_organisationB.com). The user info#_organisationB.com has Global Administrator privileges in Organisation B's Office365 domain and UserC#_organisationB.com) is a basic user with no admin rights.
The call returns a 500 HTTP Status code (Internal Server Error) and the following message:
object(stdClass)[18]
public 'odata.error' =>
object(stdClass)[19]
public 'code' => string '-2146232832, Microsoft.SharePoint.SPException' (length=45)
public 'message' =>
object(stdClass)[20]
public 'lang' => string 'en-US' (length=5)
public 'value' => string 'You need to be a site collection administrator to set this property.' (length=68)
To our knowledge an API call should never return a 500 HTTP Status Code (Internal Server Error), if we are not allowed to do what we intend it should provide an Insufficiente permissions message or similar, however, the fact that we can manually apply this through the SharePoint Online management portal makes us believe we are hitting a bug that is stopping us from achieving what we intend.
Any advise would be appreciated!
Are you using SSL from the website you execute the request?

JWT token issue on Azure Management API

I've been trying to use the Azure Service Management API in order to list the Hosted Services with no success.
In the first place, I was able to set up the authentication using PowerShell as the Microsoft documentation states here: https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
My first step was to request an access token using OAuth2 making a POST request to this URL:
https://login.windows.net/<MY_TENANT_ID>/oauth2/token
and passing these parameters:
grant_type: client_credentials
client_id: <THE_CLIENT_ID_OF_THE_APP_REGISTERED_THROUGH_POWERSHELL>
client_secret: <THE_PASSWORD_OF_APP_REGISTERED_THROUGH_POWERSHELL>
resource: https://management.core.windows.net
so, I receive a valid response and an access_token included in the response. So far so good.
Then, I want to make a simple call to the Management API; I would like to list my Hosted Services (Cloud Services), so I make a GET request to this URL:
https://management.core.windows.net/<MY_SUBSCRIPTION_ID>/services/hostedservices
Including the following headers:
Authorization: Bearer <THE_ACCESS_TOKEN_RECEIVED_IN_THE_PREVIOUS_STEP>
x-ms-version: 2014-10-01 (I've also tested with different versions)
but, what I get is a 401 Unauthorized error, with the following message:
The JWT token does not contain expected audience uri 'https://management.core.windows.net/'
I also tried with a Native Application registered directly in the Azure Portal (with Permissions set to use the Service Management API) and requesting a token using the grant_type = authorization_code. I get the access_token correctly and a refresh_token, but when I try to make a request to the above URL, I get the same error message.
On a side note, I am able to use the Azure Insights API successfully; the issue above is with the Azure Service Management API.
Anyone knows what I am missing?
I faced the same problem today. Complete the resource url with '/' https://management.core.windows.net
See the mismatch between the url in your resource and the one in the error message 'https://management.core.windows.net/'

Resources