.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不同

相关推荐
kyle~11 分钟前
Swagger ---基于 描述文件 生成 交互式API文档 的工具
前端·后端·规格说明书·说明文档
江畔柳前堤8 小时前
GO01-Go 语言与主流编程语言深度对比
开发语言·人工智能·后端·微服务·云原生·golang·go
世界哪有真情9 小时前
拿人类意识卡 AI?等于用 bug 验收正式产品
前端·人工智能·后端
Csvn11 小时前
Day 3:LIKE 与模式匹配 — 让查询学会"模糊搜索"
后端·sql
Hazenix12 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦12 小时前
GO_复合类型---指针
开发语言·后端·golang
IT_陈寒12 小时前
SpringBoot自动装配坑了我一天,原来问题出在这
前端·人工智能·后端
星栈13 小时前
深度复盘:比 EventLoop 更隐蔽!Node 微任务堆积引发的线上接口雪崩事故
后端·node.js
名字还没想好☜14 小时前
Go slice 的 append 陷阱:共享底层数组导致的数据串改
开发语言·后端·golang·go·slice
诸神缄默不语14 小时前
FastAPI后端配置CORS中间件支持浏览器跨域访问
后端·fastapi