.net core 生成jwt+swagger-通过 IHttpContextAccessor读取token信息

news/2024/5/20 0:28:38 标签: .netcore, jwt

1.安装jwt相关包

 <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" />
    <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.0.3" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.0.3" />
  </ItemGroup>

2.appsetting.json配置jwt的验证信息

 "JwtSetting": {
    "Issuer": "pzx", //颁发者
    "Audience": "everyone", //受众
    "SecurityKey": "appapap122344kkappapap122344kkappapap122344kkappapap122344kkappapap122344kkappapap122344kkappapap122344kkappapap122344kk", //密钥
    //token
    //和我配置一样可以拿我生成的token测试 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiSm9obiBEb2UiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9lbWFpbGFkZHJlc3MiOiJqb2huZG9lQGV4YW1wbGUuY29tIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQWRtaW4iLCJleHAiOjE3MDMyNzMwODYsImlzcyI6InB6eCIsImF1ZCI6ImV2ZXJ5b25lIn0.ePY0ZkDQGF1GJWKqiCQjUn2y7aSNG1WesfBH5xPy1Fg"
  }

3.校验token的合法性(在progam文件)

  #region JWT 认证

            builder.Services
              .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              //.AddCustomAuth(o => { })
              .AddJwtBearer(options =>
              {
                  options.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidIssuer = builder.Configuration["JwtSetting:Issuer"],
                      ValidAudience = builder.Configuration["JwtSetting:Audience"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSetting:SecurityKey"]))
                      // 默认允许 300s  的时间偏移量,设置为0
                      //ClockSkew = TimeSpan.Zero,
                      ValidateLifetime = true
                  };
              });

            #endregion JWT 认证

4.在swaggerUI中配置Bearer认证(在progam文件)

 builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

                // 添加Bearer认证支持
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new List<string>()
        }
    });
            });

5.配置SwaggerUI(在progam文件)

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1");
                     //加载api中文注释,true是加载控制器上的注释(须在项目属性-生成勾选生成api文档)
                c.IncludeXmlComments(AppContext.BaseDirectory + Assembly.GetExecutingAssembly().GetName().Name + ".xml", true);
                    // 在Swagger UI中添加Bearer认证输入框
                    c.DisplayRequestDuration();
                    //启动过滤
                    c.EnableFilter();
                    c.EnableDeepLinking();
                    c.EnableValidator();
                    c.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Post, SubmitMethod.Put, SubmitMethod.Patch, SubmitMethod.Delete);
                });

6.添加授权服务 (注意两者的先后顺序)

app.UseAuthentication();
app.UseAuthorization();

7.生成token信息

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

namespace webapi.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController1 : ControllerBase
    {
        private readonly ILogger<WeatherForecastController1> _logger;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public IConfiguration _configuration { get; }

        public WeatherForecastController1(ILogger<WeatherForecastController1> logger, IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _configuration = configuration;
            _httpContextAccessor = httpContextAccessor;
        }

        [HttpGet]
        public int[] Get()
        {
            return new int[] { 1, 2, 3 };
        }

        /// <summary>
        /// 生成token
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public string GenerateToken()
        {
            string issuer = _configuration["JwtSetting:Issuer"];
            string audience = _configuration["JwtSetting:Audience"];
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSetting:SecurityKey"]));
            //使用对称加密算法加密
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            //负载信息
            var claims = new[]
            {
            new Claim(ClaimTypes.Name, "John Doe"),
            new Claim(ClaimTypes.Email, "johndoe@example.com"),
            new Claim(ClaimTypes.Role, "Admin"),
            // 可以添加其他常用的claims,如ClaimTypes.Sid,ClaimTypes.GivenName等
        };

            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                expires: DateTime.Now.AddHours(1),
                signingCredentials: credentials
            );
            var tokenHandler = new JwtSecurityTokenHandler();
            return tokenHandler.WriteToken(token);
        }

        /// <summary>
        ///获取token信息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public IActionResult GetUserInfo()
        {
            var user = _httpContextAccessor.HttpContext.User;

            // 获取用户的名称声明
            var userName = user.Identity.Name;

            // 获取用户的所有声明
            var userClaims = user.Claims;

            // 遍历所有声明并输出
            foreach (var claim in userClaims)
            {
                Console.WriteLine($"Claim Type: {claim.Type}, Claim Value: {claim.Value}");
            }

            return Ok("User information retrieved successfully");
        }
    }
}

