gpt4 book ai didi

angular - 移动 safari : angular http call to .netcore 后端 - 0 未知错误

转载 作者:行者123 更新时间:2023-12-03 03:50:11 24 4
gpt4 key购买 nike

我有一个在 azure 中的 Web 应用程序中托管的 Angular 应用程序。它是使用 VS 中的模板和 .Net Core 后端创建的。部署应用程序后,它可以在桌面、Windows 和 macOS 上正常运行。

但是在移动 Safari 上,当尝试使用 azure b2c 进行 api 调用以获取 token 时,我不断收到错误。 .net 核心代码进行调用以获取 token 并从数据库返回任何其他关联数据。

我添加了应用程序洞察日志记录并收到以下错误:

{
"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 配置正确并设置了 header 。但我真的不知道下一步该去哪里。

.net core启动代码:

 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);
}
});
}
}

Angular 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 时,这是我的请求: fiddler-image

最佳答案

重写使用MSAL Angular库进行身份验证后,错误不再发生。

关于angular - 移动 safari : angular http call to .netcore 后端 - 0 未知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67007409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com