编程语言
首页 > 编程语言> > C#-为Web API创建程序化登录

C#-为Web API创建程序化登录

作者:互联网

我正在尝试使用.net core 2.0中的控制器内的HttpContext.SignInAsync登录
以下是我在.net core 1.1中使用的相同控制器,并且工作正常.

[Route("Login/{username}")]
public async Task<IActionResult> Login(string username)
{
        var userClaims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, "custom")
        };

        var principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));
        await HttpContext.SignInAsync("DefaultAuthenticationScheme", principal);
        return Ok("done");
}

然后运行上面的代码,我在网站上看不到任何输出.在调试时,我看不到它越过等待代码行.我假设该函数在SignInAsync函数可以运行之前已经完成.但是我在核心1.1中没有遇到这个问题.

我对startup.cs文件的更改如下:

services.AddAuthentication("DefaultAuthenticationScheme")
        .AddCookie();

并在配置中:

app.UseAuthentication();

我还试图创建一个可以进行相同类型登录的过滤器.但是,由于我将覆盖过滤器函数,因此无法使其成为异步函数,因此无法在此异步函数上调用await.

解决方法:

如果未通过身份验证/授权,则应将Authorize属性添加到希望重定向到Login的控制器/方法.

更新

如果您将它添加到您的ConfigureServices方法中,以替换您拥有的内容,那么我可以使用它:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o => o.LoginPath = new PathString("/Login"));

标签:asp-net-web-api,async-await,asp-net-core-2-0,claims-based-identity,c
来源: https://codeday.me/bug/20191025/1931043.html