【发布时间】:2019-01-02 09:32:03
【问题描述】:
我将在我的应用程序中实现 jwt 令牌身份验证,这里我有 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 我做错了什么吗? 我收到无效令牌之类的消息。签名无效。
请给我提示或指导。 谢谢,
【问题讨论】:
-
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:Key")))您正在读取字符串值并获取它的字节。键是典型的字节数组,但您不能将字节存储在 json 文件中。即使您的文件中有012f3b...,当您调用 byte 时,您也不会获得该字符串的字节表示形式,而是将字符串作为字节获得。您应该将密钥存储为 utf-8 序列,然后进行 base64 解码以获取字符串 -
您确定
ValidIssuer和ValidAudience在Startup.cs和您的生成文件中是否相同,因为每个文件使用不同的方法来设置它 -
@Tseng 谢谢你的回复,但我没有得到,你是说我需要将密钥作为 utf-8 存储在配置文件中,然后需要使用 base64 解码,然后将其传递给 symmetricsecuritykey ?我说对了吗..?
-
@DevEng 谢谢你的回复,是的,两者都是一样的。我进行了交叉检查并更新了我的代码。
-
为什么要自己生成令牌? Identity Server 发出令牌并在重定向回客户端时将其包含在 cookie 中。您的配置中需要
services.AddIdentityServer().AddSigningCredential([your key])。
标签: c# asp.net-core jwt