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

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.hqwc.cn/news/295939.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

蓝牙物联网在汽车领域的应用

I、蓝牙的技术特点 ​ 1998 年 5 月&#xff0c;瑞典爱立信、芬兰诺基亚、日本东芝、美国IBM 和英特尔公司五家著名厂商&#xff0c;在联合拓展短离线通信技术的标准化活动时提出了蓝牙技术的概念。蓝牙工作在无需许可的 2.4GHz 工业频段 (SIM)之上(我国的频段范围为2400.0~248…

VSCode软件与SCL编程

原创 NingChao NCLib 博途工控人平时在哪里技术交流博途工控人社群 VSCode简称VSC&#xff0c;是Visual studio code的缩写&#xff0c;是由微软开发的跨平台的轻量级编辑器&#xff0c;支持几乎所有主流的开发语言的语法高亮、代码智能补全、插件扩展、代码对比等&#xff0c…

AI创作系统ChatGPT系统源码,支持Midjourney绘画,GPT语音对话+DALL-E3文生图

一、前言 SparkAi创作系统是基于ChatGPT进行开发的Ai智能问答系统和Midjourney绘画系统&#xff0c;支持OpenAI-GPT全模型国内AI全模型。本期针对源码系统整体测试下来非常完美&#xff0c;可以说SparkAi是目前国内一款的ChatGPT对接OpenAI软件系统。那么如何搭建部署AI创作Ch…

K8S----RBAC

一、角色、绑定、用户 1、 Role 与ClusterRole 1、Role 总是要在一个命名空间中设置权限,当需要创建一个Role的时候必须指定命名空间; 2、ClusterRole 是非命名空间范围的,不受命名空间局限 2 、RoleBinding 与ClusterRoleBinding 1、RoleBinding 是受命名空间限制的 2、…

持续集成交付CICD:Linux 部署 Jira 9.12.1

目录 一、实验 1.环境 2.K8S master节点部署Jira 3.Jira 初始化设置 4.Jira 使用 一、实验 1.环境 &#xff08;1&#xff09;主机 表1 主机 主机架构版本IP备注master1K8S master节点1.20.6192.168.204.180 jenkins slave &#xff08;从节点&#xff09; jira9.12.1…

set容器的基本使用

文章目录 set默认构造迭代器inserterasefindswapclearlower_bound && upper_boundcountequal_range map和set容器&#xff0c;multimap和multiset是树形结构的关联式容器&#xff0c;这四种容器底层原理都是红黑树&#xff0c;容器中的元素是一个有序序列。 set 1.set…

智能优化算法应用:基于原子轨道搜索算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于原子轨道搜索算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于原子轨道搜索算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.原子轨道搜索算法4.实验参数设定…

ChatGPT 4 实战案例,Excel2021多条件查找

在Excel的使用过程中,查找操作是经常需要完成。例如下列实际需求: 多条件的查找应用,如果不知道用什么公式来完成,可以借助于ChatGPT4来帮忙实现。 Prompt::有一个Excel表格A6至A16为班级,B6至B16为姓名,D6至D16为考核得分,请根据A3单元格的班级和B3单元格的姓名来查找…

九:爬虫-MongoDB基础

MongoDB介绍 MongoDB是一个介于关系数据库和非关系数据库之间的产品&#xff0c;是非关系数据库当中功能最丰富&#xff0c;最像关系数据库的。它支持的数据结构非常松散&#xff0c;因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大&#xff0c;其…

python dash学习2

代码 内有说明&#xff1a; from dash import Dash, html, dcc, callback, Output, Input import plotly.express as px import pandas as pd# 从 Plotly 数据集中读取数据 df pd.read_csv(https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.c…

HarmonyOS构建第一个JS应用(FA模型)

构建第一个JS应用&#xff08;FA模型&#xff09; 创建JS工程 若首次打开DevEco Studio&#xff0c;请点击Create Project创建工程。如果已经打开了一个工程&#xff0c;请在菜单栏选择File > New > Create Project来创建一个新工程。 选择Application应用开发&#xf…

【Spring实战】03 JDBC常用操作

文章目录 1. JdbcTemplate 类1&#xff09;queryForList2&#xff09;update3&#xff09;query4&#xff09;execute5&#xff09;queryForObject 2.代码及执行1&#xff09;代码2&#xff09;执行 3. 优点4. 详细代码总结 Spring JDBC 是 Spring 框架提供的一种用于简化数据库…