5

I'd like to use Open ID Connect with Identity Server 4 for authorization in my server side Blazor application. I've got the same setup working in a MVC application.

With the newest .NET Core version, 3.0 Preview 6, it is possible to add the attribute ´@attribute [Authorize]´ to a site. But if I'm not authorized, I don't get redirected to the Identity Server to log in, as I am used from my MVC applications. Instead the site only shows the message "Not authorized".

In Startup.cs I've got the following setup:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.Authority = "http://localhost:5000";
            options.RequireHttpsMetadata = false;

            options.ClientId = "myClient";
            options.SaveTokens = true;
        });

and

        app.UseAuthentication();

How do I tell the application, that I want to be redirected to the Identity Server if I'm not logged in?

EDIT: Codevisions answer works as a workaround. I found pending github issues here and here, planned for .NET Core 3.0 Preview 7 that will possibly cover this issue officially.

Pascal R.
  • 2,024
  • 1
  • 21
  • 35

1 Answers1

4

Add to ConfigureServices code below.

services.AddMvcCore(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});
codevision
  • 5,165
  • 38
  • 50
  • Server Side Blazor a.k.a Razor Components doesn't require controllers because the client and the server communicate over SignalR. I would have to create a dummy controller just for this. – Pascal R. Jun 14 '19 at 07:25
  • I agree with you. It seem not obvious, but no actual controllers needed. I manage to simplify that just to adding AddMvcCore instead of AddcontrollersWithView. I base my reply based on sample created by MS and it actually working. – codevision Jun 14 '19 at 11:42
  • You're right, I eventually got it working this way. I'm still not fond of the fact that I have to include MVC but I guess it's the only way until they provide an official soultion. Thanks for the help! – Pascal R. Jun 17 '19 at 08:24