| layout | post |
|---|---|
| title | Syncfusion® Blazor DataGrid with GitHub OAuth 2.0 |
| description | Step-by-step guide to integrate GitHub OAuth 2.0 authentication with Syncfusion® Blazor components in a Blazor Web App. |
| platform | Blazor |
| control | Common |
| documentation | ug |
This guide explains how to integrate OAuth 2.0 authentication into a Blazor Web App (Interactive Server) using GitHub OAuth. Once authenticated, the user can access protected pages featuring the Syncfusion® Blazor DataGrid component.
OAuth 2.0 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service (such as GitHub, Google, and Microsoft). It uses tokens instead of credentials and is widely used for secure authentication in modern applications.
Benefits of using OAuth in Blazor applications
OAuth enables secure user authentication by allowing sign‑in through trusted external providers. It removes the need to store username and password in the application, reducing security risks. OAuth uses short lived access tokens to protect APIs and user data. This approach minimizes developer side security responsibilities.
This section explains how to secure the Syncfusion® Blazor DataGrid using OAuth 2.0 authentication in a Blazor Web App. It demonstrates integrating GitHub as an OAuth provider to authenticate users, restrict access to protected pages, and render the DataGrid only for authorized users.
If you already have a Blazor project configured, you can skip this section and proceed to Install required packages.
Otherwise, create a new Blazor application by following the Syncfusion getting started guides Blazor Web App (Interactive Server)
Ensure that HTTPS is enabled during project creation, as GitHub OAuth based authorization requires secure communication.
Open the NuGet Package Manager in Visual Studio from (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), and install the required package.
Syncfusion packages:
Open the ~/_Imports.razor file and import the Syncfusion® namespaces.
{% tabs %} {% highlight razor tabtitle="~/_Imports.razor" %}
@using Syncfusion.Blazor @using Syncfusion.Blazor.Grids
{% endhighlight %} {% endtabs %}
Include the theme stylesheet and script references in the App.razor file.
{% tabs %} {% highlight html %}
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>{% endhighlight %} {% endtabs %}
- Go to GitHub Developer Settings.
- Click OAuth Apps → New OAuth App.
- Configure the application:
- Homepage URL:
https://localhost:5001/(Replace5001with your application's actual HTTPS port number fromlaunchSettings.jsonif different). - Authorization callback URL:
https://localhost:5001/signin-github.
- Homepage URL:
- Copy the generated Client ID and Client Secret.
- In your Blazor project, open appsettings.json and add the following configuration.
{% tabs %} {% highlight json tabtitle="appsettings.json" %}
"Authentication": { "GitHub": { "ClientId": "", "ClientSecret": "" } }
{% endhighlight %} {% endtabs %}
Add OAuth authentication using GitHub and enable cookie based sign‑in in Program.cs.
{% tabs %} {% highlight c# tabtitle="Program.cs" %}
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; using Syncfusion.Blazor;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents() .AddInteractiveServerComponents();
// Register the Syncfusion® Blazor service
builder.Services.AddSyncfusionBlazor();
// Configure authentication (Cookies + GitHub OAuth). builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "GitHub"; }) .AddCookie() .AddOAuth("GitHub", options => { options.ClientId = builder.Configuration["Authentication:GitHub:ClientId"] ?? throw new InvalidOperationException("GitHub ClientId is not configured. Set 'Authentication:GitHub:ClientId' in appsettings or user secrets."); options.ClientSecret = builder.Configuration["Authentication:GitHub:ClientSecret"] ?? throw new InvalidOperationException("GitHub ClientSecret is not configured. Set 'Authentication:GitHub:ClientSecret' in appsettings or user secrets."); options.CallbackPath = "/signin-github"; options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize"; options.TokenEndpoint = "https://github.com/login/oauth/access_token"; options.UserInformationEndpoint = "https://api.github.com/user"; options.Scope.Add("user:email"); options.SaveTokens = true;
options.ClaimActions.MapJsonKey("urn:github:login", "login");
options.ClaimActions.MapJsonKey("urn:github:id", "id");
options.ClaimActions.MapJsonKey("urn:github:url", "html_url");
options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url");
options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
{
OnCreatingTicket = async context =>
{
// GitHub requires a user-agent header.
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Accept.ParseAdd("application/json");
request.Headers.UserAgent.ParseAdd("OAuthApp");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.AccessToken);
var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
using var payload = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync());
context.RunClaimActions(payload.RootElement);
}
};
});
builder.Services.AddAuthorization(); // Add support for API controllers (used to proxy calls to protected APIs). builder.Services.AddControllers(); // Register IHttpClientFactory for outbound HTTP calls builder.Services.AddHttpClient();
var app = builder.Build();
// Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); app.MapControllers(); app.MapStaticAssets(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); app.Run();
{% endhighlight %} {% endtabs %}
This configuration redirects users to GitHub for authentication, stores the authenticated session in a secure cookie, and retrieves the user's profile information from GitHub after a successful login.
Create a new folder Controllers in the project root, then add AccountController.cs with the following code to handle OAuth redirection.
{% tabs %} {% highlight c# tabtitle="AccountController.cs" %}
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc;
namespace OAuth.Controllers { [Route("account")] public class AccountController : Controller { [HttpGet("login")] public IActionResult Login(string? returnUrl = "/") { return Challenge( new AuthenticationProperties { RedirectUri = returnUrl }, "GitHub" ); }
[HttpGet("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
} }
{% endhighlight %} {% endtabs %}
To allow components to receive authentication state, wrap the router inside CascadingAuthenticationState under ~/Components/Routes.razor file.
{% tabs %} {% highlight razor tabtitle="Routes.razor" %}
@using Microsoft.AspNetCore.Components.Authorization
{% endhighlight %} {% endtabs %}
Create SecureGrid.razor page and render the Syncfusion® Blazor DataGrid on a secured Blazor page using the [Authorize] attribute, allowing access only to authenticated users.
{% tabs %} {% highlight razor tabtitle="Pages/SecureGrid.razor" %}
@page "/secure-grid" @rendermode InteractiveServer @attribute [Microsoft.AspNetCore.Authorization.Authorize]
@using Syncfusion.Blazor.Grids @using Microsoft.AspNetCore.Components.Authorization
Secure Data Grid
<SfGrid DataSource="@Orders" AllowPaging="true">
<GridColumns>
<GridColumn Field="@nameof(Order.OrderID)" HeaderText="Order ID" Width="120" />
<GridColumn Field="@nameof(Order.CustomerID)" HeaderText="Customer ID" Width="150" />
</GridColumns>
</SfGrid>
@code { public List Orders { get; set; } = new();
protected override void OnInitialized()
{
Orders = Enumerable.Range(1, 5).Select(x => new Order()
{
OrderID = x,
CustomerID = (new string[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" })[new Random().Next(5)],
}).ToList();
}
public class Order
{
public int? OrderID { get; set; }
public string? CustomerID { get; set; }
}
}
{% endhighlight %} {% endtabs %}
This section demonstrates how to dynamically render UI content based on the user’s authentication state. The Home.razor page uses the <AuthorizeView> component to show different content for authenticated and unauthenticated users.
{% tabs %} {% highlight razor tabtitle="Pages/Home.razor" %}
@page "/" @using Microsoft.AspNetCore.Components.Authorization
Home
<h1>DataGrid</h1>
<!-- Render DataGrid on the home page when authenticated -->
<SecureGrid />
</Authorized>
<NotAuthorized>
<h1>Welcome!</h1>
<p>
Click the Login button below to sign in with GitHub.
Once you’re logged in, the Syncfusion Blazor DataGrid will be displayed.
</p>
<a class="btn btn-primary" href="/account/login?returnUrl=/">
Login with GitHub
</a>
</NotAuthorized>
</AuthorizeView>
{% endhighlight %} {% endtabs %}
This example demonstrates how to integrate GitHub OAuth into a Blazor Web App and authenticate users using secure cookie based sign‑in. After authentication, the user can access protected pages and view the Syncfusion® Blazor DataGrid.
