作为静态网站托管在Azure存储帐户上的Angular网站在调用Azure B2C保护的Function App功能时会收到500。该函数正在接收404。
更新资料
该问题的原始标题为“调用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>
代替功能应用程序的发行方URL中的https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/
。即,删除尾随的.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
段。在随后的聊天 session 中,Alex指出该策略是路径的一部分,例如https://<tenantname>.b2clogin.com/<tenantname>.onmicrosoft.com/<policyname>/v2.0
或https://<tenantname>.b2clogin.com/<tenantguid>/<policyname>/v2.0
。但是,Function App的Issuer URL的这些路径中的任何一条都将还原为401响应。
解决401问题后,Angular SPA应用程序现在收到500。但是,被调用的API函数正在收到404。FunctionApp的日志流指示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
容器内)。有两个项目:一个 public SPA
Angular 7+项目和一个 protected API
Function App项目。由于Azure存储帐户静态网站仅允许 public 匿名访问所有文件,因此不保护Angular应用程序托管Blob容器的文件(网站的文件)。但是Angular应用程序对Azure Functions API调用的调用是安全的。 Function App API
项目通过Azure AD B2C身份验证进行保护。
为此,我试图适应Single-Page Application built on MSAL.js with Azure AD B2C和Node.js Web API with Azure AD B2C中概述的技术。我能够运行这些样本。而且,我能够修改它们的设置以针对我自己的Azure B2C租户(而不是针对Microsoft的B2C租户)进行身份验证并在本地运行它们。但是我没有尝试将这些示例项目部署到Azure并找出设置所需的调整。我不是Node.js开发人员,所以跳过了部署工作。
但是,无论何时从SPA调用API,我后来将那些(Node.js)示例项目中的代码改编成我的静态托管Angular SPA项目以及我的Azure Functions API项目时,都会产生401 Unauthorized
。因此,我想了解如何解决此问题。
设置
假设/先决条件
Sign-up and Sign-in
用户流策略<SignUpAndSignInPolicyName>
@azure/msal-angular
包app-routing.module.ts
中,useHash
选项: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' },
];
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应用
API
应用程序(即,将其命名为“ API ”)https://<functionappname>.azurewebsites.net/.auth/login/aad/callback
/.auth/login/aad/callback
后缀功能应用程序的URL https://<b2c_tenant_name>.onmicrosoft.com/API
SPA应用
SPA
应用程序(即,将其命名为“ SPA ”)API
应用程序API主要(非B2C)租户
功能应用
API
应用程序的应用程序ID https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
Azure应用程序
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
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);
});
});
}
}
<h4>Secure Component</h4>
<button (click)="invokeB2cSecuredAzureFunction()">Fetch data from B2C-secured Azure functions</button>
<hr />
<div>{{azureTestFunctionResponse}}</div>
<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
/secure
路线Fetch data from B2C-secured Azure function
按钮401 Not Authorized
响应Reply URL
更新为SPA
静态网站URL并发布了SPA文件,则在调用API函数时同样会返回401
。 所以我不确定什么配置错误。有任何想法吗?
最佳答案
这不是您租户的发行人:
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函数中的允许的受众。
关于angular - 调用受B2C保护的Function App API的Angular应用接收500,Function接收404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56411863/