ASP.NET CORE 3.1 WebApi 引用JWT

一、导入NuGet包 Microsoft.AspNetCore.Authentication.JwtBearer

 <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.6" />

二、添加身份认证相关服务到容器中

#region JWT
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "ruxing",
        ValidAudience = "ruxing",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretsecretsecret"))
    };
});
#endregion

在这里插入图片描述

三、添加Swagger服务到容器中

#region Swagger
services.AddSwaggerGen(c =>
{
   c.SwaggerDoc("v1", new OpenApiInfo
   {
       Version = "v0.1.0",
       Title = "demoManageSys",
       Description = "框架说明文档",
       Contact = new OpenApiContact { Name = "RUXING", Email = "ruxingxing@xakcdz.com" }
   });
   var basePath = AppContext.BaseDirectory;
   var xmlPath = Path.Combine(basePath, "demoManageSys.xml");
   c.IncludeXmlComments(xmlPath, true);

   #region swagger中加入jwt
   var scheme = new OpenApiSecurityScheme()
   {
       Scheme = JwtBearerDefaults.AuthenticationScheme,
       BearerFormat = "JWT",
       In = ParameterLocation.Header,
       //头名称
       Name = "",
       Type = SecuritySchemeType.ApiKey,
       Description = "Bearer Token"
   };
   c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, scheme);
   c.AddSecurityRequirement(new OpenApiSecurityRequirement()
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
   #endregion
});
#endregion

四、将身份认证加入到管道中

//身份认证中间件(踩坑:授权中间件必须在认证中间件之前)
app.UseAuthentication();

五、在需要授权的资源上加入Authorize

/// <summary>
/// 获取天气
/// </summary>
/// <returns></returns>
 [HttpGet]
 [Authorize(Roles = "admin")]
 public IEnumerable<WeatherForecast> Get()
 {
     var rng = new Random();
     return Enumerable.Range(1, 5).Select(index => new WeatherForecast
     {
         Date = DateTime.Now.AddDays(index),
         TemperatureC = rng.Next(-20, 55),
         Summary = Summaries[rng.Next(Summaries.Length)]
     })
     .ToArray();
 }

六、登录验证

public interface ICustomAuthenticationManager
{
    string Authenticate(string username, string password);

    IDictionary<string, string> Tokens { get; }
}
public class CustomAuthenticationManager : ICustomAuthenticationManager
{
    private readonly IDictionary<string, string> users = new Dictionary<string, string>
    {
        { "admin", "admin" },
        { "jonny", "jonny" },
        { "xhl", "xhl" },
        { "james", "james" }
    };

    public IDictionary<string, string> Tokens { get; } = new Dictionary<string, string>();

    public string Authenticate(string username, string password)
    {
        var claimsIdentity = new ClaimsIdentity(new[]{
            new Claim(ClaimTypes.Name,username)
        });
        if (!users.Any(u => u.Key == username && u.Value == password))
        {
            return null;
        }
        if (username == "admin")
        {
            claimsIdentity.AddClaims(new[]
            {
                new Claim( ClaimTypes.Email, "xhl.jonny@gmail.com"),
                new Claim( "ManageId", "admin"),
                new Claim(ClaimTypes.Role,"admin")
            });
        }
        var handler = new JwtSecurityTokenHandler();
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = claimsIdentity,
            Expires = DateTime.Now.AddMinutes(3),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretsecretsecret")), SecurityAlgorithms.HmacSha256),
        };
        var securityToken = handler.CreateToken(tokenDescriptor);
        var token = handler.WriteToken(securityToken);
        Tokens.Add(token, username);
        return token;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对您的问题,我可以给您一些关于js-cookie设置token过期时间以及ASP.NET Core Web APIJWT刷新Token的实用技巧。 首先,关于js-cookie设置token过期时间,可以通过以下代码实现: ```javascript // 设置cookie过期时间为1天 Cookies.set('token', 'your_token_value', { expires: 1 }); ``` 其中,`expires`属性表示过期时间,单位为天。 其次,关于ASP.NET Core Web APIJWT刷新Token,可以采用以下方法: 在JWT的payload中加入`exp`属性,表示token的过期时间。当token过期后,客户端需要向服务器发送请求,获取新的token。服务器对于过期的token,可以返回一个特定的状态码,比如401 Unauthorized。客户端接收到该状态码后,可以重新向服务器发送请求,获取新的token。 同时,在服务器端需要实现一个刷新token的接口,接口的功能是根据旧的token生成新的token。具体实现可以参考以下代码: ```csharp [HttpPost("refresh-token")] public IActionResult RefreshToken([FromBody] string token) { // 验证旧的token是否有效 var principal = _jwtService.GetPrincipalFromExpiredToken(token); if (principal == null) return BadRequest("Invalid token"); // 生成新的token var newToken = _jwtService.GenerateToken(principal.Claims); return Ok(newToken); } ``` 其中,`_jwtService`表示JWT的服务类,`GetPrincipalFromExpiredToken`方法用于从过期的token中获取`ClaimsPrincipal`对象,`GenerateToken`方法用于生成新的token。 希望以上内容对您有所帮助。如有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值