02_Web Api使用Jwt
JWT(JSON Web Token)是一种用于在网络应用之间传递信息的开放标准(RFC 7519)。它使用 JSON 对象在安全可靠的方式下传递信息,通常用于身份验证和信息交换。在Web API中,JWT通常用于对用户进行身份验证和授权。当用户登录成功后,服务器会生成一个Token并返回给客户端,客户端在接下来的请求中携带该Token来进行身份验证。
使用:
安装包:JWT
1.添加一个Web Api项目
appsettings.json设置
"JWT": {
"SecretKey": "123456789ffffffffffffffffffffffffffffffffffff", //私钥
"Issuer": "zhansan", //发布者
"Audience": "lisi" //接收者
}
2.添加一个控制器用于获取Token
/")]
public class TokenController : ControllerBase
{
public readonly IConfiguration configuration;
public TokenController(IConfiguration configuration)
{
this.configuration = configuration;
}
public string GetToken()
{//HmacSha256算法
var signingAlogorithm = SecurityAlgorithms.HmacSha256;
//存放用户信息
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub,"userId"),
new Claim(ClaimTypes.Role,"admin"),
new Claim(ClaimTypes.Name,"ClaimTypesName"),new Claim("policy","EmployeeNumber"),
};//取出私钥并以utf8编码字节输出
var secretByte = Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]);
//使用非对称算法对私钥进行加密
var signingKey = new SymmetricSecurityKey(secretByte);
//使用HmacSha256来验证加密后的私钥生成数字签名
var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
//生成Token
var Token = new JwtSecurityToken(
issuer: configuration["JWT:Issuer"], //发布者
audience: configuration["JWT:Audience"], //接收者
claims: claims, //存放的用户信息
notBefore: DateTime.UtcNow, //发布时间
expires: DateTime.UtcNow.AddDays(1), //有效期设置为1天
signingCredentials //数字签名
);
//生成字符串token
var _Tokenstring = new JwtSecurityTokenHandler().WriteToken(Token);
return _Tokenstring;
}
}
3.Program.cs设置
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
//版本控制
foreach (FieldInfo field in typeof(EditionV).GetFields())
{
c.SwaggerDoc(field.Name, new OpenApiInfo()
{
Title = field.Name + "版本",
Version = field.Name,
Description = $"{field.Name}版本"
});
}
//为swagger UI设置xml文档注释路径
var file = Path.Combine(AppContext.BaseDirectory, "WebApiApp.xml");// xml文档绝对路径
var path = Path.Combine(AppContext.BaseDirectory, file); // xml文档绝对路径
c.IncludeXmlComments(path, true); // true : 显示控制器层注释
c.OrderActionsBy(o => o.RelativePath); // 对action的名称进行排序,如果有多个,就可以看见效果了。
//注册到swagger中
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Value: Bearer {token}",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
}
});
});<br>
//策略授权
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("policy", policy => policy.RequireClaim("policy"));
});
//身份认证--如何鉴权
builder.Services.AddAuthentication(options =>
{
//options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
//取出私钥
var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]);
options.TokenValidationParameters = new TokenValidationParameters()
{
//验证发布者
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
//验证接收者
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:Audience"],
//ValidateIssuerSigningKey= true,//是否验证SigningKey
//验证是否过期
ValidateLifetime = true,
//验证私钥
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
});
//配置跨域服务
builder.Services.AddCors(options =>
{
options.AddPolicy("cross", p =>
{
p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
foreach (FieldInfo field in typeof(EditionV).GetFields())
{
c.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}");
}
});
}
app.UseCors("cross");//跨域
app.UseHttpsRedirection();
app.UseAuthentication(); //鉴权
app.UseAuthorization();//授权
app.MapControllers();
app.Run();
}
}
4.swagger设置
/// <summary>
/// 版本
/// </summary>
public static class EditionV
{
public static string V1;
public static string V2;
public static string V3;
public static string V4;
public static string V5;
}添加一个WebApiApp.xml文件,属性:复制到输出目录:始终复制
项目--->属性--->文档文件勾上。
5.添加一个UserInfoController.cs用于测试
/")]
public class UserInfoController : ControllerBase
{
/// <summary>
/// 获取用户
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public string GetUser(string id)
{
return $"用户id{id}---姓名:张三";
}
/// <summary>
/// 获取用户名
/// </summary>
/// <returns></returns>
public string GetUserName()
{
return "你好,我是李四";
}<br>/// <summary>
/// 获取用户颜色
/// </summary>
/// <returns></returns>
public string GetUserColour()
{
return "我衣服的颜色为红色";
}
}
来源:https://www.cnblogs.com/MingQiu/p/18132547
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]