angular - 调用受B2C保护的Function App API的Angular应用接收500,Function接收404

标签 angular azure-active-directory azure-ad-b2c msal msal.js

作为静态网站托管在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.c‌​om/<policyname>/v2.0https://<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 B2CNode.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。因此,我想了解如何解决此问题。

设置

假设/先决条件

  • 已创建Azure B2C租户
  • 已为B2C租户
  • 配置了身份提供程序
  • 已为B2C租户配置了Sign-up and Sign-in用户流策略
  • 记下其名称。我们在下面将其名称称为<SignUpAndSignInPolicyName>
  • 已启用静态网站功能
  • 创建了一个Azure存储帐户
  • 已创建Angular应用
  • 已安装@azure/msal-angular
  • app-routing.module.ts中,
  • 已设置useHash选项:imports: [RouterModule.forRoot(routes, { useHash: true })],
  • 散列路由对于容纳静态托管
  • 是必需的
  • 已创建安全组件并建立了 protected 路由

  •        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 Function应用
  • 记下功能应用程序的URL
  • 已在Function App中创建了以下功能以进行测试。它已发布到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应用
  • 创建API应用程序(即,将其命名为“ API ”)
  • 记下其应用程序ID
  • 稍后将在功能应用程序的AAD身份验证设置中使用应用程序ID
  • 将Include Web App / Web API设置为
  • 将“允许隐式流”设置为
  • 将回复URL设置为 https://<functionappname>.azurewebsites.net/.auth/login/aad/callback
  • 使用/.auth/login/aad/callback后缀功能应用程序的URL
  • 将应用程序ID URI段设置为“API”
  • 产量:https://<b2c_tenant_name>.onmicrosoft.com/API

  • SPA应用
  • 创建SPA应用程序(即,将其命名为“ SPA ”)
  • 将Include Web App / Web API设置为
  • 设置允许隐式流向
  • 将回复URL设置为 http://localhost:4200
  • 在“API访问”选项卡中,添加API应用程序API
  • 唯一可用的范围“代表已登录用户(user_impersonation)访问此应用程序”将被预先选择

  • 主要(非B2C)租户

    功能应用
  • 在“身份验证/授权”刀片中,
  • 将应用程序服务身份验证设置为
  • 设置未对请求进行身份验证的请求时采取的操作使用Azure Active Directory登录
  • 在“身份验证提供程序”部分中,如下配置Azure Active Directory提供程序:
  • 将管理模式设置为高级
  • 将客户端ID设置为B2C API应用程序的应用程序ID
  • 将颁发者URL设置为 https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=<SignUpAndSignInPolicyName>
  • 保存这些身份验证/授权设置

  • Azure应用程序
  • 在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
  • secure.component.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>
    
  • app.component.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>&nbsp;<span class="acronym">(B2C)</span> authentication. The site interacts with a secure
        <em>Azure Functions</em>&nbsp;<span class="acronym">API</span>.
    </mat-card>
    
    <p style="text-align: center;"><a routerLink="/" routerLinkActive="active">Home</a>&nbsp;&nbsp;<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响应
  • 如果将SPA应用程序的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/

    相关文章:

    azure - Azure Active Directory 中的简单目录查找

    Azure Active Directory OAuth 资源所有者密码凭据流程

    azure - 将部门包含在 claim list 中

    azure-ad-b2c - 将用户从一个 AAD B2C 租户迁移到另一个 B2C 租户,包括密码

    angular - * ngIf 在 Angular 绑定(bind)到对象属性时如何影响性能?

    javascript - polymer 。纸张子菜单触发器适用于纸张项目内的两个元素

    authentication - 在客户端 OWIN Web 应用程序中实现 Azure Active Directory 身份验证

    angular - Chrome 文件浏览器 - 访问完整路径

    angular - 找不到本地 "typescript"包。 "@ngtools/webpack"包 Angular 2

    azure - 身份验证成功后无法在 Azure B2C 中获取用户名