结合使用Jwt和cookie进行身份验证

问题描述 投票:0回答:1

我已成功创建 jwt 令牌,但我不确定应该将其存储在哪里。我看到很多在线网站都在谈论将 jwt 令牌存储在 cookie 中,但我不确定这是否是正确的方法,因为我认为通常 jwt 令牌应该存储在授权参数内的标头中。我在 AccountController 中有以下代码来使用 cookie,但我不确定如何在其中包含 jwt 令牌。

if (login.Password.Equals(passwordCheck) && login.Username.Equals(adminCheck))
{
    var claims = new List<Claim>
    {
        new Claim("Role", "Admin")
    };

    var claimsIdentity = new ClaimsIdentity(
        claims, CookieAuthenticationDefaults.AuthenticationScheme);

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

    return RedirectToAction("Index", "User");
}

我在 Program.cs 中有以下代码来添加 cookie 和 jwt,并根据一些关于使用 jwt 和 cookie 的在线文章

builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    options.LoginPath = "/Account/Login";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
})
.AddJwtBearer(x =>
{
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration.GetValue<string>("JwtSettings:Issuer"),
        ValidateAudience = true,
        ValidAudience = builder.Configuration.GetValue<string>("JwtSettings:Audience"),
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration.GetValue<string>("JwtSettings:SecretKey"))),
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromSeconds(300),
        RequireExpirationTime = true
    };
});

使用 ASP.NET MVC,我在具有 Http 请求的控制器中有多个操作,例如(我不确定是否应该使用 ValidateAntiForgeryToken 而不是 jwt 令牌):

[HttpGet]
public async Task<string> GetActivationCode(string id)
{
    var actCode = (await _productService.GetProduct(id)).ActivationCode;
    return actCode;
}

但我不确定如何使用 jwt 令牌对视图中的这些 ajax 调用进行身份验证:

$.ajax({
    url: '/Product/GetActivationCode',
    type: 'GET',
    data: {
        id: id
    },
    success: function (response) {
        $("#actCodeText").text("Activation Code: " + response);
    },
    error: function (xhr, status, error) {
        console.error(error);
    }
});

非常感谢您的帮助。谢谢:)

我尝试参考多篇在线文章,例如:结合cookie和jwt身份验证,但我不断收到此错误: 当 AuthenticationOptions.RequireAuthenticatedSignIn 为 true 时,不允许在主体.Identity.IsAuthenticated 为 false 时使用 SignInAsync。

jquery asp.net-mvc
1个回答
0
投票

要使用 JWT 令牌,需要将 Authorization Headers 添加到您的请求中。

$.ajax({
    url: '/point', 
    method: 'GET', Any (GET, POST, PUT, DELETE)
    headers: {
        'Authorization': `Bearer   ${jwtToken}`
    },
    success: function(response) {
     
    },
    error: function(xhr, status, error) {
       
    }
}); 
© www.soinside.com 2019 - 2024. All rights reserved.