Yes, it is possible to have the buttons in your razor page.
Of course, to do this, you need to be able to enumerate the available providers, which means you need to pass them in to your Blazor application from
_Host.cshtml (or wherever you host the Blazor application)
note: you cannot pass a list of AuthenticationScheme
because .NET will not serialise them, which is why I transform them into a DTO ExternalProvider
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@inject SignInManager<IdentityUser> _signInManager
@{
var state = new InitialApplicationState
{
XsrfToken = Xsrf.GetAndStoreTokens(HttpContext).RequestToken,
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
.ToList()
.Select(scheme=>
new ExternalProvider {Name=scheme.Name, DisplayName=scheme.DisplayName}
)
};
}
<component type="typeof(App)" param-InitialState="state" render-mode="ServerPrerendered" />
The InitialApplicationState
and ExternalProvider
are simple DTO classes
public class InitialApplicationState
{
public string XsrfToken { get; set; }
public IEnumerable<ExternalProvider> ExternalLogins { get; set; }
}
public class ExternalProvider
{
public string Name { get; set; }
public string DisplayName { get; set; }
}
Now, you need to receive this data in your Blazor code as a Parameter
on the App.razor
component
@inject InitialApplicationState InitialStateService
@code {
[Parameter] public InitialApplicationState InitialState { get; set; } = default;
protected override Task OnInitializedAsync()
{
InitialStateService.XsrfToken = InitialState.XsrfToken;
InitialStateService.ExternalLogins = InitialState.ExternalLogins;
return base.OnInitializedAsync();
}
}
All we are doing here is declaring the Parameter
InitialState
that will receive our InitialApplicationState
- and then we store that state in a service InitialStateService
which is configured in startup.cs
as a Scoped dependency.
builder.Services.AddScoped<InitialApplicationState>();
Now, we have a service in our DI container for Blazor that contains a list of available external authentication providers and our forgery protection token.
We can inject the InitialApplicationState
anywhere we need it in Blazor e.g. Index.razor
and enumerate the ExternalLogins
to render buttons
The form is declared slightly differently in Blazor as we don't have the asp*
directives:
@inject InitialApplicationState InitialStateService
<form id="external-account"
action="/Identity/Account/ExternalLogin"
method="post">
<div>
<p>
@foreach (var provider in InitialStateService.ExternalLogins)
{
<button type="submit"
name="provider"
value="@provider.Name"
title="Log in using your @provider.DisplayName account">
@provider.DisplayName
</button>
}
</p>
</div>
<input name="__RequestVerificationToken" type="hidden"
value="@InitialStateService.XsrfToken">
</form>