William Stephenson
William Stephenson

Reputation: 21

Blazor Server App error when logging out after adding authorize attribute

I am deep into making my blazor server app and I wanted to add the attribute authorize to all my pages to make sure my wep app is secure, exluding the login page. However now that I have added this code to my pages whenever I go to logout when on the pages I added the attribute too I get this error:

(Tried to logout when on the account manage page) This localhost page can’t be foundNo webpage was found for the web address: https://localhost:7123/Account/Login?ReturnUrl=%2FAccount%2FManage

I need to mention a few things, I havent added the attriute authorize to the home page and if I click the logout button when on the home page I am logged out fine it is just all the other pages. I also cannot find the Logout file in my project solution anywhere.

Here is the logout button code on the Navmenu:

<div class="nav-item px-3">
    <form action="Account/Logout" method="post">
        <AntiforgeryToken />
        <input type="hidden" name="ReturnUrl" value="@currentUrl" />
        <button type="submit" class="nav-link">
            <span class="bi bi-arrow-bar-left-nav-menu" aria-hidden="true"></span> Logout
        </button>
    </form>
</div>

And I simply added this line of code: @attribute [Authorize]

I would try to find a solution myself but i cant even find the logout page so i dont even know where to start. I have tried searching for it.

Any help appreciated

Upvotes: 1

Views: 201

Answers (2)

William Stephenson
William Stephenson

Reputation: 21

I figured it out you need to go to the IdentityComponentsEndpointRouteBuilderExtensions.cs file under the account directory. Then you fill find this code with a map post method. I simply removed the ReturnUrl parameter and had it redirect me to the home page manually.

 accountGroup.MapPost("/Logout", async (ClaimsPrincipal user, SignInManager<ApplicationUser> signInManager) =>
 {
     await signInManager.SignOutAsync();
     return TypedResults.LocalRedirect($"~/");
 });

Upvotes: 0

Saboora Roomi
Saboora Roomi

Reputation: 1

The logout button sends a POST request to Account/Logout, and you've set ReturnUrl to @currentUrl. When you log out from an authorized page, the app might be trying to redirect back to the same page that now requires authentication, leading to a loop or an error page because the user is no longer authenticated.Instead of redirecting back to the current URL after logout, redirect to a public page (e.g., the home page or login page). You can modify the ReturnUrl in the form to point to a known public page:

<form action="Account/Logout" method="post">
<AntiforgeryToken />
<input type="hidden" name="ReturnUrl" value="/" /> <!-- Redirect to home or login page -->
<button type="submit" class="nav-link">
    <span class="bi bi-arrow-bar-left-nav-menu" aria-hidden="true"></span> Logout
</button>

Upvotes: 0

Related Questions