曲线球会话中端软件
此软件包增加了对会话的支持 曲线球 框架.
特征 :
- 懒去来. 只有店里有东西,它才会开始会话.
- 如果空出会话数据, 也会自动擦除会话数据 .
- 它提供了生成和验证CSRF令牌的功能.
安装
npm install @curveball/session
从0.5和以下版本升级
如果您正在从0.5.x版本或更早的版本升级, 此软件包将引入 a 业连间休息自0.6起.
0.5会话数据见 ctx.state.session 财务报告和审定财务报表
ctx.state.sessionId但是这个已经移到 ctx.session 财务报告和审定财务报表
ctx.sessionId。 。 。 .
开始
添加中间软件
import session from '@curveball/session';
app.use(session({
store: 'memory',
});
这将在曲线球上添加内元会话存储 。 这家店主要是 是用来测试的.
下面是另一个有更多选项的例子:
import session from '@curveball/session';
app.use(session({
store: 'memory',
cookieName: 'MY_SESSION',
expiry: 7200,
cookieOptions: {
secure: true,
path: '/',
sameSite: true,
},
});
cookieName- 更新HTTP Cookie的名称。 这是CB默认.expiry- 会话消失前的不活动秒数. 这是3600秒默认。 它只涉及人类的寿命 它不会影响饼干参数.cookieOptions- 如果设置了, 将覆盖默认的 cookie 选项 。 名单 支持选项的文档中可找到 [cookie] 软件包 [3].
使用会话存储器
在自己的控制器和中间软件中,可以设置并更新会话数据
通过 ctx.session 属性.
app.use( ctx => {
// Running this will create the session
ctx.session = { userId: 5 };
ctx.response.body = 'Hello world';
});
删除会话
要删除一个开放式会话,只需清除会话数据:
app.use( ctx => {
// Running this will create the session
ctx.session = null;
});
重新生成会话编号 .
如果您清除了会话 ID, 但还有数据, 中间软件会 删除旧会话并自动创建新会话 id:
app.use( ctx => {
// This will kill the old session and start a new one with the same data.
ctx.sessionId = null;
});
CSRF 符号支持
要获得表格的CSRF令牌,中间软件提供 getCsrf() 函数 :
app.use( async ctx => {
// Obtain a CSRF token for HTML forms:
const csrfToken = await ctx.getCsrf();
});
建议将这个符号嵌入到 HTML 格式中:
<input type="hidden" name="csrf-token" value="....token goes here" />
然后继续 POST 请求中,您可以很容易地用 validateCsrf
函数。 如果符号不正确, 将自动导致 403
错误 :
app.use(route.post('/form-submit', ctx => {
// Throws error if csrf-token was not supplied or incorrect
ctx.validateCsrf();
}));
API 密码
宜自创店铺作产品用. 最后这个 工程可能还会再添加几个默认存储 .
在此之前,您必须执行以下接口:
interface SessionStore {
set(id: string, values: SessionValues, expire: number): Promise<void>;
get(id: string): Promise<SessionValues>,
delete(id: string): Promise<void>,
newSessionId(): Promise<string>,
}
SessionValues 仅仅是一个按键 > 值对象. expire 表示为unix
时间戳.