我想创建一个ASP .Net Core 2.1 REST服务器。为此,我创建了一个新项目并选择了“ API”模板。我将它与Entity Framework,一个简单的SQlite数据库以及一些GET和POST调用一起使用。
现在,我想向API添加授权(基于角色)。我读到了有关Identity的内容,但只是不起作用。有没有好的教程,或者有人可以告诉我如何向REST服务器添加授权?我的数据库上下文中已经有一个用于用户信息的表“ User”……在此先感谢您!
答案 0 :(得分:0)
如果还没有看过(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&tabs=visual-studio)值得一看。我不了解涉及SQLite和Identity的教程,尽管使用了嵌入式数据库在其他Net Core应用程序中没有问题。使用“单个用户帐户”选项的Visual Studio 2017 Net Core模板通过一组登录/注销剃刀页面为SQL Server(Express)数据库开箱即用地添加身份验证/授权。身份表非常具体,通常由迁移填充。您可能会发现,通过右键单击项目“添加=>新脚手架项目=>身份”来设置身份剃刀页面很有用。ApplicationModel.cs模型类用于自定义AspNetUsers表。这些都可以使用“ EF Core Power Tools”(https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools)进行逆向工程,并可以通过使用自定义上下文(例如WCX_IdentityContext.cs)在右键单击菜单中选择“逆向工程”,在另一个数据库中重新创建。通常,您可以通过如下所示的上下文进行访问
[Authorize]
public IActionResult Index()
{
// The home page is redirected dependent on currently logged in user details stored in the Identity tables.
if (User.Identity.IsAuthenticated)
{
using (var context = new WCX_IdentityContext())
{
// Use Identity and EF core to retrieve logged on user details
var identity = (ClaimsIdentity)User.Identity;
// The AspNetUsers Identity table contains the basic identity details
var user = context.AspNetUsers.SingleOrDefault(x => x.UserName == identity.Name);
我希望这可以帮助您入门。