Using SignInManager in server-side Blazor

2020-02-13 04:49发布

问题:

Is it possible to use SignInManager without having some HTTPContext ? I'm making a Blazor server-side app and I need to make end-users signed in using PasswordSignInAsync() method of SignInManager.

If there is other ways to do it with cookies or something else, I'll take it too, as long they are "clean" methods.

If I could get also an explanation on how to configure for Startup.cs the solution, it will be perfect.

回答1:

I'd strongly suggest that you use the Identity authentication system in your app. You should not try to create any authentication system instead. This is something free, and is set up within a couple of minutes. Don't waste your time to do something so complicated. Instead learn what are the Blazor Authorization components and how to use them in your application. They are great.

Note: The communication between Blazor Server and its client-side is done through SignaleR. HttpContext is not available most of the time. Do not try to use the HttpContext. Actually, you can't because whenever you try to access it, it is null.

The following describe how you can create a Blazor Server App with the Identity UI:

  • Start creating a Blazor App

  • In the window titled Create a new Blazor app do this:

    1. Select Blazor Server App
    2. On the right side of the window is a link with the text Change, under the Authentication title. Tap the link and select Individual User Account. Press OK...
    3. Click the "Create" button

Visual Studio has created for you a Blazor Server App with Identity UI to authenticate your users. Note that the Identity UI is actually the Razor Pages Identity UI used with Razor Pages and MVC. You may scaffold one or more items from this system if you need to make some changes. Go to solution explorer and verify that Visual Studio has added two folders named Areas and Data. She also has configured your Startup class with the necessary services to mange the Identity UI. What you want now is to create the database where user names, roles, claims, etc. are stored. To create the database you should use migrations. Here is a link telling you how to run the commands that do the job for you. Now you can run your app, register to the web site, login, logout, etc.

God luck.