dotnet / dotnet/aspnetcore

Exception triggered by AuthorizeAttribute on the first page loaded in a circuit

Open
#55,678 10 comments 0 reactions 0 assignees View on GitHub
area-blazor bug feature-blazor-server feature-blazor-server-auth
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

To learn how auth works in Blazor, I'm writing a minimal implementation from scratch. In the process, I've encountered a strange error.

If the first page loaded in a circuit *does not* have `[Authorize]`, everything works perfectly. You can freely navigate to a page that does have `[Authorize]`, and the page is displayed as expected. That is, you get either the page content or a "not authorized" message depending on whether the user is authenticated.

However, if the first page loaded in a circuit *does* have `[Authorize]`, then the app crashes with an error about not being able to find an `IAuthenticationService`.

This only affects `AuthorizeAttribute`. There is no error if the first page loaded in the circuit contains an ``.

### Expected Behavior

`AuthorizeAttribute` should have the same effect on the first page loaded in a circuit as it does on subsequent pages.

### Steps To Reproduce

This repo contains the Blazor Web App template and my changes in separate commits for easy review. The README contains instructions for an easy way to see the problem.

https://github.com/kjkrum/BlazorAuthWtf

### Exceptions (if any)

```
System.InvalidOperationException: Unable to find the required 'IAuthenticationService' service. Please add all the required services by calling 'IServiceCollection.AddAuthentication' in the application startup code.

at Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.GetAuthenticationService(HttpContext context)

at Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.ChallengeAsync(HttpContext context)

at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<g__Handle|0>d.MoveNext()

--- End of stack trace from previous location ---

at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)

at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
```

### .NET Version

8.0

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.