An unauthorized HTTP request to the Dynamics CRM API through Angular 2 using ADAL

I am trying to create an application using Angular that can connect to Dynamics CRM through the web API. These are the following steps:

1. Registered your own application in Azure, granted the required delegated permissions, and updated the manifest to allow implicit flow.

2. Created an application user in CRM, setting his application identifier equal to the client ID of my registered Azure application. Assigned my own application security role to my application user.

3 .. Cloned many Angular 2 quickstart Git repositories that authenticate with Azure AD through ADAL, like this one .

4. Updated clone code adal config, by setting my tenant, clientId, redirectUriand endpoints.

So far, it has been successful. I can launch the application and enter my browser through my browser, either as an application user or as another CRM user that is part of Azure AD. This returns a token.

5. Attempt to send http.getto v8.0or v8.2(I was told that it v8.2does not support cross-domain calls):

getEntities(): Promise<any> {
    let token = this.adalService.getCachedToken(this.adalService.config.clientId);
    let headers = new Headers({
        'Authentication': 'Bearer ' + token,
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(`${crmURL}/api/data/v8.2/accounts`, options)
        .toPromise()
        .then((res) => { return res; })
        .catch((e) => { console.error(e); });
}

6. Get this error message:

enter image description here

It reads:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. 
The response had HTTP status code 401.

While on my Chrome browser’s network tab, I get two answers:

Answer 1

Are common

Request URL:https://ms-dyn365-prevxxxxxx/api/data/v8.2/accounts
Request Method:OPTIONS
Status Code:200 OK
Remote Address:104.44.xxx.xxx:xxx
Referrer Policy:no-referrer-when-downgrade

Headings

Access-Control-Allow-Headers:authentication,content-type,odata-maxversion,odata-version
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:http://localhost:3000
Access-Control-Expose-Headers:Preference-Applied,OData-EntityId,Location,ETag,OData-Version,Content-Encoding,Transfer-Encoding,Content-Length,Retry-After
Access-Control-Max-Age:3600
Content-Length:0
Date:Thu, 13 Apr 2017 10:08:01 GMT
Server:Microsoft-IIS/8.5
Set-Cookie:crmf5cookie=!NDyiupL55lrWWLtPQKTK52dwbxk9wdEAHeCiec0/z/7x9KWXe2dVIdQCGvL0S/HAp7F3N0OGfeWf/70=;secure; path=/
Strict-Transport-Security:max-age=31536000; includeSubDomains
Vary:Origin
X-Powered-By:ASP.NET

Answer 2

Are common

Request URL:https://ms-dyn365-prevxxxxx.crm4.dynamics.com/api/data/v8.2/accounts
Request Method:GET
Status Code:401 Unauthorized
Remote Address:104.xx.xxx.xxx:xxx
Referrer Policy:no-referrer-when-downgrade

Headings

Cache-Control:private
Content-Length:49
Content-Type:text/html
Date:Thu, 13 Apr 2017 10:08:01 GMT
REQ_ID:b2be65bc-xxxx-4b34-xxxx-5c39812650xx
Server:Microsoft-IIS/8.5
Set-Cookie:ReqClientId=xxxxxxxx-70b5-45f9-9b84-30f59481bxxx; expires=Wed, 13-Apr-2067 10:08:01 GMT; path=/; secure; HttpOnly
Strict-Transport-Security:max-age=31536000; includeSubDomains
WWW-Authenticate:Bearer authorization_uri=https://login.windows.net/xxxxxxxx-87e4-4d81-8010-xxxxxxxxxxxxx/oauth2/authorize, resource_id=https://ms-dyn365-prevxxxxxx.crm4.dynamics.com/
X-Powered-By:ASP.NET

Note. I can successfully access the web API through the mail manager:

1. https://www.getpostman.com/oauth2/callback URL- Azure .

2. Postman, :

Token Name: Token
Auth URL: https://login.windows.net/common/oauth2/authorize?resource=https://ms-dyn365-prevxxxxxx.crm4.dynamics.com
Access Token URL: https://login.microsoftonline.com/common/oauth2/token
Client ID: xxxxxxxx-ebd3-429c-9a95-xxxxxxxxxxxx
Callback URL: https://www.getpostman.com/oauth2/callback
Grant Type: Authorization Code

3.. -, .

4. , Postman GET:

Content-Type: application/json
Authorization: Bearer eyJ0eXAiO...

5. GET :

GET https://ms-dyn365-prevxxxxxx.crm4.dynamics.com/api/data/v8.2/accounts

6. .

, 401.

+4
1

Access-Control-Allow-Origin , -.

JSONP Access-Control-Allow-Origin . JSONP , , - , orignal.

AJAX, .

Update

, REST.

REST 8.2 . 8.0, , :

enter image description here

:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <base href="/">
    <title></title>
    <script src="node_modules\angular\angular.js"></script>

</head>
<body>
    <div ng-app="myApp">
        <div ng-controller="HomeController">
            <ul class="nav navbar-nav navbar-right">            
                     <li><a class="btn btn-link" ng-click="listAccounts()">List account info</a></li>
            </ul>
           <div ng-repeat="account in accounts">
                    <span>name:</span><span>{{account.name}}</span>
           </div>
        </div>
    </div>

    <script>
    var myApp = angular.module('myApp',[]);

    myApp.controller('HomeController', ['$scope', '$http',
                            function ($scope, $http){

                                    $scope.listAccounts=function(){

                                        var req = {
                                        method: 'GET',
                                        url: 'https://{domain}.crm.dynamics.com/api/data/v8.0/accounts',
                                        headers: {
                                        'authorization': 'Bearer eyJ0eXAiO...'
                                        }
                                        };
                                       $http(req).then(function(response){
                                            $scope.accounts=response.data.value
                                       }, function(){

                                       });
                                    }
                            }]);
    </script>
</body>
</html>

Angular 2:

https://github.com/VitorX/angular2-adaljs-crm

+2

Source: https://habr.com/ru/post/1674670/


All Articles