一佳一

记录像1+1一样简洁的代码

导航

.NET 6 Swagger+JWT 配置

Posted on 2024-06-21 14:40  一佳一  阅读(49)  评论(0编辑  收藏  举报

1.1 封装一个SwaggerExtend类(包含JWT配置)

/// <summary>
/// Swagger 静态类
/// </summary>
public static class SwaggerExtend
{
/// <summary>
/// 添加服务: swagger
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static void AddCustSwagger(this IServiceCollection services)
{
var version = "V1.0";
var apiName = "XX平台";
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = version,
Title = $"{apiName} API",
Description = $"{apiName} {version} 接口服务"
});

// 获取应用程序所在目录
var basePath = Path.GetDirectoryName(typeof(SwaggerExtend).Assembly.Location);
var xmlPath = Path.Combine(basePath, "dichanweb.xml");

// swagger界面默认只显示 方法&字段 注释,不显示 控制器注释
// 第二个参数为true, 则是controller的注释
//options.IncludeXmlComments(xmlPath);
options.IncludeXmlComments(xmlPath, true);

options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer { token }\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference=new OpenApiReference()
{
Id="Bearer",
Type=ReferenceType.SecurityScheme
}
},
new string[]{}
}
});
});
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
string Jwt_Issuer = "test.cn";
string Jwt_Audience = "test";
string Jwt_SecretKey = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789";

options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Jwt_Issuer,
ValidAudience = Jwt_Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Jwt_SecretKey))
};
});

}

/// <summary>
/// 添加中间件: swagger
/// </summary>
/// <param name="app"></param>
public static void UseCustSwagger(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));

}

1.2注入

builder.Services.AddCustSwagger();
/*认证*/
app.UseAuthentication();
/*授权*/
app.UseAuthorization();

  //配置Swagger
  app.UseCustSwagger();

1.3 用户登录后返回TOKEN的方法

 private string GenerateJwtToken(T_User user)
        {
            string Jwt_Issuer = "test.cn";
            string Jwt_Audience = "test";
            string Jwt_SecretKey = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789";

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.FMobilePhone)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Jwt_SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: Jwt_Issuer,
                audience: Jwt_Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddHours(1),
                signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

 参考:https://www.cnblogs.com/CRobot/p/16715909.html