使用 JWT 令牌的 ASP.NET Core 网站到 WebApi 身份验证

Uma*_*air 6 c# jwt asp.net-core

我正在开发一个 ASP.NET Core 2.2 网站,用户需要在其中登录然后使用它。

将AccountController在我的网站调用另一个ASP.NET核心的WebAPI(带[AllowAnonymous]属性),以得到用户名和密码令牌的JWT。

除了AccountController网站内的所有控制器都将具有[Authorize("Bearer")]检查用户是否已获得授权的属性。

我的 WebApi 也会有其他需要 的控制器[Authorize("Bearer")],因此在发出 http 请求时将从网站传递 JWT 令牌。在WebApi项目中查看下面配置的Startup.cs>ConfigureServices()方法文件:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        ValidIssuer = "ZZZZ",
        ValidAudience = "ZZZZ",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
    };
});
services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build());
});
Run Code Online (Sandbox Code Playgroud)

和Configure()方法:

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core WebApi - 生成 JWT 令牌:

JWTToken jwt = new JWTToken();
jwt.Token = "";
jwt.Expires = DateTime.UtcNow.AddMinutes(90);

var claims = new[]
{
    new Claim(ClaimTypes.UserData, UserId)
};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(privateSecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
    issuer: "ZZZ",
    audience: "ZZZ",
    claims: claims,
    expires: jwt.Expires,
    signingCredentials: creds);

var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);

jwt.Token = tokenStr;
return jwt;
Run Code Online (Sandbox Code Playgroud)

我已经完成了生成令牌并返回 JWT 令牌的 WebApi 方法。但是我如何处理该令牌以便身份验证/授权在我的 ASP.NET Core 网站中工作。

[HttpPost]
public async Task<IActionResult> Login(LoginModel model)
{
    var httpClient = _httpClientFactory.CreateClient(ConstantNames.WebApi);
    var response = await httpClient.PostAsJsonAsync($"{ApiArea}/authenticate", model);
    if (response.IsSuccessStatusCode)
    {
        var jwtToken = await response.Content.ReadAsAsync<JWTToken>();

        /* --> WHAT DO I DO HERE? <-- */

    }
    else
    {
        ModelState.AddModelError("Password", "Invalid password");
        model.Password = "";
        return View(model);
    }

    return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)

因此,为了使事情变得复杂,我的项目概述如下:

ASP.NET Core 网站- 具有登录页面和其他控制器,对数据表和表单进行 ajax 调用,必须经过授权 ASP.NET Core WebApi - 生成 JWT 令牌,并具有其他必须经过授权的 api 调用的方法

我如何告诉网站,如果用户未获得授权,则转到我的/Account/Login页面?

这个过程是否正确,如果不是,我是否仍然需要添加身份并为网站以不同的方式执行此操作?

itm*_*nus 5

如果您的 ASP.NET Core 网站和 ASP.NET Web API 是两个不同的网站:

  • 对于 WebAPI,客户端应始终通过添加Authorization : Bearer {access_token}. 或者注册一个OnMessageReceived处理程序,如果你想通过 cookie/querystring 发送它
  • 对于 ASP.NET Core 网站,浏览器应使用 cookie 或 JWT 作为凭据。

我不确定您的身份验证如何。

假设您选择对 ASP.NET Core 网站使用 cookie,请确保您已设置 LoginPath = "/Account/Login";

// the Startup::ConfigureServices of your ASP.NET Core Website
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o => {
        o.LoginPath = "/Account/Login";
    });
Run Code Online (Sandbox Code Playgroud)

然后按照Camilo Terevinto 的建议,您需要让用户登录:

    [HttpPost]
    public async Task<IActionResult> Login(LoginModel model)
    {
        var httpClient = _httpClientFactory.CreateClient(ConstantNames.WebApi);
        var response = await httpClient.PostAsJsonAsync($"{ApiArea}/authenticate", model);
        if (response.IsSuccessStatusCode)
        {
            var jwtToken = await response.Content.ReadAsAsync<JWTToken>();

            var username = ...
            var others = ...
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                // add other claims as you want ...
            };
            var iden= new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(iden);
            await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, principal);
            return Redirect("/")

        }
        else
        {
            ModelState.AddModelError("Password", "Invalid password");
            model.Password = "";
            return View(model);
        }

        return RedirectToAction("Index", "Home");
    }
Run Code Online (Sandbox Code Playgroud)