Stanco delle solite sessioni introduttive o generiche su blazor? Bene, questa è la serata che fa per te.
In questa sessione ho raccolto una serie di argomenti, problematiche e tips derivanti da due anni di utilizzo di Blazor (praticamente dal suo lancio). Casi reali affrontanti e risolti.
E come nel (ormai) classico format online di XE, ci sarà ampio spazio per le domande ed il confronto.
4. OAuth and OIDC as the best option for authentication in Blazor WebAssembly apps
• AddOidcAuthentication
• AddMsalAuthentication
• AddMicrosoftIdentityWebApi
• AddIdentityServerJwt
Authentication
5. Duende Software might require you to pay a license fee for production use
of Duende Identity Server.
Authentication - Identity Server
6. Requirements:
• The UI and the backend are one application which are coupled together.
• The WASM client can only use APIs hosted on the same domain.
With cookie authentication, the Blazor application can served (downloaded)
after a successful login.
• We can use [Authorize] on _Host.cshtml page
Cookie authentication
7. Token-based authentication based on JSON Web Tokens (JWTs) was chosen
over cookie-based authentication for functional and security reasons:
• Using a token-based protocol offers a smaller attack surface area, as the tokens aren't sent in all
requests.
• Server endpoints don't require protection against Cross-Site Request Forgery (CSRF) because the
tokens are sent explicitly.
• Tokens have narrower permissions than cookies.
• Tokens have a short lifetime, one hour by default, which limits the attack window. Tokens can also be
revoked at any time.
• Self-contained JWTs offer guarantees to the client and server about the authentication process.
• Tokens with OAuth and OIDC don't rely on the user agent behaving correctly to ensure that the app
is secure.
• Token-based protocols, such as OAuth and OIDC, allow for authenticating and authorizing hosted
and standalone apps with the same set of security characteristics.
Authentication
9. Blazor apps are built using Razor components, informally known as Blazor
components. A component is a self-contained portion of user interface (UI)
with processing logic to enable dynamic behavior. Components can be
nested, reused, shared among projects, and used in MVC and Razor Pages
apps.
Components
10. Components can use a singleton service for comunicate.
We can use a state container to maintain the application status:
• It can be a simple class injected as a singleton (Blazor WebAssembly) or
scoped service (Blazor Server)
Use events to notify changes.
Dependency Injection, singleton, event
12. To call into JS from .NET, inject the IJSRuntime abstraction and call one of
the following methods:
• IJSRuntime.InvokeAsync
• JSRuntimeExtensions.InvokeAsync
• JSRuntimeExtensions.InvokeVoidAsync
The TValue return type must also be JSON serializable. TValue should match
the .NET type that best maps to the JSON type returned.
A JS Promise is returned for InvokeAsync methods. InvokeAsync unwraps the
Promise and returns the value awaited by the Promise.
You can call JS method only after that the component is rendered.
IJSRuntime
13. Blazor enables JavaScript (JS) isolation in standard JavaScript modules
(ECMAScript specification).
JS isolation provides the following benefits:
• Imported JS no longer pollutes the global namespace.
• Consumers of a library and components aren't required to import the related JS.
JavaScript isolation, IJSObjectReference
14. Disposes the IJSObjectReference for garbage collection in
IAsyncDisposable.DisposeAsync.
When the external JS file is supplied by a Razor class library, specify the
module's JS file using its stable static web asset path:
"./_content/{PACKAGE ID}/{SCRIPT PATH AND FILENAME (.js)}"
IJSInProcessObjectReference represents a reference to a JS object whose
functions can be invoked synchronously.
IJSObjectReference, IJSInProcessObjectReference
15. Blazor WebAssembly components may experience poor performance when
.NET objects are serialized for JavaScript (JS) interop and either of the
following are true:
• A high volume of .NET objects are rapidly serialized. For example, poor
performance may result when JS interop calls are made on the basis of
moving an input device, such as spinning a mouse wheel.
• Large .NET objects or many .NET objects must be serialized for JS interop. For
example, poor performance may result when JS interop calls require
serializing dozens of files.
IJSUnmarshalledObjectReference represents a reference to an JS object
whose functions can be invoked without the overhead of serializing .NET
data.
IJSUnmarshalledObjectReference
17. Only use an element reference to mutate the contents of an empty element
that doesn't interact with Blazor.
An ElementReference can't be passed between components because:
• The instance is only guaranteed to exist after the component is rendered,
which is during or after a component's
OnAfterRender/OnAfterRenderAsync method executes.
• An ElementReference is a struct, which can't be passed as a component
parameter.
ElementReference
18. To invoke a static .NET method from JavaScript (JS), use the JS functions
DotNet.invokeMethod or DotNet.invokeMethodAsync:
• DotNet.invokeMethodAsync('{ASSEMBLY NAME}', '{.NET METHOD ID}', {ARGUMENTS});
• The .NET method must be public, static, and have the [JSInvokable] attribute.
To invoke an instance .NET method from JavaScript (JS):
• Pass the .NET instance by reference to JS by wrapping the instance in a
DotNetObjectReference and calling Create on it.
• Invoke a .NET instance method from JS using invokeMethod or invokeMethodAsync
from the passed DotNetObjectReference. The .NET instance can also be passed as an
argument when invoking other .NET methods from JS.
• Dispose of the DotNetObjectReference.
Call .NET methods from JavaScript
19. JavaScript (JS) files and other static assets aren't generally cached on clients
during development in the Development environment.
During development, static asset requests include the Cache-Control
header with a value of no-cache or max-age with a value of zero (0).
During production in the Production environment, JS files are usually cached
by clients.
Cached JavaScript files
21. • Ability to run multiple Blazor server / Web assembly apps in the same document
• Empty Blazor project template
• Real multithreading (on supported browsers)
• Pause and resume Blazor applications
• More control over circuits lifetime (ability to monitor circuit activity and terminate
from client/server)
• Server-side Blazor: Provide APIs/Extension Points for Circuit Eviction
• Improve prerendering and authentication experience in Blazor
What's new in .NET 7
22. What's new in .NET 7
https://github.com/dotnet/aspnetcore/issues/39504
23. Blazor: After finishing Blazor Hybrid support for .NET MAUI, WPF, and
Windows Forms, we’ll make broad improvements to Blazor including:
• New .NET WebAssembly capabilities: mixed-mode AOT, multithreading,
web crypto.
• Enhanced Hot Reload support.
• Data binding improvements.
• More flexible prerendering.
• More control over the lifecycle of Blazor Server circuits.
• Improved support for micro frontends.
ASP.NET Core updates in .NET 7 Preview 1
24. Riferimenti
• Call JavaScript functions from .NET methods in ASP.NET Core Blazor
• https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet
• Call .NET methods from JavaScript functions in ASP.NET Core Blazor
• https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript
• ASP.NET Community Standup - Blazor .NET 7 Roadmap
• https://www.youtube.com/watch?v=3o91I6lD-Bo
• What's Coming for Blazor Hybrid in .NET 7
• https://visualstudiomagazine.com/articles/2022/02/10/blazor-hybrid-net-7.aspx
• ASP.NET Core Roadmap for .NET 7 #39504
• https://github.com/dotnet/aspnetcore/issues/39504
25. • Secure a Blazor WebAssembly application with cookie authentication
• https://guidnew.com/en/blog/secure-a-blazor-webassembly-application-with-cookie-authentication/
• Securing Blazor Web assembly using cookies
• https://damienbod.com/2021/03/08/securing-blazor-web-assembly-using-cookies/
• ASP.NET Core Roadmap for .NET 7 #39504
• https://github.com/dotnet/aspnetcore/issues/39504
Riferimenti