8.注入 builder.Services.AddHttpContextAccessor();

 builder.Services.AddHttpContextAccessor();

9.演示
执行如图方法生成token
在这里插入图片描述
10.复制token 填入Authorize输入框格式 Bearer+空格+token

在这里插入图片描述
11.访问方法,获取token里存的claim信息
在这里插入图片描述
为啥httpcontext能读取到token的信息呢?
在一个.NET Core应用程序中,通常使用身份验证和授权来验证用户并控制他们对资源的访问。当用户进行身份验证后,他们通常会收到一个包含有关其身份的信息的令牌(token),例如访问令牌(access token)或身份令牌(identity token)。

这些令牌一般包含在HTTP请求的标头(header)中,例如Authorization标头。在.NET Core应用程序中,HttpContext中的User属性会包含与已验证用户相关的信息,而这些信息通常也包括从令牌中提取的声明(claims)。
end…


http://www.niftyadmin.cn/n/5281058.html

相关文章

R语言贝叶斯网络模型、INLA下的贝叶斯回归、R语言现代贝叶斯统计学方法、R语言混合效应(多水平/层次/嵌套)模型

目录 ㈠ 基于R语言的贝叶斯网络模型的实践技术应用 ㈡ R语言贝叶斯方法在生态环境领域中的高阶技术应用 ㈢ 基于R语言贝叶斯进阶:INLA下的贝叶斯回归、生存分析、随机游走、广义可加模型、极端数据的贝叶斯分析 ㈣ 基于R语言的现代贝叶斯统计学方法&#xff08;贝叶斯参数估…

nodejs+vue+ElementUi医院预约挂号系统3e3g0

本医院预约挂号系统有管理员&#xff0c;医生和用户。该系统将采用B/S结构模式&#xff0c;使用Vue和ElementUI框架搭建前端页面&#xff0c;后端使用Nodejs来搭建服务器&#xff0c;并使用MySQL&#xff0c;通过axios完成前后端的交互 管理员功能有个人中心&#xff0c;用户管…

学习ArcGIS的第一天

文章目录 1 下载安装arcGIS——万事开头难2 阅读菜单和工具栏3 修改保存的相对位置4 加载图层5 arcgis的入门操作5.0 下载数据,并记下存放位置5.1 添加地理数据5.2 保存地图文档- 本文学习ArcGIS的一些基础操作,以中国地图、江苏地图等数据练习ArcGIS的主要基础功能。 - 本文…

IPC之九:使用UNIX Domain Socket进行进程间通信的实例

socket 编程是一种用于网络通信的编程方式&#xff0c;在 socket 的协议族中除了常用的 AF_INET、AF_RAW、AF_NETLINK等以外&#xff0c;还有一个专门用于 IPC 的协议族 AF_UNIX&#xff0c;IPC 是 Linux 编程中一个重要的概念&#xff0c;常用的 IPC 方式有管道、消息队列、共…

json解析之fastjson和jackson使用对比

前言 最近项目中需要做埋点分析&#xff0c;首先就需要对埋点日志进行解析处理&#xff0c;刚好这时候体验对比了下fastjson和jackson两者使用的区别&#xff0c;以下分别是针对同一个json串处理&#xff0c;最终的效果都是将json数据解析出来&#xff0c;并统一展示。 一、fa…

看懂PL/SQL执行计划

看懂PL/SQL执行计划 一&#xff1a;什么是Oracle执行计划&#xff1f; 执行计划是一条查询语句在Oracle中的执行过程或访问路径的描述 二&#xff1a;怎样查看Oracle执行计划&#xff1f; 因为我一直用的PLSQL远程连接的公司数据库&#xff0c;所以这里以PLSQL为例&#xff1…

人工智能-机器学习-深度学习-分类与算法梳理

目前人工智能的概念层出不穷&#xff0c;容易搞混&#xff0c;理清脉络&#xff0c;有益新知识入脑。 为便于梳理&#xff0c;本文只有提纲&#xff0c;且笔者准备仓促&#xff0c;敬请勘误&#xff0c;不甚感激。 人工智能 三大派系 符号主义(Symbolists) 基于逻辑推理的智能…

python 用OpenCV 将图片转视频

import os import cv2 import numpy as npcv2.VideoWriter&#xff08;&#xff09;参数 cv2.VideoWriter() 是 OpenCV 中用于创建视频文件的类。它的参数如下&#xff1a; filename&#xff1a;保存视频的文件名。 fourcc&#xff1a;指定视频编解码器的 FourCC 代码&#xf…