【发布时间】:2020-02-29 18:48:43
【问题描述】:
app.module.ts已经配置好,应用可以通过Azure B2C登录界面成功登录。
还有一个 Azure 函数,它通过 HTTP GET 请求简单地返回一个带有一个字符串属性“text”的 JSON 对象。该函数已配置为使用 Azure B2C 进行身份验证。这已通过在浏览器中访问函数 URL、通过 B2C 登录屏幕登录并从函数返回 JSON 对象来确认。
调用受保护 api 的组件如下所示:
import { Component, OnInit } from '@angular/core';
import { MsalService } from '@azure/msal-angular';
import { HttpClient } from '@angular/common/http';
const FUNCTION_ENDPOINT = 'function-url-here';
export interface MyInterface {
text: string;
}
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
value: MyInterface;
constructor(private authService: MsalService, private http: HttpClient) { }
ngOnInit() {
this.getValue();
}
getValue() {
this.http.get<MyInterface>(FUNCTION_ENDPOINT).toPromise()
.then(value => {
this.value = value;
});
}
}
关闭函数身份验证后,函数中的 JSON 将返回给 Angular 应用程序。开启功能认证后,浏览器控制台打印如下错误:
从源“null”访问“https://mytenant.b2clogin.com/mytenant.onmicrosoft.com/oauth2/v2.0/authorize?response_type=id_token&redirect_uri=https%3A%2F%functionname.azurewebsites.net%2F.auth%2Flogin%2Faad%2Fcallback&client_id=SAMPLE-STRING&scope=openid+profile+email&response_mode=form_post&p=b2c_1_signupsignin1&nonce=SAMPLE-STRING&state=redir%3D%252Fapi%252FHttpTrigger2%253Fcode%SAMPLE-STRING”处的 XMLHttpRequest(从“https://functionname.azurewebsites.net/api/HttpTrigger2?code=SAMPLE-STRING”重定向)已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头.
第二个错误:
core.js:4002 ERROR 错误:未捕获(承诺中):HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status": 0,"statusText":"未知错误","url":"https://functionname.azurewebsites.net/api/HttpTrigger2?code=SAMPLE-STRING","ok":false,"name":"HttpErrorResponse","message":"https://functionname.azurewebsites.net/api/HttpTrigger2?code=SAMPLE-STRING 的 Http 失败响应:0 未知错误","错误":{"isTrusted":true}}
控制台也有警告:
跨域读取阻止 (CORB) 阻止了 MIME 类型为 text/html 的跨域响应 https://mytenant.b2clogin.com/mytenant.onmicrosoft.com/oauth2/v2.0/authorize?response_type=id_token&redirect_uri=https%3A%2F%2Ffunctionname.azurewebsites.net%2F.auth%2Flogin%2Faad%2Fcallback&client_id=SAMPLE-STRING&scope=openid+profile+email&response_mode=form_post&p=b2c_1_signupsignin1&nonce=SAMPLE-STRING&state=redir%3D%252Fapi%252FHttpTrigger2%253Fcode%SAMPLE-STRING。详情请见https://www.chromestatus.com/feature/5629709824032768。
Angular 应用程序的 URL 是 http://localhost:4200/。这是 Azure 函数的 CORS 配置:
可以做些什么来让 Angular 应用程序向 Azure Function 发出经过身份验证的请求?
【问题讨论】:
-
嗨@craydon。您可能需要为此检查 Enable Access-Control-Allow-Credentials。
-
有什么区别?那安全吗?如果这不起作用,还有其他建议吗?
-
要访问已启用身份验证的应用服务,您需要在标头中传递访问令牌。 codemilltech.com/…
-
能够将 B2C 添加到函数应用中,但使用 MSAL 从 Angular 调用并不简单。
标签: angular typescript azure-functions azure-ad-b2c msal