Chris Mack
Chris Mack

Reputation: 5208

.NET Core Identity in Blazor and Web API Solution

I'm creating a Blazor application (.NET Core, C#) and am confused about how to integrate .NET Core's built-in authentication and authorizaton services (.NET Core Identity).

I have a solution that contains a project for the Blazor app, as well as a .NET Core API project for data retrieval from the back-end database.

I've seen tutorials where .NET Core Identity is implemented in the Blazor app (along with all of the pre-built pages and components for registering, signing in, etc.).

This is fine, but when I'm also building an API for data access, I feel that authentication, etc. should also be implemented in the Web API part, as this is where the authorization for data access needs to be.

What is the best/correct way to design this?

Upvotes: 2

Views: 2856

Answers (2)

Vy Do
Vy Do

Reputation: 52488

I understand your case: Blazor web-app (server-side or client-side Blazor) + ASP.NET Core Web API.

You use ASP.NET Core Identity with JWT token to archive your need. Sample source code: https://github.com/donhuvy/dotnet5_jwt

tutorial: https://viblo.asia/p/xac-thuc-jwt-dua-theo-role-trong-aspnet-core-web-api-5-4P856vA95Y3

video: https://www.youtube.com/watch?v=gsx3xCiJJlY&list=PLFJQnCcZXWjuHP03Kgf46FrX5L2fRzDsx

Upvotes: 1

Fei Han
Fei Han

Reputation: 27793

I'm creating a Blazor application (.NET Core, C#) and am confused about how to integrate .NET Core's built-in authentication and authorizaton services (.NET Core Identity).

You can refer to this doc about "Scaffold Identity into a Blazor Server project without existing authorization" to integrate ASP.NET Core Identity in your Blazor project, which would help add required libraries and configure Identity for you.

Then you should do some modifications in your Blazor project:

add LoginDisplay.razor under Shared folder

<AuthorizeView>
    <Authorized>
        <a href="Identity/Account/Manager">Hello, @context.User.Identity.Name!</a>
        <form method="post" action="Identity/Account/LogOut">
            <button type="submit" class="nav-link btn btn-link">Log out</button>
        </form>
    </Authorized>
    <NotAuthorized>
        <a href="Identity/Account/Register">Register</a>
        <a href="Identity/Account/Login">Login</a>
    </NotAuthorized>
</AuthorizeView>

reference LoginDisplay in MainLayout.razor

@inherits LayoutComponentBase

<div class="sidebar">
    <NavMenu />
</div>

<div class="main">
    <div class="top-row px-4">
        <LoginDisplay></LoginDisplay>
        <a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a>
    </div>

    <div class="content px-4">
        @Body
    </div>
</div>

update App.razor as below

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        @*<LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>*@
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>

configurations in Startup class

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        //... 
        //other configurations here

        services.AddRazorPages();
        services.AddServerSideBlazor();

        services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
        services.AddSingleton<WeatherForecastService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //...
        //other configurations here

        app.UseAuthentication();
        app.UseAuthorization();

        //...

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
}

when I'm also building an API for data access, I feel that authentication, etc. should also be implemented in the Web API part

If you separate data accessing part in a Web API project, securing Web API part (via JWT authentication etc) would help prevent unexpected consumer from calling your API.

Test Result

enter image description here

Upvotes: 2

Related Questions