JWT端
1.新建webapi项目,建议在IIS单独开个端口,以便多个系统调用
2.NuGet包安装System.IdentityModel.Tokens.Jwt
3.appsettings.json添加系统对应秘钥并配置读取接口(放哪看个人喜好)
4.编写生成token接口
[HttpGet("GetToken")]
public string GetToken(string data)
{
JObject obj = JObject.Parse(data.ToString());
string staffCode = obj["userCode"].ToString();
string systemName = obj["systemName"].ToString();
string systemKey = config.GetSection($"Key:{systemName}").Value;
if (string.IsNullOrEmpty(systemKey))
{
return "";
}
//存放token中的数据
var claims = new Claim[]
{
new Claim("userCode", staffCode),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(systemKey));
var token = new JwtSecurityToken
(
//issuer: "http://localhost:6060", // jwt服务器地址
//audience: "http://localhost:5000", //请求token的服务器地址
claims: claims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddHours(12), //超期时间
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) //加密算法
);
try
{
return new JwtSecurityTokenHandler().WriteToken(token);
}
catch (Exception ex)
{
return "";
}
}
别忘了配置跨域
项目代码中使用JWT鉴权认证
1.nuget安装Microsoft.AspNetCore.Authentication.JwtBearer
注意版本号对应你的.net版本
2.添加依赖注入
public static class AddServiceCollectioncs
{
public static IServiceCollection AddJwtCollectioncs(this IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true, //开启验证token
//秘钥,需要和JWT端保持一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config.tokenSettings.Key)),
ValidateIssuer = false, //开启验证jwt服务器地址
//ValidIssuer = "http://localhost:6060", //验证jwt服务器地址
ValidateAudience = false, //开启验证请求token的服务器地址
//ValidAudience = "http://localhost:5000",//验证请求token的服务器地址
ValidateLifetime = true, //允许验证时间误差
ClockSkew = TimeSpan.Zero
};
});
return services;
}
}
Program.cs文件中添加
builder.Services.AddJwtCollectioncs();
app.UseAuthentication();
app.UseAuthorization();
3.Swagger中配置jwt认证功能(可忽略)
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Description = "格式:Bearer {token}",
Name = "Authorization",
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference=new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[] {}
}
});
到此后端配置完成,在需要认证的接口上加 [Authorize]就可以使用了,认证不通过会返回401,例如
前端在请求头中加入token,注意格式Bearer (空格) token
headers:{"Authorization":"Bearer eyJhbGciOiJ****************************"}