Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exception rendering component: Could not find 'AuthenticationService' in 'window'

Tags:

c#

blazor

I want to redirect unauthorized user to login page if user try to reach authorized pages. So far i wrote this using this tutorial. Project builded succesfully. But browser threw this error

Unhandled exception rendering component: Could not find 'AuthenticationService' in 'window'

And pages stuck on authorizing

<Authorizing>
  <div class="main">Please wait...</div>
</Authorizing>

All pages print "Please Wait ..." How can i fix this error?

App.Razor

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <RedirectToLogin />
            </NotAuthorized>
            <Authorizing>
                <div class="main">Please wait...</div>
            </Authorizing>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

_Imports.Razor

@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using Kermes.Client
@using Kermes.Client.Shared
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Blazorise

Program.cs

public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.Services
                  .AddBlazorise(options =>
                  {
                      options.ChangeTextOnKeyPress = true;
                  })
                  .AddBootstrapProviders()
                  .AddFontAwesomeIcons();
            builder.Services.AddSingleton(new HttpClient
            {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });
            builder.RootComponents.Add<App>("app");
            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            builder.Services.AddApiAuthorization(options => {
                options.AuthenticationPaths.LogInPath = "auth/login";
                options.AuthenticationPaths.LogInCallbackPath = "auth/login-callback";
                options.AuthenticationPaths.LogInFailedPath = "auth/login-failed";
                options.AuthenticationPaths.LogOutPath = "auth/logout";
                options.AuthenticationPaths.LogOutCallbackPath = "auth/logout-callback";
                options.AuthenticationPaths.LogOutFailedPath = "auth/logout-failed";
                options.AuthenticationPaths.LogOutSucceededPath = "auth/logged-out";
                options.AuthenticationPaths.ProfilePath = "auth/profile";
                options.AuthenticationPaths.RegisterPath = "auth/register";
            });

            var host = builder.Build();
            host.Services
              .UseBootstrapProviders()
              .UseFontAwesomeIcons();

            await host.RunAsync();
        }
    }

Counter.cs

@page "/counter"
@attribute [Authorize]
<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

Server/Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using KermesAPI.Helpers;
using KermesAPI.Services;
using AutoMapper;
using System;

namespace Kermes.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>();
            services.AddAuthentication();
            services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.IgnoreNullValues = true);
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddSwaggerGen();

            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddScoped<IAccountService, AccountService>();
            services.AddScoped<IEmailService, EmailService>();
            services.AddControllersWithViews();
            services.AddRazorPages();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }
}
like image 819
MuhammedBalta Avatar asked Jul 30 '20 21:07

MuhammedBalta


1 Answers

Try this instead:

<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>

I had the same problem. Adding the above Script-Reference in the index.html file in the Blazor client project fixed it for me.

like image 71
mo74 Avatar answered Nov 11 '22 08:11

mo74