.NET 对于JWT的封装

下载依赖

Microsoft.AspNetCore.Authentication.JwtBearer

image.png

创建配置

实体类

image.png

``` namespace JWT4 { public class JWTSetting { public string SecKey { get; set; } public int ExpireSeconds { get;set; } } }

```

配置setting.json

image.png

``` { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "JWT": { "SecKey": "1313jdfhdjf@kfdi9knfdfndnjf{}", "ExpireSeconds": 3600 } }

```

配置Program.cs

主要在如下两处添加代码:

image.png

image.png ```

using JWT4;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

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();

// JWT
builder.Services.Configure<JWTSetting>
    (builder.Configuration.GetSection("JWT"));
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(opt =>
    {
        var jWTSettings = builder.Configuration.GetSection("JWT").Get<JWTSetting>();
        byte[] keyBytes = Encoding.UTF8.GetBytes(jWTSettings.SecKey);
        SymmetricSecurityKey secKey = new SymmetricSecurityKey(keyBytes);
        opt.TokenValidationParameters = new()
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = secKey
        };

    });



var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseHttpsRedirection();


app.UseAuthentication ();

app.UseAuthorization();

app.MapControllers();

app.Run();

测试

controller

创建登录方法

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JWT4.Controllers
{
    [Route("/[controller]/[action]")]
    [ApiController]
    public class IdentityController : ControllerBase
    {

        private readonly IOptionsSnapshot<JWTSetting> jwtSetting;

        public IdentityController(IOptionsSnapshot<JWTSetting> jwtSetting)
        {
            this.jwtSetting = jwtSetting;
        }

        [HttpPost]
        public  ActionResult<string> Login(string userName,string password)
        {
            if(userName == "xyy123" && password == "123")
            {
                List<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
                claims.Add(new Claim(ClaimTypes.Role, "admin"));


                string key = jwtSetting.Value.SecKey;
                DateTime expire = DateTime.Now.AddDays(jwtSetting.Value.ExpireSeconds);

                byte[] bytes = Encoding.UTF8.GetBytes(key);
                SymmetricSecurityKey secKey = new SymmetricSecurityKey(bytes);
                SigningCredentials credentials = new(secKey, SecurityAlgorithms.HmacSha256Signature);
                JwtSecurityToken tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expire, signingCredentials: credentials);
                string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);

                return jwt;
            }
            else
            {
                return BadRequest();
            }
        }
    }
}

只有当用户输入正确信息后,才能够登录,返回对应JWT信息

image.png

check

只有在请求中捎带验证信息,才能够执行该方法

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace JWT4.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class CheckController : ControllerBase
    {
        [HttpGet]
        public string Test1()
        {
            return "ok";
        }
    }
}

若没有捎带信息,则:

image.png

可在Postman 中新增请求头参数:

AuthorizationBearer + JWT

image.png

其他方法

获取 payload 信息

image.png

image.png

AllowAnonymous

加上后,允许不输入权限即可访问

image.png

[Authorize(Roles ="xxx")]

只有角色为 xxx 时候,才可登录

image.png

需要在创建JWT时,指定用户角色

image.png

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值