CORS异常:无法加载https://login.microsoftonline.com/{TENANT_ID}/oauth2/authorize

时间:2018-10-22 14:46:55

标签: azure cors azure-active-directory azure-authentication

这是具有工作/学校类型身份验证的ASP.NET MVC项目。

控制器

using Nasi.AzureConn;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Nasi.Controllers
{
    public class JimmyController : Controller
    {
        public ActionResult GetAllSubscriptions()
        {
            //The below line is where the ttps://login.microsoftonline.com/{TENANT_ID}/oauth2/authorize?client_id={CLIENT_ID}
            //is being called
            AzureAuth aAuth = AzureAuth.GetAzureAuthorization(Session, HttpContext.GetOwinContext());
            AzureConn aConn = AzureConn.GetAzureConnection(Session, aAuth);
            var subscriptions = aConn.GetAllSubscriptions();
            return Json(subscriptions, JsonRequestBehavior.AllowGet);
        }
    }
}

.cshtml

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

    <p>Data:</p>

    <code>{{az_data}}</code>

</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope, $http) {
        $http.get("/Jimmy/GetAllSubscriptions")
            .then(function (response) {
                $scope.az_data = response.data;
            });
    });
</script>

我有点困惑为什么我得到Failed to load https://login.microsoftonline.com/{TENANT_ID}/oauth2/authorize?client_id={CLIENT_ID}&response_mode=form_post&response_type=code%20id_token&scope=openid%20profile&state=OpenIdConnect.AuthenticationProperties%3{SOME RANDOM VALUE}&x-client-SKU=ID_NET451&x-client-ver=5.2.1.0: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44320' is therefore not allowed access.,因为认证由它自己的控制器处理。当我调试控制器var subscriptions = aConn.GetAllSubscriptions();时得到了预期的数据。

有人可以启发我吗?

1 个答案:

答案 0 :(得分:-1)

这是有关CORS的问题,您需要允许CORS。

我们可以通过如下修改Web.config来做到这一点:

<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>