[英]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.