.netcore3.1集成jwt验证及在Swagger接口文档中调试接口时添加Token信息

.netcore3.1集成 jwt Token验证

什么是Json web token (JWT)?我在这里就不做详细介绍了,网上的资料特别多。

详细了解请点击https://www.jianshu.com/p/576dbf44b2ae

这里介绍的是在.netcore3.1项目中添加jwt验证的中间件

我们需要安装 Microsoft.AspNetCore.Authentication.JwtBearer

怎么安装这里不做详细介绍。我安装的是3.1.2版本的

首先我们在项目的配置文件appsettings.json中添加以下节点配置信息:

  "JwtSettings": {
    "SecurityKey": "e1b47ef9-8803-4098-8468-8548a2b18ed8", // 密钥
    "Issuer": "jwtIssuerTest", // 颁发者
    "Audience": "jwtAudienceTest", // 接收者
    "ExpireSeconds": 12 // 过期时间(h)
  }

添加获取配置信息的实体类:

public class JwtSettings
{
    /// <summary>
    /// 密钥(字符串长度大于16)
    /// </summary>
    public string SecurityKey { get; set; }

    /// <summary>
    /// 颁发者
    /// </summary>
    public string Issuer { get; set; }

    /// <summary>
    /// 接收者
    /// </summary>
    public string Audience { get; set; }

    /// <summary>
    /// 过期时间(s)
    /// </summary>
    public int ExpireSeconds { get; set; }
}

然后在Startup.cs文件中的ConfigureServices方法中添加以下代码:

#region Jwt配置
//将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));

//由于初始化的时候我们就需要用,所以使用Bind的方式读取配置
//将配置绑定到JwtSettings实例中
var jwtSettings = new JwtSettings();
Configuration.Bind("JwtSettings", jwtSettings);

//添加身份验证
services.AddAuthentication(options =>
{
    ////认证middleware配置
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    //jwt token参数设置
    options.TokenValidationParameters = new TokenValidationParameters
    {
        //Token颁发机构
        ValidIssuer = jwtSettings.Issuer,
        //颁发给谁
        ValidAudience = jwtSettings.Audience,
        //这里的key要进行加密
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecurityKey))
    };
});
#endregion


在Configure方法中添加引用:

//身份授权认证
app.UseAuthentication();//需要放在 app.UseAuthorization 的前面
app.UseAuthorization();

在LoginController控制器中添加获取tokend的方法,在需要Token验证的添加[Authorize]特性:

/// <summary>
/// LoginController
/// </summary>
public class LoginController : BaseController
{
    private static JwtSettings _jwtSettings;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="jwtSettingsAccesser"></param>
    public LoginController(IOptions<JwtSettings> jwtSettingsAccesser)
    {
        _jwtSettings = jwtSettingsAccesser.Value;
    }

    /// <summary>
    /// 获取Token令牌
    /// </summary>
    /// <param name="userModel"></param>
    /// <returns></returns>
    private object Token(OperatorModel userModel)
    {
        var tokenHandler = new JwtSecurityTokenHandler();

        var key = Encoding.UTF8.GetBytes(_jwtSettings.SecurityKey);
        var authTime = DateTime.UtcNow;//授权时间
        var expiresAt = authTime.AddHours(_jwtSettings.ExpireSeconds);//过期时间
        var tokenDescripor = new SecurityTokenDescriptor
        {
            Audience = _jwtSettings.Audience,
            Issuer = _jwtSettings.Issuer,
            Subject = new ClaimsIdentity(new Claim[] { }),
            Expires = expiresAt,
            //对称秘钥SymmetricSecurityKey
            //签名证书(秘钥,加密算法)SecurityAlgorithms
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescripor);
        var tokenString = tokenHandler.WriteToken(token);
        var result = new
        {
            Authorization = tokenString,
            token_type = "Bearer",
            user = new
            {
                userModel.Id,
                userModel.Name,
                userModel.Account,
                userModel.PhoneNumber
            }
        };
        return result;
    }

    /// <summary>
    /// 集成jwt验证及在Swagger中实现添加Token(不需要验证)
    /// </summary
    /// <returns></returns>
    [HttpPost]
    public IActionResult Test()
    {
        OperatorModel model = new OperatorModel
        {
            Id = "123",
            Account = "admin",
            Name = "张三",
            PhoneNumber = "1234578910",
            Role = "管理员",
        };
        return Content(Token(model).ToJson());
    }

    /// <summary>
    /// 集成jwt验证及在Swagger中实现添加Token(需要验证)
    /// </summary>
    /// <returns></returns>
    [Authorize]
    [HttpPost]
    public IActionResult Test1()
    {
        OperatorModel model = new OperatorModel
        {
            Id = "123",
            Account = "admin",
            Name = "张三",
            PhoneNumber = "1234578910",
            Role = "管理员",
        };
        return Content(model.ToJson());
    }
}

启动项目发现Swagger中请求接口时添加不了Token,在请求需要Token验证的接口时返回401错误:

微信图片_20200303132356.png

我们需要在Swagger中添加Token

在Swagger中调试接口时添加Token

然后在Startup.cs文件ConfigureServices方法中配置AddSwaggerGen的代码内部添加代码:

//名称必须为“Bearer”,否者请求接口时Header不会带上Token
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
    Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格。",
    Name = "Authorization",
    In = ParameterLocation.Header,
    Type = SecuritySchemeType.ApiKey,
    BearerFormat = "JWT",
    Scheme = "bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
            }
        },
        new List<string>()
    }
});

添加上面代码后启动后会出现以下截图的小锁:

微信图片_20200303132859.png

点击顶部的小锁进行Token配置,输入获取到的Token秘钥(输入格式为"Bearer 获取到的Token秘钥",中间需要一个空格隔离):

微信图片_20200303133948.png

设置了Token后小锁被锁上,设置成功。

QQ截图20200306175725.png

然后再请求需要Token验证的接口,调试成功,返回正确数据:

微信图片_20200306175348.png

到这里,集成jwt登录验证及在Swagger中添加Token输入已经完成。

版权声明:若无特殊注明,本文为《奕独客》原创,转载请保留文章出处。
本文链接:.netcore3.1集成jwt验证及在Swagger接口文档中调试接口时添加Token信息 [https://www.yiduk.com/教程资料/31.html]
正文到此结束

热门推荐