I'm working on a project in .NET C# with role-based authorization on specific pages, but after logging user in i can't access authorized pages. I also cannot find any cookie files in browser.I've tried to watch some yt tutorials and help myself by chatGpt but I still cannot manage to make it work.
My program.cs
using Microsoft.AspNetCore.Identity;using Microsoft.EntityFrameworkCore;using PZP.Components;using PZP.Domain.Entities;using PZP.Infrastructure.Repositories;using PZP.Infrastructure;using PZP.Services;using Microsoft.AspNetCore.Authentication.JwtBearer;using PZP.Application.Models;using Microsoft.AspNetCore.Components.Authorization;using PZP.Services.Interfaces;using System.Net;using System.Text;using Microsoft.IdentityModel.Tokens;using System.Security.Claims;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddRazorComponents().AddInteractiveServerComponents();builder.Services.AddCascadingAuthenticationState();builder.Services.AddRazorPages();builder.Services.AddAuthorization();builder.Services.AddScoped\<ProceedingRepository\>();builder.Services.AddScoped\<UserRepository\>();builder.Services.AddScoped\<CompanyRepository\>();builder.Services.AddScoped\<UserService\>();builder.Services.AddScoped\<CompanyService\>();builder.Services.AddScoped\<AuthService\>();builder.Services.AddScoped\<IEmailService, EmailService\>();builder.Services.AddSingleton\<UserRegistrationState\>();builder.Services.AddAntDesign();builder.Services.AddDbContext\<PzpDbContext\>(options =\>options.UseSqlServer(builder.Configuration.GetConnectionString("PZP_Test"),b =\> b.MigrationsAssembly("PZP.Infrastructure")));builder.Services.AddSingleton\<HttpClient\>(ProviderAliasAttribute =\>{var client = new HttpClient{BaseAddress = new Uri(builder.Configuration\["ApiBaseAddress"\])};return client;});builder.Services.AddIdentity\<User, IdentityRole\>().AddEntityFrameworkStores\<PzpDbContext\>().AddDefaultTokenProviders();var emailConfig = builder.Configuration.GetSection("EmailConfiguration").Get\<EmailConfigurationModel\>();builder.Services.AddSingleton(emailConfig);builder.Services.Configure\<IdentityOptions\>(opts =\> opts.SignIn.RequireConfirmedEmail = true);builder.Services.AddEndpointsApiExplorer();builder.Services.AddHostedService\<ProceedingService\>();builder.Services.ConfigureApplicationCookie(options =\>{options.Cookie.HttpOnly = true;options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Lax; options.LoginPath = "/login"; options.LogoutPath = "/logout"; options.AccessDeniedPath = "/access-denied"; options.SlidingExpiration = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(600); });var app = builder.Build();app.UseHttpsRedirection();app.Use(async (context, next) =\>{Console.WriteLine($"Request Path: {context.Request.Path}, Method: {context.Request.Method}");context.Response.OnStarting(() =\>{Console.WriteLine($"Response Starting: {context.Response.StatusCode} for {context.Request.Path}");return Task.CompletedTask;});await next();Console.WriteLine($"Response Completed: {context.Response.StatusCode} for {context.Request.Path}");});if (!app.Environment.IsDevelopment()){app.UseExceptionHandler("/Error");app.UseHsts();}app.Use(async (context, next) =\>{var authHeader = context.Request.Headers\["Authorization"\].ToString();if (!string.IsNullOrEmpty(authHeader)){Console.WriteLine($"Authorization Header: {authHeader}");}await next();});app.UseStaticFiles();app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseAntiforgery();app.UseEndpoints(endpoints =\>{endpoints.MapControllers();endpoints.MapRazorPages();endpoints.MapRazorComponents\<App\>().AddInteractiveServerRenderMode();});app.Run();AuthService
using System.Net.Http.Json;using Microsoft.AspNetCore.Components.Authorization;using PZP.Application.Models;using PZP.Services;public class AuthService{ private readonly HttpClient _httpClient; public AuthService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<bool> LoginAsync(LoginModel loginModel) { var response = await _httpClient.PostAsJsonAsync("api/auth/login", loginModel); return response.IsSuccessStatusCode; } public async Task LogoutAsync() { await _httpClient.PostAsync("api/auth/logout", null); }}AuthController
using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;using PZP.Application.Models;using PZP.Domain.Entities;using PZP.Services.Interfaces;using System.Security.Claims;[ApiController][Route("api/[controller]")]public class AuthController : ControllerBase{ private readonly SignInManager<User> _signInManager; private readonly UserManager<User> _userManager; private readonly IEmailService _emailService; public AuthController( SignInManager<User> signInManager, UserManager<User> userManager, IEmailService emailService) { _signInManager = signInManager; _userManager = userManager; _emailService = emailService; } [HttpPost("Login")] public async Task<IActionResult> Login([FromBody] LoginModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password)) { return Unauthorized("Invalid email or password."); } if (!await _userManager.IsEmailConfirmedAsync(user)) { return Unauthorized("Email not confirmed."); } await _signInManager.SignInAsync(user, isPersistent: true); return Ok(); } [HttpPost("Logout")] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return Ok(); } [HttpGet("ConfirmEmail")] public async Task<IActionResult> ConfirmEmail(string token, string email) { var user = await _userManager.FindByEmailAsync(email); if (user != null) { var result = await _userManager.ConfirmEmailAsync(user, token); if (result.Succeeded) { return StatusCode(StatusCodes.Status200OK); } } return StatusCode(StatusCodes.Status500InternalServerError); }}LoginPage
@page "/login"@using PZP.Application.Models@using PZP.Services@inject AuthService AuthService@inject NavigationManager Navigation@code { [Parameter] public bool IsVisible { get; set; } [Parameter] public EventCallback<bool> IsVisibleChanged { get; set; } [Parameter] public EventCallback OnLoginSuccess { get; set; } private LoginModel loginModel = new LoginModel(); private void CloseModal() { IsVisible = false; IsVisibleChanged.InvokeAsync(false); } private async Task LoginAsync() { bool loginSuccess = await AuthService.LoginAsync(loginModel); if (loginSuccess) { await OnLoginSuccess.InvokeAsync(); CloseModal(); StateHasChanged(); } else { Console.WriteLine("Nieudane logowanie. Sprawdź adres e-mail i hasło."); } }}@if (IsVisible){<div class="modal-wrapper"><div class="modal fade show d-block" tabindex="-1" style="background-color: rgba(0,0,0,0.5);"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Logowanie</h5><button type="button" class="close" aria-label="Close" @onclick="CloseModal"><span aria-hidden="true">×</span></button></div><div class="modal-body"><div class="form-group"><label for="email">E-mail</label><input type="email" class="form-control" id="email" placeholder="Wpisz e-mail" @bind="loginModel.Email"></div><div class="form-group"><label for="password">Hasło</label><input type="password" class="form-control" id="password" placeholder="Wpisz hasło" @bind="loginModel.Password"></div><div class="form-group form-check"><input type="checkbox" class="form-check-input" id="rememberMe" @bind="loginModel.RememberMe"><label class="form-check-label" for="rememberMe">Zapamiętaj mnie</label></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" @onclick="CloseModal">Zamknij</button><button type="button" class="btn btn-primary" @onclick="LoginAsync">Zaloguj się</button></div></div></div></div></div>}