Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

asp.net core - Blazor hosted - authorize immediately before displaying application

Can anybody give me a helping push to get my hosted Blazor application (Client, Server and Shared) to request a login immediately, before the application is initially shown. I want the experience that a user must log in before accessing the application at all.

My starting point is the Blazor Webassembly (hosted) template with Api Authorization (Individual User Accounts)

Using the Authorize attribute on either server-side actions or a client-side Razor page will not initiate the authentication flow before the specific action/page with the Authorize attribute is being requested by the user. How would I go about having the authorization flow kicked off as the first thing, before the application is even displayed for the first time?

I am sure this is possible and even trivial for somebody more savvy than me. Can anybody give me a shove in the right direction, please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I created a control RedirectToLogin.razor

@inject NavigationManager Navigation
@code {
    protected override void OnInitialized()
    {
        String thisPage = Navigation.Uri.Replace(Navigation.BaseUri, "~/");
        Navigation.NavigateTo($"Identity/Account/Login?returnUrl={thisPage}");
        base.OnInitialized();
    }
}

And then inserted it into the mainlayout.razor

<div class="container-fluid">
 <AuthorizeView>
        <Authorized>
            <NavigationLogger />
            <ContextMenuMouseClick>
                <MenuTopBar />
                <NavMenu />
                <SubPageContainer>
                    @Body
                </SubPageContainer>
            </ContextMenuMouseClick>
        </Authorized>
        <NotAuthorized>
            <RedirectToLogin />
        </NotAuthorized>
</AuthorizeView>
</div>

So when the layout is loaded and it is in the NotAuthorized state it will redirect to the login page and after authorising will return to the page it was trying to access.

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...