我正在使用 C# asp.net 我想在我的网页上使用 jwt 令牌。 因此,每当页面加载时,我都必须使用 jwt ,我是一个初学者,所以我没有太多想法,我知道它是如何工作的,但我不知道从哪里开始或如何准确实现。 我有一个登录页面,我只需要 jwt 作为“在线 ID/管理员/用户名”。 使用这些 对称安全密钥 签署凭证 Jwt头 Jwt负载 Jwt安全令牌 JwtSecurityTokenHandler 写令牌 var token = handler.ReadJwtToken(tokenString); 谷歌搜索给出了 .net core 的结果,这不是我想要的, 有人能帮我吗? 谢谢你
我尝试了一些代码片段,但我确信我没有以正确的方式做
要使用 JWT 进行身份验证,您必须首先注册用户并将其存储在数据库中。登录并使用数据库信息验证用户时,使用以下代码创建 JWT 令牌。
public static string GenerateJwtToken()
{
DateTime value = DateTime.Now.AddMinutes(20.0);
byte[] bytes = Encoding.ASCII.GetBytes("MIIBrTCCAaGg ...");
SigningCredentials signingCredentials = new SigningCredentials(new SymmetricSecurityKey(bytes), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256");
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Expires = value,
SigningCredentials = signingCredentials
};
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
SecurityToken token = jwtSecurityTokenHandler.CreateToken(tokenDescriptor);
return jwtSecurityTokenHandler.WriteToken(token);
}
然后,在具有 Authorize 属性的操作中,您必须在请求标头中发送上面创建的令牌。
[HttpPost]
[Authorize]
public async Task<IActionResult> Test(TestRequest input)
{
.
.
.
}
我写了一个简单的例子,你可以从这个link
看到JWT的完整实现示例程序.cs
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
//JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
app.UseAuthentication();
app.UseAuthorization();
appSetting.json
"Jwt": {
"Key": "aVeryLongSecretKeyThatIsAtLeast32BytesLong",
"Issuer": "http://localhost:7123/",
"Audience": "http://localhost:7123/"
}
生成代币
private readonly IConfiguration _config;
public JWTService(IConfiguration config)
{
_config = config;
}
public string GenerateToken(UserMaster user)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, getUserType(user.UserType))
};
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
查看角色
[Authorize(Roles = "SuperAdmin")]
[HttpPost("create-user-with-email")]
public async Task<IActionResult> Get([FromBody] CreateUserWithEmail _loginUser)
{
var result = await _user.CreateUserWithEmail(_loginUser);
return Ok(result);
}