Я пытаюсь выйти из системы, однако файл cookie не становится недействительным. Вместо этого я просто получаю перенаправление на указанный путь и по-прежнему могу получить доступ ко всему.
Функция onLogin в контроллере с SignInAsync работает нормально.
Когда Я вхожу в него при отладке, значение ControllerBase.HttpContext.User.Identity.IsAuthenticated всегда ложно.
Program.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using MudBlazor.Services;
using PersonalWebsiteRedesign.Classes.Database;
using PersonalWebsiteRedesign.Components;
using System.Net;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.AddDbContext();
builder.Services.AddControllers();
builder.Services.AddMudServices();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped(sp => new HttpClient(new HttpClientHandler
{
UseCookies = true,
Credentials = CredentialCache.DefaultCredentials
})
{
BaseAddress = new Uri("https://localhost:7043/")
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "fslr_auth";
options.AccessDeniedPath = "/error";
options.LogoutPath = "/user/logout";
options.LoginPath = "/user/login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.IsEssential = true;
options.Cookie.Path = "/";
options.SlidingExpiration = true;
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Cookies", policy => policy.RequireAuthenticatedUser());
});
builder.Services.AddSingleton();
builder.Services.AddCascadingAuthenticationState();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorComponents()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(PersonalWebsiteRedesign.Client._Imports).Assembly);
app.MapControllers();
app.Run();
AuthController.cs
[ApiController]
public class AuthController : ControllerBase
{
SQL_DB_Context dbContext;
public AuthController(SQL_DB_Context _dbContext)
{
dbContext = _dbContext;
}
[HttpPost]
[Route("api/auth/login")]
public async Task onLogin([FromBody] LoginUserForm loginUserForm)
{
if (loginUserForm != null && dbContext.Users.Any(x => x.username == loginUserForm.UserName))
{
var userid = dbContext.Users.Where(x => x.username == loginUserForm.UserName).FirstOrDefault().id;
var roleid = dbContext.UserRoles.Where(x => x.id == userid).FirstOrDefault().roleId;
var roleToString = dbContext.RolesList.Where(x => x.id == roleid).FirstOrDefault().Role;
var claims = new List
{
new Claim(ClaimTypes.Name, loginUserForm.UserName),
new Claim(ClaimTypes.Role, roleToString)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return this.Ok();
} else
{
return this.BadRequest();
}
}
[HttpPost]
[Route("api/auth/logout")]
public async Task onLogout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return this.Ok();
}
Logout.razor
page "/user/logout"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Http
@using System.Net
@rendermode InteractiveServer
@attribute [Authorize]
@inject NavigationManager navManager
@inject HttpClient HttpClient
@inject IHttpContextAccessor httpContextAccessor
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
await onLogout();
}
}
private async Task onLogout()
{
var baseAddress = new Uri(navManager.BaseUri);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var result = await client.PostAsync("api/auth/logout", null, CancellationToken.None);
if (result.IsSuccessStatusCode)
{
navManager.NavigateTo("/user/login", true);
Console.WriteLine("Logged out user: " + httpContextAccessor.HttpContext.User.Identity.Name + ", Status: " + httpContextAccessor.HttpContext.User.Identity.IsAuthenticated);
}
else
{
Console.WriteLine("Couldn't logout user.");
}
var x = "";
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... ate-cookie
Контроллер .Net Blazor HttpContext.SignOutAsync() не делает файл cookie недействительным ⇐ C#
Место общения программистов C#
1729502350
Anonymous
Я пытаюсь выйти из системы, однако файл cookie не становится недействительным. Вместо этого я просто получаю перенаправление на указанный путь и по-прежнему могу получить доступ ко всему.
Функция onLogin в контроллере с SignInAsync работает нормально.
Когда Я вхожу в него при отладке, значение ControllerBase.HttpContext.User.Identity.IsAuthenticated всегда ложно.
[b]Program.cs[/b]
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using MudBlazor.Services;
using PersonalWebsiteRedesign.Classes.Database;
using PersonalWebsiteRedesign.Components;
using System.Net;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.AddDbContext();
builder.Services.AddControllers();
builder.Services.AddMudServices();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped(sp => new HttpClient(new HttpClientHandler
{
UseCookies = true,
Credentials = CredentialCache.DefaultCredentials
})
{
BaseAddress = new Uri("https://localhost:7043/")
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "fslr_auth";
options.AccessDeniedPath = "/error";
options.LogoutPath = "/user/logout";
options.LoginPath = "/user/login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.IsEssential = true;
options.Cookie.Path = "/";
options.SlidingExpiration = true;
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Cookies", policy => policy.RequireAuthenticatedUser());
});
builder.Services.AddSingleton();
builder.Services.AddCascadingAuthenticationState();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorComponents()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(PersonalWebsiteRedesign.Client._Imports).Assembly);
app.MapControllers();
app.Run();
[b]AuthController.cs[/b]
[ApiController]
public class AuthController : ControllerBase
{
SQL_DB_Context dbContext;
public AuthController(SQL_DB_Context _dbContext)
{
dbContext = _dbContext;
}
[HttpPost]
[Route("api/auth/login")]
public async Task onLogin([FromBody] LoginUserForm loginUserForm)
{
if (loginUserForm != null && dbContext.Users.Any(x => x.username == loginUserForm.UserName))
{
var userid = dbContext.Users.Where(x => x.username == loginUserForm.UserName).FirstOrDefault().id;
var roleid = dbContext.UserRoles.Where(x => x.id == userid).FirstOrDefault().roleId;
var roleToString = dbContext.RolesList.Where(x => x.id == roleid).FirstOrDefault().Role;
var claims = new List
{
new Claim(ClaimTypes.Name, loginUserForm.UserName),
new Claim(ClaimTypes.Role, roleToString)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return this.Ok();
} else
{
return this.BadRequest();
}
}
[HttpPost]
[Route("api/auth/logout")]
public async Task onLogout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return this.Ok();
}
[b]Logout.razor[/b]
page "/user/logout"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Http
@using System.Net
@rendermode InteractiveServer
@attribute [Authorize]
@inject NavigationManager navManager
@inject HttpClient HttpClient
@inject IHttpContextAccessor httpContextAccessor
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
await onLogout();
}
}
private async Task onLogout()
{
var baseAddress = new Uri(navManager.BaseUri);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var result = await client.PostAsync("api/auth/logout", null, CancellationToken.None);
if (result.IsSuccessStatusCode)
{
navManager.NavigateTo("/user/login", true);
Console.WriteLine("Logged out user: " + httpContextAccessor.HttpContext.User.Identity.Name + ", Status: " + httpContextAccessor.HttpContext.User.Identity.IsAuthenticated);
}
else
{
Console.WriteLine("Couldn't logout user.");
}
var x = "";
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79107013/net-blazor-controller-httpcontext-signoutasync-does-not-invalidate-cookie[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия