簡體   English   中英

帶有Windows身份驗證角度應用程序的.Net核心出現錯誤

[英].Net core with windows authentication angular app gets error

我在 web api .net5 (.net core) 中編寫了一個服務,我使用 windows authentication=true 因為我需要當前用戶的詳細信息。 但是當“windowsAuthentication”:true,“anonymousAuthentication”:false 時,我的 Angular 應用程序無法訪問該服務並返回 unauthorize 錯誤:401 Unauthorized for options 和在控制台中:

Access to XMLHttpRequest at 'https://localhost:44343/api/smooss' from origin 'http://localhost:4200' has been blocked by CORS

當我設置“anonymousAuthentication”時:true 它確實有效,但我沒有用戶的詳細信息

我的代碼如下所示:

客戶:

 public CheckISAuthorized() {
    
    const  requestOptions = {
      headers: new HttpHeaders({
       'Authorization': "my-request-token",
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
      })
     };
      
        return this.http.get(`${baseUrl}smooss`,requestOptions );
      }}
    
i have interceptor that adds withCredentials=true:
   

      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
               debugger;
                request = request.clone({
                    withCredentials: true
                    
                });
        
                return next.handle(request);
            }

in server:
startup.cs:
 

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContextPool<SMOOSSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SmoosDB")));
              
                services.AddControllers();
                services.AddScoped<ISmooseRepository, SmoosRepository>();
                services.AddAuthentication(IISDefaults.AuthenticationScheme);
                services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                           .AllowAnyMethod()
                           .AllowAnyHeader()
                            .AllowCredentials();
                }));
    
               
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Smoos", Version = "v1" });
                });
                services.AddSingleton<IAuthorizationHandler, AppSmoossRequirement>();
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("AppSmooss", policy => policy.Requirements.Add(new AppSmoossRequirement()));
                });
                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
               
            }
    
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseSwagger();
                    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Smoos v1"));
                }
                
                app.UseRouting();
                app.UseAuthentication();
                app.UseCors("MyPolicy");
                app.UseHttpsRedirection();
                app.UseAuthorization();
               
              }
in controller:
   

     [EnableCors("MyPolicy")]
            [Authorize(Policy = "AppSmooss")]
            [Route("api/smooss")]
            [ApiController]
            public class SmoossApi : ControllerBase
this is the method:
   

      [HttpGet]
                public async Task<List<Smooss>> Get()
                {
        
                    return await SmoosRepository.GetFlights();
                }

所以最后我找到了解決方案,感謝 Rena 對這篇文章的評論:github.com/aspnet/CORS/issues/60 問題是來自瀏覽器的選項調用沒有與憑據一起發送,這就是它未經授權的原因。 解決方案是添加一個中間件來處理選項請求並允許 Windows 和匿名身份驗證,以便選項請求將成功

中間件:

 public async Task Invoke(HttpContext context)
    {
        if (context.Request.Method != "OPTIONS" && 
       !context.User.Identity.IsAuthenticated)
        {
            context.Response.StatusCode = 401;
            return; //Stop pipeline and return immediately.
        }
        await _next(context);
    }

在launchSettings.json 中:

"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true ,

我還必須刪除客戶端的授權標頭:

      const  requestOptions = {
      headers: new HttpHeaders({
//this line  is not needed
      // 'Authorization': "my-request-token",
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
      })
      };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM