.Net 实操将Token存入Session

一、参考

.NET Session - 掘金 (juejin.cn)

.NET 让Swagger中带JWT报文头 - 掘金 (juejin.cn)

.NET ActionFilter行为过滤器 - 掘金 (juejin.cn)

二、环境搭建

2.1 依赖下载

Microsoft.AspNetCore.Session

2.2 服务注册

主要注册了过滤器ActionApiFilterJWT请求头Session服务

ini 复制代码
using Microsoft.AspNetCore.Http;
using Microsoft.OpenApi.Models;
using Token1;

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(s =>
{
    //添加安全定义
    s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "请输入token,格式为 Bearer xxxxxxxx(注意中间必须有空格)",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    //添加安全要求
    s.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme{
                Reference =new OpenApiReference{
                    Type = ReferenceType.SecurityScheme,
                    Id ="Bearer"
                }
            },new string[]{ }
        }
    });
});

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

builder.Services.AddControllers(o => o.Filters.Add(typeof(ActionApiFilter)));

var app = builder.Build();
app.UseSession();

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

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

2.3 创建过滤器

当用户的请求头中捎带了Token时,就将其存入Session

csharp 复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net.WebSockets;

namespace Token1
{
    public class ActionApiFilter : ControllerBase, IAsyncActionFilter
    {

        private readonly ILogger<ActionApiFilter> logger;
        private readonly IHttpContextAccessor httpContextAccessor_;
        public ActionApiFilter(ILogger<ActionApiFilter> logger, IHttpContextAccessor httpContextAccessor_)
        {
            this.logger = logger;
            this.httpContextAccessor_ = httpContextAccessor_;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string token = context.HttpContext.Request.Headers["Authorization"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                string value = token.Split(' ').Last();
                await Console.Out.WriteLineAsync($"token:" + value);
                // 存入session
                httpContextAccessor_.HttpContext.Session.SetString("value", value);
            }
            else
            {
                await Console.Out.WriteLineAsync($"no token");
            }
            ActionExecutedContext actionExecutedContext = await next.Invoke();
        }
    }
}

2.4 创建控制器

创建了Set和Get方法,模拟Session的存取

csharp 复制代码
using Microsoft.AspNetCore.Mvc;

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

        [HttpGet]
        public void Set()
        {
        }

        [HttpGet]
        public object Get()
        {
            return HttpContext.Session.GetString("value");
        }
    }
}

三、测试

填写token信息,此后每次加载请求头都会捎带

此时Seesion已存入token

注销请求头,去除Get对Set的影响(如果不注销,那么Get方法也会捎带token,会覆盖Set内容)

成功获取

此时再用postman测试一次,模拟不同用户访问

成功获取对应token

此时再访问用户1,内容不变,表明不同用户存取的session不同

相关推荐
梁下轻语的秋缘21 小时前
ESP32-WROOM-32E存储全解析:RAM/Flash/SD卡读写与速度对比
java·后端·spring
wanzhong233321 小时前
开发日记8-优化接口使其更规范
java·后端·springboot
羊小猪~~1 天前
【QT】--文件操作
前端·数据库·c++·后端·qt·qt6.3
张彦峰ZYF1 天前
商品供给域的工程化简要设计考量
后端·系统架构·商品模型·商品供给
小北方城市网1 天前
微服务注册中心与配置中心实战(Nacos 版):实现服务治理与配置统一
人工智能·后端·安全·职场和发展·wpf·restful
爬山算法1 天前
Hibernate(47)Hibernate的会话范围(Scope)如何控制?
java·后端·hibernate
源码宝1 天前
云HIS二次开发实施路径指南
后端·源码·二次开发·saas·云his·医院信息系统
李慕婉学姐1 天前
Springboot旅游景点管理系统2fj40iq6(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
蓝眸少年CY1 天前
(第八篇)spring cloud之zuul路由网关
后端·spring·spring cloud
long3161 天前
弗洛伊德·沃肖算法 Floyd Warshall Algorithm
java·后端·算法·spring·springboot·图论