tvb108108
tvb108108

Reputation: 408

How to show a user authenticated, but not authorized in the Nav Menu in Blazor

I'm working on a new application in Blazor. I have asp.net identity setup and working.

Is there a way to be authenticated, but not authorized?

For example, initially we are requiring users to register, but are not adding their roles until we manually add them.

So the user could be authenticated by entering the correct user name and password, but has no roles, so there would be no menu items.

Is there a way to do this in Blazor razor with asp.net identity?

<AuthorizeView Roles="@X.Shared.Constants.AspNetRolesConstants.Administrator.ToString()">
    <Authorized>
        <h3>Welcome to X Research!</h3>
    </Authorized>
    <NotAuthorized>
        <h3>Welcome to X Research!</h3>
        <br />
        Please Log in!
        <br /><br />
        (If you are returned to this page, please contact an Administrator to have roles added for your account!)
    </NotAuthorized>
</AuthorizeView>

I read this article, but it doesn't seem to do what I want to do.

Thanks.

Update

When I use the above AuthorizeView etc., then when you are not logged in, I see this:

enter image description here

So I would rather not show 'Not Authorized' on the main Index.razor page if they need to log in.

Maybe there is a way to redirect to my Login page if they are not authenicated?

Upvotes: 0

Views: 1468

Answers (2)

tvb108108
tvb108108

Reputation: 408

@David let me do the correct answer:

The key was adding @attribute [AllowAnonymous] so it allows past the build in authentication. If I do not put this, it will say 'Not Authorized'

Here is my full code:

@page "/"
@inject NavigationManager navigationManager;
@attribute [AllowAnonymous]

 <h3>Welcome to Research!</h3>

@code{

    [CascadingParameter] protected Task<AuthenticationState> AuthStat { get; set; }

    protected async override Task OnInitializedAsync()
    {
        base.OnInitialized();
        var user = (await AuthStat).User;

        if (user.Identity == null)
        {
            throw new GenericException("user is null");
        }

        if(!user.Identity.IsAuthenticated)
        {
            navigationManager.NavigateTo("/Identity/Account/Login", true);
        }
    }
}

Upvotes: 1

David
David

Reputation: 150

Yes you can redirect to other Pages just inject the NavigationManager:

@inject NavigationManager NavManager

<h1>Redirect Page</h1>

<p>Redirecting to Default Page</p>

@code {
    protected override void OnInitialized()
    {
        NavManager.NavigateTo("/");
    }
}

Upvotes: 1

Related Questions