简体   繁体   中英

How can I call '/Identity/Account/ExternalLogin' from a Blazor component?

My goal is to have the external provider buttons (exactly like the foreach from the /Identity/Account Login and Register pages, see below) in a Blazor component. I am using the "Blazor Server App" template.

I have successfully pulled in the external providers, enumerated buttons, and have a form with the same action as the default identity login page. My external login is with Twitter and is confirmed working on the default page.

<form action="/Identity/Account/ExternalLogin" method="post">
    @foreach (var provider in ExternalLogins)
    {
        <button type="submit" class="btn btn-primary btn-lg form-control" name="provider" 
value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
    }
</form>

When I use the button to login from the blazor component, the debug window shows a Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException being thrown. My only guess is that this is because the navigation is not initiating from one of the built-in identity pages that probably have Antiforgery elements. How do I directly navigate to this ExternalLogin page without the middle-man login/register page?

Calling the /Identity/Account/ExternalLogin page means taking care of anti-CSRF mechanism (HTTP header and form's hidden field) and it's not easy to implement.
Instead of directly call /Identity/Account/ExternalLogin it's easier to customize the login page:

Starting from the default blazor template with authentication (wasm or server), scaffold Identity items, depending of what you need, but at least the login page and external login pages to customize them.

Select the Areas folder and right click to open the contextual menu. The choose Add -> New Scaffolded Item...

在此处输入图像描述

Choose Identity and click Add.

在此处输入图像描述

Select your Identity data context class and what you want to scaffold.

在此处输入图像描述

Update Areas/Identity/Pages/Account/Login.cshtml for your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM