0

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            // Set DB
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")
                ));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<IDBInitializer,DBInitializer>();

            services.AddAutoMapper(typeof(Startup));

            // ApiSettings
            IConfigurationSection apiSettingSection = Configuration.GetSection("APISettings");
            IConfigurationSection jwtSection = apiSettingSection.GetSection("JWTSetting");
            IConfigurationSection adminAccountSection = apiSettingSection.GetSection("AdminAccount");

            services.Configure<APISettings.AdminAccount>(adminAccountSection);
            services.Configure<APISettings.JWTSettings>(jwtSection);
            services.AddHttpContextAccessor();

            // Authentication
            var jwtSettings = jwtSection.Get<APISettings.JWTSettings>();

            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(opt =>
                {
                    opt.TokenValidationParameters = new()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = jwtSettings.ValidIssuer,
                        ValidAudience = jwtSettings.ValidAudience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.SecretKey)),
                        ClockSkew = TimeSpan.Zero,
                    };
                    opt.SaveToken = true;
                    opt.Events = new JwtBearerEvents();
                    opt.Events.OnMessageReceived = context =>
                    {
                        if (context.Request.Cookies.ContainsKey("Y-Access-Token"))
                            context.Token = context.Request.Cookies["Y-Access-Token"];

                        return Task.CompletedTask;
                    };
                })
                .AddCookie(opt =>
                {
                    opt.Cookie.SameSite = SameSiteMode.None;
                    opt.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                    opt.Cookie.IsEssential = false;
                });

            // DI
            services.AddTransient<IAccountRepository, AccountRepository>();
            services.AddTransient<ILoggingRepository, LoggingRepository>();

            // controller & swagger & Cors
            services.AddCors(o => o.AddPolicy("AutoTrading", builder =>
            {
                builder.WithOrigins("https://localhost:7096").AllowAnyMethod().AllowAnyHeader().AllowCredentials();
            }));
            services.AddControllers();
            services.AddRouting(opt => opt.LowercaseUrls = true);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Description = "Please insert JWT with Bearer into field",
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                   {
                     new OpenApiSecurityScheme
                     {
                       Reference = new OpenApiReference
                       {
                         Type = ReferenceType.SecurityScheme,
                         Id = "Bearer"
                       }
                      },
                      new string[] { }
                    }
                  });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IDBInitializer dBInitializer ,ILoggerFactory loggerFactory)
        {
            var serviceProvider = app.ApplicationServices.CreateScope().ServiceProvider;
            var dbContext = serviceProvider.GetRequiredService<ApplicationDbContext>();
            var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
            loggerFactory.AddProvider(new CustomLoggerProvider(dbContext, httpContextAccessor));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
            }
            dBInitializer.Initilize();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseCors("AutoTrading");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

loginController.cs

[AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginAsync([FromBody] UserAuthRequestDTO authRequestDTO)
        {
            var responseDTO = await _accountRepository.LoginAsync(authRequestDTO);

            if (responseDTO.IsSucceeded)
            {
                Response.Cookies.Append("Y-Access-Token", responseDTO.Token, new CookieOptions() {HttpOnly = true, Expires=DateTime.Now.AddMinutes(5)});
                return Ok(responseDTO);
            }

            return BadRequest(responseDTO);
        }

When I using blazor client try Login, cookie is null. (cookie is not setted) When I using swagger try Login, it's cookie is setted correctly.

my RestApi is https://localhost:1234, and Blazor wasm is https://localhost:3456

is cookie can not setted to the other URL? Should I set cookie at Blazor client with javascript?

thank you.

Swagger Cookie

Blazor Cookie

  • as referred by [this](https://stackoverflow.com/questions/49317304/asp-net-core-2-1-session#answer-51654203) please mark the cookie as `IsEssential = true;` – Modar Na Sep 28 '21 at 10:30

0 Answers0