I have created a .NET Core project with WebApi template selected includes no authentication. I want to add ASP.NET identity in it for role based authorization. How can I achieve this?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
This will give you a bear bones webapi with aspnet core identity, first create your project (this assumes you've created a new folder and you're in it):
Add aspnet core identity:
Add some database provider to store your data:
Now add a user type, the simplest version being:
And a db context, here I'm setting up the connection string within the class but you'd probably want to use DbContextOptions instead:
Then in your Startup.cs add the following marked lines:
Note that by default the AddIdentity extension will set the default authentication scheme and add various cookies that you probably don't want in an API, the cut down alternative is as follows (to replace the above AddIdentity call in ConfigureServices):
This will give you the database side of things, you can then use UserManager and SignInManager to create and authenticate users, to get them use the DI system:
And then use as follows:
And:
Using
CheckPasswordSignInAsync
instead ofPasswordSignInAsync
will avoid the creation of a cookie ifAddIdentity
is used, ifAddIdentityCore
was also used above, then you must useCheckPasswordSignInAsync
asPasswordSignInAsync
will not work as anIAuthenticationSignInHandler
will not have been setup.There is nothing special the template is doing, all you need is the Microsoft.AspNet.Identity.Core NuGet package and the you should be able to follow from here:
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity