[英]Jwt Token signature always invalid
我将在我的应用程序中实现 jwt Token 身份验证,这里我有 2 个 api,其中 1 个是我的令牌服务器,它创建令牌并与其他人共享。 启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = _config["Jwt:Issuer"],
ValidAudience = _config["Client"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:Key")))
};
});
services.AddIdentityServer()
// .AddDeveloperSigningCredential()
// .AddInMemoryPersistedGrants()
.AddJwtBearerClientAuthentication()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients(Config.GetUrls(Configuration)))
.AddAspNetIdentity<ApplicationUser>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
代币生成(登录)
public IActionResult CreateToken([FromForm]LoginModel login)
{
IActionResult response = Unauthorized();
//var user = Authenticate(login);
var userIdentity = _userManager.FindByNameAsync(login.username).Result;
var loginResult = _signInManager.CheckPasswordSignInAsync(userIdentity, login.password, false).Result;
if (userIdentity != null && loginResult.Succeeded)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
ClaimsIdentity identity = new ClaimsIdentity(
new GenericIdentity(user.UserName, "Login"),
new[] {
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
}
);
var token = new JwtSecurityToken(issuer: _config["Jwt:Issuer"],
audience: _config["Client"],
claims: identity.Claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return Ok(new ResponseModel
{
access_token = tokenString,
expires_in = "3600",
token_type = "Bearer"
});
}
return null;
}
我的 creatkey = 123456789@test 是我做错了什么。 我收到类似无效令牌的消息。 签名无效。
请给我提示或指导。 谢谢,
您的密钥应超过 16 个字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.