加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – CORS预检请求在Azure托管的Web API中响应302重定向

发布时间:2020-12-17 08:52:06 所属栏目:安全 来源:网络整理
导读:场景: 我有两个在Windows Azure上单独托管的ASP.NET Web应用程序,它们都与同一个Azure Active Directory租户相关联: 带有AngularJS SPA前端的MVC应用程序和用于在客户端上处理Azure AD身份验证的adal.js库. 带有Microsoft OWIN中间件的Web API,用于在服务
场景:

我有两个在Windows Azure上单独托管的ASP.NET Web应用程序,它们都与同一个Azure Active Directory租户相关联:

>带有AngularJS SPA前端的MVC应用程序和用于在客户端上处理Azure AD身份验证的adal.js库.
>带有Microsoft OWIN中间件的Web API,用于在服务器上处理Azure AD身份验证.

问题:

当角度引导客户端应用程序时,页面在通过oauth重定向到正确的Identity Authority后正确加载,并且adal.js库正确检索并存储每个应用程序的不同令牌(通过检查“资源/会话 – 存储”选项卡进行验证Chrome开发工具).但是,当客户端应用程序尝试访问或更新API中的任何数据时,CORS预检请求正在响应302重定向到Identity Authority,这会导致控制台中出现以下错误:

XMLHttpRequest cannot load 07001.
The request was redirected to
‘07002{authority-guid}/oauth2/authorize?response_type=id_token&redirect_uri=….etc..etc..’,
which is disallowed for cross-origin requests that require preflight.

示例标头(匿名):

Request
OPTIONS /api/items HTTP/1.1
Host: webapi.azurewebsites.net
Connection: keep-alive
Access-Control-Request-Method: GET
Access-Control-Request-Headers: accept,authorization
Origin: https://mvcapp.azurewebsites.net
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/39.0.2171.99 Safari/537.36
Accept: */*
Referer: https://mvcapp.azurewebsites.net/

Response
HTTP/1.1 302 Found
Content-Length: 504
Location: https://login.windows.net/{authority-guid}/oauth2/authorize?response_type=id_token&redirect_uri=https%3A%2F%2F....etc..etc.%2F&client_id={api-guid}&scope=openid+profile+email&response_mode=form_post&state=...etc...
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=4f51...snip....redact....db6d;Path=/;Domain=webapi.azurewebsites.net

我做了什么/尝试过

>确保Azure AD租户允许OAou2隐式流,如here和其他地方所述.
>确保API exposes access permissions和MVC / SPA registers for access使用那些公开的权限.
>在API的web.config中明确添加了一个OPTIONS动词处理程序(见下文).
>使用在API服务器上启用CORS的各种组合,OWIN本身以及EnableCorsAttribute(见下文).

问题

有没有办法让Azure AD租户关联的Web API不重定向CORS预检请求?
我在adal.js库和/或OWIN启动代码中缺少一些初始化设置(见下文)?
Azure门户中是否有允许OPTIONS请求通过OWIN管道的设置?

相关代码:

adal.js初始化

angular.module("myApp",["ngRoute","AdalAngular"])

.config(["$routeProvider","$locationProvider","$httpProvider","adalAuthenticationServiceProvider",function ($routeProvider,$locationProvider,$httpProvider,adalProvider) {

        $routeProvider.when("/",{ // other routes omitted for brevity
            templateUrl: "/content/views/home.html",requireADLogin: true // restrict to validated users in the Azure AD tenant
        });

        // CORS support (I've tried with and without this line)
        $httpProvider.defaults.withCredentials = true;

        adalProvider.init({
            tenant: "contoso.onmicrosoft.com",clientId: "22222111-aaaa-2222-bbbb-3333cccc4444",// Azure id of the web app
            endpoints: {
                // URL and Azure id of the web api
                "https://webapi.azurewebsites.net/": "99999999-zzzz-8888-yyyy-7777xxxx6666"
            }
        },$httpProvider);
    }
]);

OWIN中间件初始化

public void ConfigureAuth(IAppBuilder app)
{
    // I've tried with and without the below line and also by passing
    // in a more restrictive and explicit custom CorsOptions object
    app.UseCors(CorsOptions.AllowAll);

    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
            TokenValidationParameters = new TokenValidationParameters
            {
                // Azure id of the Web API,also tried the client app id
                ValidAudience = "99999999-zzzz-8888-yyyy-7777xxxx6666"
            },Tenant = "contoso.onmicrosoft.com"
        }
    );

    // I've tried with and without this
    app.UseWebApi(GlobalConfiguration.Configuration);
}

WebApiConfig初始化

public static void Register(HttpConfiguration config)
{
    // I've tried with and without this and also using both this
    // and the OWIN CORS setup above. Decorating the ApiControllers
    // or specific Action methods with a similar EnableCors attribute
    // also doesn't work.
    var cors = new EnableCorsAttribute("https://mvcapp.azurewebsites.net","*","*")
    {
        cors.SupportsCredentials = true // tried with and without
    };
    config.EnableCors(cors);

    // Route registration and other initialization code removed
}

API OPTIONS动词处理程序注册

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="OPTIONSHandler" path="*" verb="OPTIONS" modules="IsapiModule" scriptProcessor="C:WindowsMicrosoft.NETFramework64v4.0.30319aspnet_isapi.dll" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

相关资源

在某个时间,我已经尝试了以下(以及更多)论坛和博客文章以及github示例代码中的所有可以想象的组合.

> ADAL JavaScript and AngularJS – Deep Dive
> Secure ASP.NET Web API 2 using Azure Active Directory,Owin Middleware,and ADAL
> Token Based Authentication using ASP.NET Web API 2,Owin,and Identity
> AzureADSamples/SinglePageApp-DotNet (github)
> AngularJSCORS (github)
> How to make CORS Authentication in WebAPI 2?
> AngularJS and OWIN Authentication on WebApi

我有类似的问题找出适合的包.只有Owin cors足以设置.请先检查owin.cors的包.
<package id="Microsoft.Owin" version="3.0.0" targetFramework="net45" />
<package id="Microsoft.Owin.Cors" version="2.1.0" targetFramework="net45" />

处理程序的WebConfig选项:

<system.webServer>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

你正在使用owin config中的specsiying cors选项做对了.

public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = ConfigurationManager.AppSettings["ida:Audience"],Tenant = ConfigurationManager.AppSettings["ida:Tenant"]

            });
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    }

控制器不需要CORS相关属性.

[Authorize]
public class ContactsController : ApiController
{

    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "person1","person2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "person" + id;
    }

WebAPIConfig不需要与CORS相关的条目.

工作示例如下:https://github.com/omercs/corsapisample

您可以使用以下代码在应用中进行测试:

app.factory('contactService',['$http',function ($http) {
var serviceFactory = {};

var _getItems = function () {
    $http.defaults.useXDomain = true;
    delete $http.defaults.headers.common['X-Requested-With'];
    return $http.get('http://yourhostedpage/api/contacts');
};

serviceFactory.getItems = _getItems;

return serviceFactory;

}]);

预检回应示例:

Remote Address:127.0.0.1:8888
Request URL:http://localhost:39725/api/contacts
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept,authorization
Access-Control-Request-Method:GET
Host:localhost:39725
Origin:http://localhost:49726
Proxy-Connection:keep-alive
Referer:http://localhost:49726/myspa.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/39.0.2171.99 Safari/537.36
Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization
Access-Control-Allow-Origin:http://localhost:49726
Content-Length:0
Date:Fri,23 Jan 2015 01:10:54 GMT
Server:Microsoft-IIS/8.0
X-Powered-By:ASP.NET

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读