2

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?

2
  • Hi @ChrisMack, any updates about this case? Have you achieved the requirement of integrating ASP.NET Core Identity in your Blazor project? Commented Aug 28, 2020 at 9:09
  • Hi @FeiHan, thanks for your answer, I’m still working through the implementation. Would I be correct in thinking that a user would log in via the API and be issued a JWT token which then proves they are logged in? Would the token be used to access pages in the Blazor app or would there be another mechanism for this? Commented Aug 28, 2020 at 10:39

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.