NetCore WebAPi 基于 JwtBearer 的鉴权验证

1.安装 NuGet 包:Microsoft.AspNetCore.Authentication.JwtBearer
2.配置:appsettings.json
3.配置:Program.cs
4.获取Token,在控制器上加入[AllowAnonymous]
5.鉴权,在控制器上加入[Authorize]
6.提交Token方式
7.获取Token信息
8.源码下载:Micro.AspNetCore.Identity.zip



1.安装 NuGet 包:Microsoft.AspNetCore.Authentication.JwtBearer

 

2.配置:appsettings.json

{
  "JWT": {
    //加密的key(SecretKey必须大于等于16位字符)
    "SecretKey": "1234567812345678",
    //token是谁颁发的
    "Issuer": "tenantid",
    //过期时间
    "Expires": 10,
    //token可以给哪些客户端使用
    "Audience": "appid"
  }
}

 

3.配置:Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
 
//配置认证服务
builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters();
    options.Events = new JwtBearerEvents()
    {
        OnMessageReceived = context =>
        {
            context.Token = context.Request.Query["access_token"];
            return Task.CompletedTask;
        }
    };
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true, //是否验证Issuer
        ValidateAudience = true, //是否验证Audience
        ValidateLifetime = true, //是否验证失效时间
        RequireExpirationTime = true, //过期时间
        ValidateIssuerSigningKey = true, //是否验证IssuerSigningKey
        ValidAudience = builder.Configuration["JWT:Audience"],
        ValidIssuer = builder.Configuration["JWT:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"])),
        //自定义校验规则:新登录后,之前的token无效
        //AudienceValidator = (audiences, securityToken, validationParameters) =>
        //{
        //    return audiences != null && audiences.FirstOrDefault().Equals(audience);
        //}
    };
});
 
var app = builder.Build();
 
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
 
//1.先开启认证
app.UseAuthentication();
//2.再开启授权
app.UseAuthorization();
 
app.MapControllers();
 
app.Run();

 

4.获取Token,在控制器上加入[AllowAnonymous]

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
 
namespace Micro.AspNetCore.Identity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [AllowAnonymous]
    public class TokenController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        //一定要在这里注入configuration
        public TokenController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
 
        [HttpPost]
        public string Post([FromBody] string value)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
                new Claim("Id", "9527"),
                new Claim("Name", "Admin")
            };
            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;
            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);
            // 5. 从 appsettings.json 中读取Expires
            var expires = Convert.ToDouble(_configuration["JWT:Expires"]);
            // 6. 根据以上,生成token
            var token = new JwtSecurityToken(
                _configuration["JWT:Issuer"],     //Issuer
                _configuration["JWT:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddDays(expires),   //expires
                signingCredentials               //Credentials
            );
            // 7. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;
        }
    }
}

 

5.鉴权,在控制器上加入[Authorize]

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
 
namespace Micro.AspNetCore.Identity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UsersController : ControllerBase
    {
        // GET api/<UsersController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            var user = HttpContext.User;
            var claim = (ClaimsIdentity)HttpContext.User.Identity;
            var Id = Convert.ToInt32(claim.Claims.Where(x => x.Type.Contains("Id")).FirstOrDefault().Value);
 
            return Id.ToString();
        }
    }
}

 

6.提交Token

方式一:

方式二:

 

方式三:

 

7.获取Token信息

var user = HttpContext.User;
var claim = (ClaimsIdentity)HttpContext.User.Identity;
var Id = Convert.ToInt32(claim.Claims.Where(x => x.Type.Contains("Id")).FirstOrDefault().Value);
 
参考文献:http://img.tnblog.net/chengpeng/article/details/8052
posted @   microsoft-zhcn  阅读(197)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2021-06-07 WPF 防止UI阻塞 BackgroundWorker
2021-06-07 C# Task(任务调度)
点击右上角即可分享
微信分享提示