Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How to Implement Cookies using HttpClient in Blazor

$
0
0

I'm facing some issues with authentication in Blazor when using the HTTP client to send requests to my API controller. Specifically, the cookie isn't appearing on the application or in the Cookies when inspecting. I'm not very familiar with using authentication in Blazor, but I did try using a regular form and it worked fine - the cookie was added and the user became authenticated.

However, when I checked the authentication state, the user was not authenticated. I attempted to create a simple example with the API controller.

 [ApiController] [Route("/Api")] public class Controller:ControllerBase  {       [HttpPost]    [Route("Login")]    public async Task<IActionResult> Login()    {        var userClaims = new[] { new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()) };        var identity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);        var principal = new ClaimsPrincipal(identity);        var props = new AuthenticationProperties        {            ExpiresUtc = DateTime.UtcNow.AddMinutes(30),            AllowRefresh = true,            IsPersistent = true        };        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props);        return Ok();    }}

the login method where the http client makes the request :

private async Task Login()  {      var handler = new HttpClientHandler      {          UseCookies = true,          CookieContainer = new CookieContainer()      };      HttpClient httpClient = new HttpClient(handler);    var response =await httpClient.PostAsync($"{_manager.BaseUri}Api/Login", null);    var content = await response.Content.ReadAsStringAsync();    var cookies = handler.CookieContainer.GetCookies(new Uri(_manager.BaseUri));    var auth=await state.GetAuthenticationStateAsync();   var users= auth.User.Claims;  }

my program.cs

using BlazorApp4.Components;using Microsoft.AspNetCore.Authentication.Cookies;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddRazorComponents()    .AddInteractiveServerComponents();builder.Services.AddHttpClient("MyHttpClient", client =>{    client.Timeout = TimeSpan.FromMinutes(3); });builder.Services.AddControllers();builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)    .AddCookie(options =>    {        options.Cookie.HttpOnly = true;        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;         options.Cookie.SameSite = SameSiteMode.Lax;         options.ExpireTimeSpan = TimeSpan.FromMinutes(30);        options.LoginPath = "/Login";    });builder.Services.AddAuthorization();var app = builder.Build();// Configure the HTTP request pipeline.if (!app.Environment.IsDevelopment()){    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.UseAuthentication();app.UseAuthorization();app.UseHttpsRedirection();app.MapControllers();app.MapControllerRoute("Login", "Api/Login");app.UseStaticFiles();app.UseAntiforgery();app.MapRazorComponents<App>()    .AddInteractiveServerRenderMode();app.Run();

one more thing when making request straight from an html form it works as expected and the cookie gets added , the user also is authenticated

Tried some answers from chat got none of them work


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>