title
stringlengths
3
46
content
stringlengths
0
1.6k
19:720
Enclose the C# object in a DotNetObjectReference instance and pass it to JavaScript with a JavaScript call:
19:721
var objRef = DotNetObjectReference.Create(myObjectInstance);
19:722
//pass objRef to JavaScript
19:723
....
19:724
//dispose the DotNetObjectReference
19:725
objRef.Dispose()
19:726
19:727
19:728
On the JavaScript side, say the C# object is in a variable called dotnetObject. Then, we just need to invoke:
19:729
dotnetObject.invokeMethodAsync(`<dll name>`, `MyMethod`, arg1, ...).
19:730
then(result => {...})
19:731
19:732
19:733
19:734
The Awesome Blazor project (https://github.com/AdrienTorris/awesome-blazor) lists a lot of open-source projects that use JavaScript’s interoperability to build .NET wrappers for well-known JavaScript libraries. There, you can find wrappers for 3D graphics JavaScript libraries, plot JavaScript libraries, and so on.
19:735
The next section explains how to handle contents and number/date localization.
19:736
Globalization and localization
19:737
As soon as the Blazor application starts, both the application culture and the application UI culture are set to the browser culture. However, the developer can change both of them by assigning the chosen cultures to CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture. Typically, the application lets the user choose one of its supported cultures, or it accepts the browser culture only if it is supported; otherwise, it falls back to a supported culture. In fact, it is possible to support just a reasonable number of cultures because all application strings must be translated into all supported cultures.
19:738
If the application must support a single culture, this culture can be set once and for all in program.cs after the host has been built but before the host is run.
19:739
This can be done by replacing await builder.Build().RunAsync() with:
19:740
var host = builder.Build();
19:741
19:742
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(…);
19:743
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(…);
19:744
19:745
await host.RunAsync();
19:746
19:747
If the application must support several languages, the code is similar, but the culture information must be taken from the browser’s local storage, where the user must be given the option to store it in some applications option page.
19:748
Once the CurrentCulture is set, dates and numbers are automatically formatted according to the conventions of the chosen culture. For the UI culture, the developer must manually provide resource files with the translations of all application strings in all supported cultures. Blazor uses the same localization/globalization techniques, so please refer to the ASP.NET Core globalization section of Chapter 17, Presenting ASP.NET Core, for more details.
19:749
There are two ways to use resource files. With the first option, you create a resource file, say, myResource.resx, and then add all language-specific files: myResource.it.resx, myResource.pt.resx, and so on. In this case, Visual Studio creates a static class named myResource whose static properties are the keys of each resource file. These properties will automatically contain the localized strings corresponding to the current UI culture. You can use these static properties wherever you like, and you can use pairs composed of a resource type and a resource name to set the ErrorMessageResourceType and ErrorMessageResourceName properties of validation attributes or similar properties of other attributes. This way, the attributes will use an automatically localized string.
19:750
With the second option, you add only language-specific resource files (myResource.it.resx, myResource.pt.resx, and so on). In this case, Visual Studio doesn’t create any class associated with the resource file, and you can use resource files together with IStringLocalizer and IStringLocalizer<T> injected in components as you use them in ASP.NET Core MVC views (see the ASP.NET Core globalization section of Chapter 17, Presenting ASP.NET Core).
19:751
Authentication and authorization
19:752
In the Routing subsection, we discussed how the CascadingAuthenticationState and AuthorizeRouteView components prevent unauthorized users from accessing pages protected with an [Authorize] attribute. Let’s go deeper into the details of how page authorization works.
19:753
In .NET applications, authentication and authorization information is usually contained in a ClaimsPrincipal instance. In server applications, this instance is built when the user logs in, taking the required information from a database. In Blazor WebAssembly, such information must be provided by some remote server that takes care of SPA authentication too. Since there are several ways to provide authentication and authorization to a Blazor WebAssembly application, Blazor defines the AuthenticationStateProvider abstraction.
19:754
Authentication and authorization providers inherit from the AuthenticationStateProvider abstract class and override its GetAuthenticationStateAsync method, which returns Task<AuthenticationState>, where AuthenticationState contains the authentication and authorization information. Actually, AuthenticationState contains just a User property with a ClaimsPrincipal.
19:755
Once we’ve defined a concrete implementation of AuthenticationStateProvider, we must register it in the dependency engine container in the application’s Program.cs file:
19:756
builder.services.AddScoped<AuthenticationStateProvider,
19:757
MyAuthStateProvider>();
19:758
19:759
We will return to the predefined implementations of AuthenticationStateProvider offered by Blazor after having described how Blazor uses authentication and authorization information provided by a registered AuthenticationStateProvider.
19:760
The CascadingAuthenticationState component calls the GetAuthenticationStateAsync method of the registered AuthenticationStateProvider and cascades the returned Task<AuthenticationState>. You can intercept this cascading value with a [CascadingParameter] defined as follows in your components:
19:761
[CascadingParameter]
19:762
private Task<AuthenticationState> myAuthenticationStateTask { get; set; }
19:763
……
19:764
ClaimsPrincipal user = (await myAuthenticationStateTask).User;
19:765
19:766
However, Blazor applications typically use AuthorizeRouteView and AuthorizeView components to control user access to content.
19:767
AuthorizeRouteView prevents access to pages if the user doesn’t satisfy the prescriptions of the page’s [Authorize] attribute; otherwise, the content in the NotAuthorized template is rendered. AuthorizeRouteView also has an Authorizing template that is shown while user information is being retrieved.
19:768
AuthorizeView can be used within components to show the markup it encloses only to authorized users. It contains the same Roles and Policy parameters of the [Authorize] attribute that you can use to specify the constraints the user must satisfy to access the content:
19:769
<AuthorizeView Roles=`Admin,SuperUser`>
19:770
//authorized content
19:771
</AuthorizeView>
19:772
19:773
AuthorizeView can also specify NotAuthorized and an Authorizing template:
19:774
<AuthorizeView>
19:775
<Authorized>
19:776
...
19:777
</Authorized>
19:778
<Authorizing>
19:779
...
19:780
</Authorizing>
19:781
<NotAuthorized>
19:782
...
19:783
</NotAuthorized>
19:784
</AuthorizeView>
19:785
19:786
If one adds authorization while creating a Blazor WebAssembly project, the following method call is added to the application dependency engine:
19:787
builder.Services.AddOidcAuthentication(options =>
19:788
{
19:789
// Configure your authentication provider options here.
19:790
// For more information, see https://aka.ms/blazor-standalone-auth
19:791
builder.Configuration.Bind(`Local`, options.ProviderOptions);
19:792
});
19:793
19:794
This method adds an AuthenticationStateProvider that extracts the user information from the authentication cookie of an OAuth provider. The OAuth protocol with the OAuth provider is performed with the help of the AuthenticationService.js JavaScript file we saw in the Loading and starting the application subsection of this chapter. The OAuth provider endpoint returns user information in the form of a bearer token that can, then, also be used to authenticate communications with the server’s web API. Bearer tokens are described in detail in the REST service authorization and authentication and ASP.NET Core service authorization sections of Chapter 15, Applying Service-Oriented Architectures with .NET. Blazor WebAssembly communication is described in the next subsection.
19:795
The previous code takes the OAuth parameters from a configuration file you must add as wwwroot/appsettings.json:
19:796
{
19:797
`Local`: {
19:798
`Authority`: `{AUTHORITY}`,
19:799
`ClientId`: `{CLIENT ID}`
19:800
}
19:801
}
19:802
19:803
If you use Google as the authentication provider, AUTHORITY is https://accounts.google.com/, while CLIENT ID is the client ID you receive when you register your Blazor application with the Google Developers program.
19:804
Google needs some more parameters, namely the return URL to return once the authentication process is completed and the page to return to after a logout:
19:805
{
19:806
`Local`: {
19:807
`Authority`: `https://accounts.google.com/`,
19:808
`ClientId`: `2...7-e...q.apps.googleusercontent.com`,
19:809
`PostLogoutRedirectUri`: `https://localhost:5001/authentication/logout-callback`,
19:810
`RedirectUri`: `https://localhost:5001/authentication/login-callback`,
19:811
`ResponseType`: `id_token`
19:812
}
19:813
}
19:814
19:815
Where https://localhost:5001 must be replaced with the actual domain of the Blazor application.
19:816
Before any authentication or if the authentication fails, an unauthenticated ClaimsPrincipal is created. This way, when the user tries to access a page that is protected by an [Authorize] attribute, the AuthorizeRouteView component invokes the RedirectToLogin component, which, in turn, navigates to the Authentication.razor page, passing it a login request in its action route parameter:
19:817
@page `/authentication/{action}`
19:818
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
19:819
<RemoteAuthenticatorView Action=`@Action` />