why Net core return 0 to angular?

Viewed 68

I have an app with angular and net core web api 3. The problem I have is that when the token expires in angular I get a status code 0, but when using postman it effectively returns the code 401 (unauthorized). What could be happening? Thank you very much for your help.

enter image description here

Start.cs

public void ConfigureServices(IServiceCollection services)
    {
        var appSettingsJson = AppSettingsJson.GetAppSettings();
        var tokenKey = appSettingsJson["Token:Key"];
        services.AddMvc()
               .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
               .AddNewtonsoftJson(ConfigureJson).AddExtensions();
        services.AddSignalR();
        services.AddCors(options =>
        {
            options.AddPolicy("EnableCORS", builder => { builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod(); });
            options.AddPolicy("NoRestrictions", builder => { builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod(); });
        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
         .AddJwtBearer(options =>
         {
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 ValidateIssuer = true,
                 ValidateAudience = true,
                 ValidateLifetime = true,
                 ValidateIssuerSigningKey = true,
                 ValidIssuer = "http://localhost:5000",
                 ValidAudience = "http://localhost:5000",
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey))
             };
         });
        services.AddControllers();
    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
        else app.UseHsts();
        app.Use(async (ctx, next) =>
        {
            await next();
            if (ctx.Response.StatusCode == 204)
            {
                ctx.Response.ContentLength = 0;
            }
        });
        app.UseRouting();
        app.UseAuthorization();
        app.UseCors("EnableCORS");
        app.UseAuthentication();
        app.UseHttpsRedirection();
        //app.UseMvc();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotifyHub>("notify").RequireCors("EnableCORS");
            endpoints.MapHub<NotifyActionHub>("notifyaction").RequireCors("EnableCORS");
        });
    }
1 Answers

I could solve it. I did it was to change the position of the services.AddCors and app.UseCors ("EnableCORS") instructions; to the front line and it worked perfectly.

 public void ConfigureServices(IServiceCollection services)
    {
        var appSettingsJson = AppSettingsJson.GetAppSettings();
        var tokenKey = appSettingsJson["Token:Key"];
        *services.AddCors(options =>
        {
            options.AddPolicy("EnableCORS", builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); });
        });*
        services.AddMvc()
               .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
               .AddNewtonsoftJson(ConfigureJson).AddExtensions();
        services.AddSignalR();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
         .AddJwtBearer(options =>
         {
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 ValidateIssuer = true,
                 ValidateAudience = true,
                 ValidateLifetime = true,
                 ValidateIssuerSigningKey = true,
                 ValidIssuer = "http://localhost:5000",
                 ValidAudience = "http://localhost:5000",
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey))
             };
         });
        services.AddControllers();
    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
        else app.UseHsts();
        app.UseCors("EnableCORS");

        app.Use(async (ctx, next) =>
        {
            await next();
            if (ctx.Response.StatusCode == 204)
            {
                ctx.Response.ContentLength = 0;
            }
        });
        app.UseRouting();
        app.UseAuthorization();
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers().RequireCors("EnableCORS");
            endpoints.MapHub<NotifyHub>("notify").RequireCors("EnableCORS");
            endpoints.MapHub<NotifyActionHub>("notifyaction").RequireCors("EnableCORS");
        });

    }
Related