我有一个托管在azure中的web应用程序中的angular应用程序。它是使用VS中的模板创建的,带有。Net Core后端。部署应用程序后,它在台式机、windows和macOS上运行良好。
但在移动safari上,我在尝试使用azure b2c进行api调用以获取令牌时不断出错。.net核心代码进行调用以获取令牌并从数据库返回任何其他相关数据。
我添加了应用程序洞察日志记录,并得到以下错误:
{
"headers":{
"normalizedNames":{
},
"lazyUpdate":null,
"headers":{
}
},
"status":0,
"statusText":"Unknown Error",
"url":"**********.azurewebsites.net/Auth/Token",
"ok":false,
"name":"HttpErrorResponse",
"message":"Http failure response for ***********.azurewebsites.net/Auth/Token: 0 Unknown Error",
"error":{
"isTrusted":true
}
}
这导致我的应用程序通过错误页面中的循环机制来尝试和验证。在网上无休止地搜索后,我已经确保CORS配置正确,并且设置了标题。但我真的不确定下一步该去哪里。
.net核心启动代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration["ApplicationInsights:InstrumentationKey"] ?? string.Empty);
ConfigureIoC(services);
MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new AutoMapperConfig());
});
services.AddSingleton(mappingConfig.CreateMapper());
services.AddCors();
services.AddControllersWithViews(options =>
{
options.RespectBrowserAcceptHeader = true;
}).AddNewtonsoftJson();
//Azure AD - B2C
ConfigureAuth(services);
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
IdentityModelEventSource.ShowPII = true;
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseCors(builder => {
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
spa.Options.StartupTimeout = TimeSpan.FromSeconds(200);
}
});
}
}
角度http拦截器代码:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | any> {
return next.handle(this.addTokenToRequest(request, this.authService.tokenSubject.value)).pipe(
tap(res => {
if (res instanceof HttpResponse) {
this.decreaseRequests();
}
}),
catchError(err => {
this.decreaseRequests();
if (err instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>err).status) {
case 401:
this.authService.logOut();
return;
//return this.handle401Error(request, next);
case 200:
return;
default:
return this.handleError(err);
}
} else {
this.logger.logTrace(`Interceptor: Error - ${err}`);
return throwError(err);
}
})
);
};
private decreaseRequests() {
this.totalRequests--;
}
private addTokenToRequest(request: HttpRequest<any>, token: string): HttpRequest<any> {
return request.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: 'Bearer ' + token
})
});
}
http请求:
getToken(code, codeVerifier) {
this.logger.logTrace("AuthComponent: getToken --> Start");
let request = {
code: code,
codeVerifier: codeVerifier,
scopes: this.scopes
}
this.httpService.post<IToken>(`${this.apiUrl}Auth/Token`, request).subscribe({
next: (response) => {
this.setStoredAuthInfo(response.id_token, response.refresh_token, response.id_token_expires_in.toString(), response.refresh_token_expires_in.toString());
},
complete: () => {
return true;
}
});
}
运行fiddler时,这是我的请求:小提琴图像
重新写入使用MSAL角度库进行身份验证后,错误不再发生。