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

Blazor Authentication Cookie SendAsync NULL Exeption at httpContext.SignInAsync()

$
0
0

This is my Program.cs file:

using BlazorWebApp.Components;using BlazorWebApp.Services;using BLL_Shared.Models.Configurations;using DAL.Abstractions;using DAL.Implementations;using DAL.Models;using DevExpress.Blazor;using LocalizationServices.Helpers;using LocalizationServices.Implementations;using LocalizationServices.Abstractions;using StorageServices.Abstractions;using StorageServices.Helpers;using StorageServices.Implementations;using Microsoft.AspNetCore.Components.Web;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Components.Authorization;using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;using Microsoft.JSInterop;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Authentication.Cookies;namespace BlazorWebApp;public class Program{    public static void Main(string[] args)    {        var builder = WebApplication.CreateBuilder(args);        // Add services to the container.        builder.Services.AddRazorComponents()               .AddInteractiveServerComponents();        builder.Services.AddDevExpressBlazor(configure => configure.BootstrapVersion = BootstrapVersion.v5);        builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json");        // builder.Services.Configure<ConnectionModel>(builder.Configuration.GetSection("DefaultConnection").Bind());        builder.Services.AddSingleton(p => new ConnectionModel()                {                    ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection")                          ?? throw new Exception("Connection string was not found!")                });        builder.Services.AddTransient<IDBService, DapperDBService>();        builder.Services.AddTransient<IPollingService, PollingService>();        builder.Services.AddTransient<IPollingRawService, PollingRawService>();        //builder.Logging.AddFilter();        builder.Services.UseStorages(new(StoragePath: "configurations.db"));        // todo: investigate why next DI logic is not working as expected        //builder.Services.AddTransient<IStorageService>(provider => provider.GetService(typeof(IStorageService<ClientModel>)) as IStorageService);        //builder.Services.AddTransient(typeof(IStorageService), typeof(StorageService<ClientModel>));        builder.Services.AddSingleton<ILocalizationDictionaryManager, LocalizationDictionaryManager>();        builder.Services.AddSingleton<LocalizationServiceFront>();        builder.Services.AddScoped<AuthentificationSerice>();        // Add Custom Authentication State Provider and ProtectedSessionStorage        builder.Services.AddAuthorizationCore();        builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)               .AddCookie(options =>                   {                       options.Cookie.Name = "token_auth";                       options.LoginPath = "/login";                       options.Cookie.MaxAge = TimeSpan.FromHours(3); //To be determined                       options.AccessDeniedPath = "/access-denied";                   });        builder.Services.AddAuthorization();        builder.Services.AddCascadingAuthenticationState();        builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();        builder.Services.UseLocalization(new(                StoragePath: "localization.db",                SourceLocalization: "EN",                InitialLocalization: "EN"));        builder.Services.AddBlazorBootstrap();        var app = builder.Build();        // Configure the HTTP request pipeline.        if (!app.Environment.IsDevelopment())        {            app.UseExceptionHandler("/Error");        }        app.UseStaticFiles();        app.UseAntiforgery();        app.UseAuthentication();        app.UseAuthorization();        app.MapRazorComponents<App>()               .AddInteractiveServerRenderMode();        app.Run();    }}

And this is Login.Razor:

@page "/login"@using BlazorWebApp.Services@using System.Security.Claims@using Microsoft.AspNetCore.Authentication@using Microsoft.AspNetCore.Authentication.Cookies@inject AuthentificationSerice AuthService@inject NavigationManager Navigation@inject IHttpContextAccessor HttpContextAccessor<h3>Login</h3>@if(!string.IsNullOrEmpty(ErrorMessage)){<p style="color: red;">@ErrorMessage</p>}<div><label for="username">Username</label><input type="Text" @bind="Username" id="username" />@if(!IsSimpleUser){<label for="password">Password:</label><input type="password" @bind="Password" id="password" />}<div><input type="checkbox" @bind="IsSimpleUser" id="simpleUser" /><label for="simpleUser">Simple User(No Password Required)</label></div><Button @onclick="LogIn">Login</Button></div>@code {private string Username { get; set; }public string Password { get; set; }private bool IsSimpleUser { get; set; } = true;private string ErrorMessage{ get; set; }private string UserJson { get; set; }private async Task LogIn(){    var response = await AuthService.Login(Username, IsSimpleUser ? null : Password);    if(response != null)    {        UserJson = System.Text.Json.JsonSerializer.Serialize(response, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });        var claims = new List<Claim>        {            new Claim(ClaimTypes.Name, response.Username),            new Claim(ClaimTypes.Role, response.Role)        };        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);        var principal = new ClaimsPrincipal(identity);        var httpContext = HttpContextAccessor.HttpContext;        await httpContext.SignInAsync(principal);        Navigation.NavigateTo("/");    }    else    {        ErrorMessage = "Invalid username or password";    }}}

The problem is that when calling

await httpContext.SignInAsync(principal); 

I get the following outside exception:

enter image description here

I've also tried using a CustomAuthenticationStateProvider but the problem was that after the user was logged in, I was automatically redirected to an authorized view page and it was ok, he could see the authorized content, but when he refreshed the page or went to another page and than back to the authorized page he was no longer able to see the authorized content.

Now I've also tried to use local storage using JSRuntime and SecuredStorage by Microsoft but I've got too many errors on them and now I'm trying to use cookie tokens. Please help as I've really hit a wall.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



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