What is JavaScript isolation in Blazor components?
Blazor allows JavaScript isolation in standard JavaScript modules. JavaScript isolation provides the following benefits: JavaScript code is allowed to load only specified components. Imported JavaScript does not affect any global namespace. Library and component consumers are not required to import the related JavaScript. Follow these steps to implement JavaScript isolation in Blazor: Create an export JavaScript function in the wwwroot/script folder.[isolationScript.js] export function jsIsolation(value) { console.log(value); } Import the JavaScript function using the IJSRuntime.InvokeAsync method in Blazor and call the JavaScript method on button click event.[Index.razor] @page “/”@inject IJSRuntime JSRuntime Enter text:<input @bind=”content” /> <button class=”btn btn-primary” @onclick=”OnClickButton”>Click</button> @code { private string content { get; set; } private async void OnClickButton() { var jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>(“import”, “./script/isolationScript.js”); await jsModule.InvokeVoidAsync(“jsIsolation”, content); } } The JavaScript code file loads only during a button click event. It will not load again and again for each button click. Refer to this documentation for more details.
How do I implement Blazor authentication with OpenID Connect?
Blazor authentication is implemented to determine who a particular user is. Blazor follows the existing ASP.NET Core authentication mechanisms to show a user’s identity.Follow these steps to implement authentication with OpenID Connect in Blazor: Create Blazor application Create a Blazor Server app and install a NuGet package named “Microsoft.AspNetCore.Authentication.OpenIdConnect” using the NuGet package manager. Add OIDC and authentication configuration Add OpenID Connect and cookie authentication service configuration to the Blazor Server app in the Startup.cs file.[Startup.cs] using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Authentication.OpenIdConnect;using Microsoft.IdentityModel.Tokens; namespace BlazorServerApp{ public class Startup { . . . . . . public void ConfigureServices(IServiceCollection services) { . . . . . . services.AddAuthentication(opt => { opt.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; opt.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }).AddCookie().AddOpenIdConnect(“oidc”, options => { options.Authority = “https://demo.identityserver.io/”; options.ClientId = “interactive.confidential.short”; options.ClientSecret = “secret”; options.ResponseType = “code”; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.UseTokenLifetime = false; options.Scope.Add(“openid”); options.Scope.Add(“profile”); options.TokenValidationParameters = new TokenValidationParameters{ NameClaimType = “name” }; options.Events = new OpenIdConnectEvents { OnAccessDenied = context => { context.HandleResponse(); context.Response.Redirect(“/”); return Task.CompletedTask; } }; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { . . . . . . app.UseAuthentication(); app.UseAuthorization(); } } } Add AuthorizeRouteView to the App.razor file Add AuthorizeRouteView to display the page matching the specified route only if the user is authorized.[App.razor] @inject NavigationManager UriHelper <CascadingAuthenticationState> <Router AppAssembly=”@typeof(Program).Assembly”> <Found Context=”routeData”> <AuthorizeRouteView RouteData=”@routeData” DefaultLayout=”@typeof(MainLayout)”> <NotAuthorized> @{ var returnUrl = UriHelper.ToBaseRelativePath(UriHelper.Uri); UriHelper.NavigateTo($”login?redirectUri={returnUrl}”, forceLoad: true); } </NotAuthorized> <Authorizing> Loading… </Authorizing> </AuthorizeRouteView> </Found> <NotFound> <LayoutView Layout=”@typeof(MainLayout)”> <p>Sorry, there’s nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState> Add buttons Add Log out and Log in buttons to authorize the user in the header section.[MainLayout.razor] <div class=”top-row px-4″> <AuthorizeView> <Authorized> <form method=”get” action=”logout”> <button type=”submit” class=”nav-link btn btn-link”>Log out</button> </form> </Authorized> <NotAuthorized> <a href=”login?redirectUri=/”>Log in</a> </NotAuthorized> </AuthorizeView> <a href=”https://docs.microsoft.com/aspnet/” target=”_blank”>About</a> </div> Redirect requests to log in or log out users Create Razor pages for login (Login.cshtml.cs) and logout (Logout.cshtml.cs) redirection requests to IdentityServer for authorization under the Pages folder.[Login.cshtml.cs] using Microsoft.AspNetCore.Authentication; namespace BlazorServerApp.Pages{ public class LoginModel : PageModel { public async Task OnGet(string redirectUri) { await HttpContext.ChallengeAsync(“oidc”, new AuthenticationProperties { RedirectUri = redirectUri }); } } } [Logout.cshtml.cs] using Microsoft.AspNetCore.Authentication; namespace BlazorServerApp.Pages{ public class LogoutModel : PageModel { public async Task<IActionResult> OnGetAsync() { await HttpContext.SignOutAsync(); return Redirect(“/”); } } } Show authorized content in Razor component Following is the code to display the authorized content when the app is authorized. If the app is not authorized, it displays the “Not Authorized” message to the user.[Index.razor] @page “/” <AuthorizeView> <Authorized> <h1>Hello, @context.User.Identity.Name !</h1> <p>Welcome to your new app.</p> </Authorized> <NotAuthorized> <p>Not Authorized</p> </NotAuthorized> </AuthorizeView> Run the application Press Ctrl + F5 to run the application and click Log in in the header to authenticate the user. You can download the reference sample on GitHub.
How do I do cookie authentication in Blazor?
Cookies are created by the application and passed to the user’s web browser when the user submits the request. The web browser passes the cookie back to the application to indicate that the user is authenticated. When the user logs out, the cookie is removed.Follow these steps to set a cookie and read that cookie with authentication in Blazor. Configure the cookie authentication services in the Startup.cs file.[Startup.cs] public class Startup{ . . . . . . public void ConfigureServices(IServiceCollection services) { . . . . . . services.AddAuthentication(“Cookies”).AddCookie(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { . . . . . . app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); . . . . . . }); } } Now, add a controller page to set the cookie to the browser and redirect the URL.[CookieController.cs] using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using System.Collections.Generic;using System.Security.Claims;using System.Threading.Tasks; namespace blazorcookie { [Route(“/[controller]”)] [ApiController] public class CookieController : ControllerBase { [HttpPost] public async Task<ActionResult> Login([FromForm] string name) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.NameIdentifier, name) }, “auth”); ClaimsPrincipal claims = new ClaimsPrincipal(claimsIdentity); await HttpContext.SignInAsync(claims); return Redirect(“/”); } } } To use the authorized view, configure the CascadingAuthenticationState component in the App.razor file. This will let you check the authentication state inside the Blazor application.[ App.razor ] <CascadingAuthenticationState> <Router AppAssembly=”@typeof(Program).Assembly” PreferExactMatches=”@true”> . . . . . . . . . </Router></CascadingAuthenticationState> Use form action to call the cookie controller to set the cookie and have it read by AuthorizeView user name.[Index.razor] @page “/” <AuthorizeView> <Authorized> <h1>Hello @context.User.Claims.First().Value</h1> </Authorized></AuthorizeView> <form action=”cookie” method=”post”> <input type=”text” name=”name” /> <input type=”submit” /></form> Run the application and submit the form request. You will find an authentication cookie with the scheme “Cookies,” which was specified in the ConfigureServices() method of the Startup class. Refer to this blog post for more details and download the sample on GitHub.
How do you preserve the state in Blazor server-side?
Blazor Server is a stateful application framework that maintains a connection to the server. Its state will occur in the server memory known as circuit. We can preserve the state in Blazor server-side three ways: Server-side storage URL Browser storage The following example demonstrates how to preserve the state in Blazor server-side using browser storage. Install the Blazored.SessionStorage NuGet package in the NuGet package manager to store the session data in Blazor. Add the Blazored SessionStorage configuration to the Blazor Server app. [Startup.cs] [Index.razor] Refer to this documentation for details.
How do I deploy a Blazor WebAssembly app to Heroku?
Heroku is a cloud platform as a service that enables you to deploy, build, and run applications in the cloud. Following are the steps to deploy a Blazor WebAssembly application to Heroku. Prerequisites: Blazor WebAssembly app in your GitHub Heroku account Deploy a Blazor WebAssembly app in Heroku Go to the Heroku dashboard and create a new app. Provide the app name and create an app. Now the new app is created. Next connect your GitHub Blazor WebAssembly app repository to Heroku for deployment. By default, Heroku does not support .NET apps for deployment. So, we add third-party build packs to enable the .NET app deployment support. Go to the settings tab and click Add buildpack. Now the dialog box will open. Copy the link below, paste it into the Buildpack URL section, and save your changes. The build pack has been added. Go to the Deploy tab and deploy the repository manually. The Blazor app starts building now. Now the Blazor app is deployed. Click View to run the deployed application. The deployed application opens in the default browser. See the following image for reference.