设想:
我在 Windows Azure 上分别托管了两个 ASP.NET Web 应用程序,并且都与同一个 Azure Active Directory 租户相关联:
具有 AngularJS SPA 前端和adal.js库的 MVC 应用程序,用于在客户端处理 Azure AD 身份验证。
带有 Microsoft OWIN 中间件的 Web API,用于处理服务器上的 Azure AD 身份验证。
问题:
当 Angular 引导客户端应用程序时,页面在通过 oauth 重定向到正确的身份授权后正确加载,并且 adal.js 库为每个应用程序正确检索和存储不同的令牌(通过检查资源/会话存储选项卡Chrome 开发工具)。但是,当客户端应用程序尝试访问或更新 API 中的任何数据时,CORS 预检请求会响应 302 重定向到身份验证机构,这会导致控制台中出现以下错误:
XMLHttpRequest 无法加载https://webapi.azurewebsites.net/api/items。请求被重定向到' https://login.windows.net/ {authority-guid}/oauth2/authorize?response_type=id_token&redirect_uri=....etc..etc..',这对于跨域请求是不允许的需要预检。
示例标头(匿名):
要求 选项 /api/items HTTP/1.1 主机:webapi.azurewebsites.net 连接:保持活动 访问控制请求方法:GET Access-Control-Request-Headers:接受、授权 来源:https://mvcapp.azurewebsites.net 用户代理:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36 接受: */* 推荐人:https://mvcapp.azurewebsites.net/ 回复 找到 HTTP/1.1 302 内容长度:504 位置: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=...等... 服务器:Microsoft-IIS/8.0 X-Powered-By: ASP.NET 设置 Cookie:ARRAffinity=4f51...snip....redact....db6d;Path=/;Domain=webapi.azurewebsites.net
我做过/尝试过的事
- 确保 Azure AD 租户允许 OAuth2 隐式流,如此处和其他地方所述。
- 确保 API公开访问权限,并且 MVC/SPA使用这些公开的权限注册访问。
- 在 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: "11111111-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:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
相关资源
有时,我尝试了以下(以及更多)论坛和博客文章以及 github 示例代码中几乎所有可以想象的组合。