asp.net-core - ASP.NET Core 2.1 身份验证

标签 asp.net-core asp.net-core-2.1 role-base-authorization

我面临以下问题:我正在尝试使用基于角色的身份验证来保护我的 ASP.NET Core Web API。

我已将以下行添加到 ConfigureServices():

// Authorization
services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

        options.LoginPath = "/api/Account/Login";
        options.AccessDeniedPath = "/api/Account/AccessDenied";
        options.SlidingExpiration = true;
    });

以及Configure():

// Authorization
app.UseAuthentication();

using (var scope = app.ApplicationServices.CreateScope())
{
    CreateRoles(scope.ServiceProvider.GetService<RoleManager<IdentityRole>>()).Wait();
    CreateUsers(scope.ServiceProvider.GetService<UserManager<ApplicationUser>>()).Wait();
}

CreateRoles()CreateUsers() 工作正常:这些方法创建一些角色和一个管理员用户,将它们存储在相应的 SQL 表和 user/角色经理。

现在我可以使用[Authorize]保护我的 Controller 。可以访问带有 [AllowAnonymous] 标记的 API 调用。

但是我如何登录 API 并访问其他 API 调用?

为此,我创建了一个帐户 Controller ,如下所示:

[Route("/api/Account")]
public class AccountController : Controller
{
    public AccountController()
    {
    }

    [HttpPost]
    [Route("Login")]
    public async Task<IActionResult> Login()
    {
    }
}

我已经阅读了很多有关此主题的文章,但我无法启动并运行登录。因此,目标是使用用户管理器中存储的用户登录并访问一些需要身份验证的 API 调用。有人可以尝试解释我如何实现它吗?

最佳答案

您需要使用 SignInManager<>.PasswordSignInAsync() 登录用户。它将分配必要的 cookie 来处理身份验证。它可能看起来像这样:

public class AccountController : Controller
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    public AccountController(SignInManager<ApplicationUser> signInManager)
    {
        _signInManager = signInManager;
    }

    public async Task<IActionResult> Login(string login, string password)
    {
        var result = await _signInManager.PasswordSignInAsync(login, password, true, lockoutOnFailure: false);

        if (result.Succeeded)
        { 
            //process successful result
        }
        else
        {
            //process failed result
        }
    }
}

关于asp.net-core - ASP.NET Core 2.1 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53693578/

相关文章:

c# - DBContext : Getting disposed without calling Dispose(). 未使用 using 语句

asp.net-core-webapi - 有没有办法在每个 HTTP 请求的 JSON 响应中重置 $id? JsonSerializerSettings = PreserveReferencesHandling.Objects

c# - 迁移到 .NET Core 2.1 破坏了 Swagger UI

asp.net-core - Gitlab 管道总是失败并显示错误消息

允许基于日期访问的权限设计模式

c# - WebSocket.CreateServerBuffer 与 WebSocket.CreateClientBuffer

c# - Facebook OAuth "Unhandled remote failure. (Correlation Failed.)"

c# - 为什么 MyService 中的 DbContext (ASP.NET) 为空?

mysql - Cakephp 3 findAuth 连接表返回数组

.net - 角色检查应该在调用堆栈的哪个位置进行?