Angular网站托管在Azure 存储帐户 as a 静态网站当调用 Azure B2C 保护时收到 500功能应用程序功能。该函数正在接收 404。
Update
这个问题的原始标题是“调用 B2C 安全函数的 Angular 应用程序接收401 Unauthorized
正如@Alex AIT 建议的(如下),解决方案是替换https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
在功能应用程序中发行人网址 with https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/
。即,删除尾随.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
段。在随后的聊天中,Alex 指出该策略是路径的一部分,例如https://<tenantname>.b2clogin.com/<tenantname>.onmicrosoft.com/<policyname>/v2.0
or https://<tenantname>.b2clogin.com/<tenantguid>/<policyname>/v2.0
。然而,函数应用程序的这些路径之一发行人网址恢复到 401 响应。
解决 401 问题后,Angular SPA 应用程序现在收到 500。但是,调用的 API 函数收到 404。函数应用程序的日志流表明Failed to download OpenID configuration from 'https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration': The remote server returned an error: (404) Not Found.
所以政策没有附加。
我的目标是建立一个安全、无服务器的 Angular Web 应用程序,该应用程序静态托管在 Azure 存储网站上(即在存储帐户的$web
容器)。有两个项目:apublic SPA
角度 7+项目和一个受保护的 API
功能应用程序项目。由于 Azure 存储帐户静态网站仅允许公开匿名访问所有文件,因此Angular应用程序托管 blob 容器的文件(网站的文件)不安全。但是Angular应用程序的调用Azure 函数API 调用是安全的。这功能应用程序 API
项目通过 Azure AD B2C 身份验证进行保护。
为此,我尝试采用中概述的技术使用 Azure AD B2C 在 MSAL.js 上构建的单页应用程序 https://azure.microsoft.com/en-us/resources/samples/active-directory-b2c-javascript-msal-singlepageapp/ and Node.js Web API 与 Azure AD B2C https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi。我能够运行这些样本。此外,我还能够修改它们的设置,以针对我自己的 Azure B2C 租户(而不是针对 Microsoft 的 B2C 租户)进行身份验证并在本地运行它们。但我并没有尝试将这些示例项目部署到 Azure 并找出设置所需的调整。我跳过了部署练习,因为我不是 Node.js 开发人员。
但我随后将这些 (Node.js) 示例项目中的代码改编为我的静态托管 Angular SPA 项目和我的 Azure Functions API 项目,结果是:401 Unauthorized
每当从 SPA 调用 API 时。所以我想了解如何解决这个问题。
设置
假设/先决条件
- 蔚蓝B2C租户已经被创造了
-
身份提供商已配置为B2C租户
- A
Sign-up and Sign-in
user flow policy has been configured for the B2C Tenant
- 记下其名称。我们将在下面将其名称称为
<SignUpAndSignInPolicyName>
- 已创建 Azure 存储帐户及其静态网站功能已启用
-
An Angular应用程序已创建
- The
@azure/msal-angular
软件包已安装
-
In app-routing.module.ts
,
- the
useHash
option has been set: imports: [RouterModule.forRoot(routes, { useHash: true })],
- 已创建安全组件并建立受保护的路由
const routes: Routes = [
{ path: 'secure', component: SecureComponent, canActivate: [MsalGuard] },
{ path: 'state', redirectTo: 'secure' }, // HACK/TODO
{ path: 'error', redirectTo: 'secure' }, // HACK/TODO
{ path: '', redirectTo: '', pathMatch: 'full' },
];
-
蔚蓝功能应用程序已经被创造了
-
在以下函数中已创建功能应用程序用于测试目的。它已发布到 Azure:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace SomeCompany.Functions
{
public static class HttpTriggerCSharp
{
[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
}
B2C租户
API Application
- 创建
API
应用程序(即,将其命名为“API”)
- Make a note of its Application ID
- The 应用程序ID稍后将在Function App的AAD Auth设置中使用
- Set 包括Web应用程序/Web API to Yes
- Set the 允许隐式流 to Yes
- Set the Reply URL to
https://<functionappname>.azurewebsites.net/.auth/login/aad/callback
- 后缀功能应用程序的网址为
/.auth/login/aad/callback
- Set the App ID URI segment to “API”
- Yields:
https://<b2c_tenant_name>.onmicrosoft.com/API
SPA Application
- 创建
SPA
应用程序(即,将其命名为“SPA”)
- Set 包括Web应用程序/Web API to Yes
- Set 允许隐式流 to Yes
- Set the 回复网址 to http://本地主机:4200 http://localhost:4200
- In the API access tab, add the
API
application API
- 唯一可用的范围“代表登录用户访问此应用程序 (user_impersonation)”将被预先选择
主要(非 B2C)租户
Function App
- In the Authentication / Authorization blade,
- Set 应用服务认证 to On
- Set 请求未经验证时采取的操作 to 使用 Azure Active Directory 登录
- In the Authentication Providers section, configure the Azure Active Directory provider as follows:
- Set 管理模式 to Advanced
- Set 客户ID到B2C
API
应用程序的应用程序ID
- Set the 发行人网址 to
https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
- 保存这些认证/授权设置
Azure Application
-
In the Angular应用程序的app.module.ts
NgModule
import属性,设置:
MsalModule.forRoot({
clientID: '<B2C Tenant |> SPA Application |> Application ID>',
// Note, for authority, the following doesn't work:
// B2C Tenant |> User flows (policies) |> <SignUpAndSignInPolicyName> |> Run user flow |> URL at top of the `Run user flow` blade
// I.e., `https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>`
// Supposedly (according to various blog posts), that URL should be used as the `authority`. So, why doesn't it work?.
// The following URL works. However, the B2C portal indicates that `login.microsoftonline.com` is to be deprecated soon
authority: 'https://login.microsoftonline.com/tfp/<b2c_tenant_name>.onmicrosoft.com/<SignUpAndSignInPolicyName>',
// B2C Tenant |> Applications |> API |> Published Scopes |> `user_impersonation` | FULL SCOPE VALUE
consentScopes: ['https://<b2c_tenant_name>.onmicrosoft.com/API/user_impersonation'],
})
-
创建一个名为Secure
ng g c Secure -s --skipTests
-
安全组件.ts
import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { MsalService } from '@azure/msal-angular';
@Component({
selector: 'app-secure',
templateUrl: './secure.component.html',
})
export class SecureComponent {
constructor(private http: HttpClient, private msalService: MsalService) { }
azureTestFunctionResponse: string;
callApiWithAccessToken(accessToken: string) {
const url = 'https://<function_app_name>.azurewebsites.net/api/HttpTriggerCSharp?name=HelloFromAzureFunction';
const httpHeaders = new HttpHeaders({ Authorization: `Bearer ${accessToken}` });
const subscription: Subscription = this.http.get(url, { headers: httpHeaders , responseType: 'text'}).subscribe(_ => {
this.azureTestFunctionResponse = _;
subscription.unsubscribe();
});
}
invokeB2cSecuredAzureFunction() {
// B2C Tenant |> `API` Application |> Published Scopes |> `user_impersonation` scope |> Full Scope Value
const tokenRequest: string[] = ['https://<b2c_tenant_name>.onmicrosoft.com/API/user_impersonation'];
this.msalService.acquireTokenSilent(tokenRequest)
.then(tokenResponse => {
this.callApiWithAccessToken(tokenResponse);
})
.catch(error1 => {
this.msalService.acquireTokenPopup(tokenRequest)
.then(tokenResponse => {
this.callApiWithAccessToken(tokenResponse);
})
.catch(error => {
console.log('Error acquiring the access token to call the Web api:\n' + error);
});
});
}
}
-
secure.component.html
<h4>Secure Component</h4>
<button (click)="invokeB2cSecuredAzureFunction()">Fetch data from B2C-secured Azure functions</button>
<hr />
<div>{{azureTestFunctionResponse}}</div>
-
应用程序组件.html
<div style="text-align:center">
<h4> {{ title }} </h4>
</div>
<mat-card style="float: left;">
This site is a configuration demonstration of a secure, serverless Angular web application. The site is statically hosted on an
<em>Azure Storage</em> website (<code>$web</code> container). The site's backend is secured
by Azure <em>Business-to-Consumer</em> <span class="acronym">(B2C)</span> authentication. The site interacts with a secure
<em>Azure Functions</em> <span class="acronym">API</span>.
</mat-card>
<p style="text-align: center;"><a routerLink="/" routerLinkActive="active">Home</a> <a routerLink="/secure" routerLinkActive="active">Secure</a></p>
<p style="text-align: center;"><router-outlet></router-outlet></p>
在本地提供应用程序:ng serve
- Click on the Secure link
- 哪个导航到
/secure
route
- 提示用户进行身份验证
- 单击
Fetch data from B2C-secured Azure function
button
- 服务器返回一个
401 Not Authorized
回复
- 如果 SPA 应用程序的
Reply URL
更新为SPA
静态网站 URL 和 SPA 文件已发布,401
同样,当调用 API 函数时也会返回。
所以我不确定什么配置错误。有任何想法吗?
这不是您的租户的发行人:
https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
但如果您在浏览器中打开此 URL,它将显示您搜索的发行人。
它应该是这样的:
https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0
https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_guid>.onmicrosoft.com/v2.0
https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/SignUpAndSignInPolicyName/v2.0
https://login.microsoftonline.com/<b2c_tenant_name>.onmicrosoft.com/v2.0
对于 Azure Function 和 Angular 应用程序,选择 b2clogin.com 和 login.microsoftonline.com 可能也是一个好主意。我不认为你可以这样混合它们。
如果您仍然遇到问题,您可以尝试将此作为范围而不是/user_impersonation
:
https://<b2c_tenant_name>.onmicrosoft.com/API/.default
或者尝试添加https://<b2c_tenant_name>.onmicrosoft.com/API/user_impersonation
发送给 Azure Function 中允许的受众。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)