You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ORY Kratos Go SDK创建用户时密码设置与会话获取问题

ORY Go客户端注册逻辑问题解决方案

1. 创建用户时设置密码的正确方式

密码不属于用户自定义traits字段,不要把密码写入traits map。密码是身份的内置凭证,需要通过AdminCreateIdentityBody的Credentials字段配置,指定凭证类型为password,传入明文密码后ORY会自动完成哈希存储,不需要手动处理加密逻辑。
修正后的身份创建代码如下:

var newIdentity models.NewIdentity
err := fctx.BodyParser(&newIdentity)
if err != nil {
    c.Log.Error("请求参数解析失败: %s", err.Error())
    return err
}

adminCreateIdentityBody := *ory.NewAdminCreateIdentityBody(
    "default",
    map[string]interface{}{
        "email": newIdentity.Email,
        "name": map[string]string{
            "first": newIdentity.Name.First,
            "last":  newIdentity.Name.Last,
        },
    },
)

// 配置密码凭证
adminCreateIdentityBody.Credentials = map[string]models.AdminCreateIdentityBodyCredentials{
    "password": {
        Config: map[string]interface{}{
            "password": newIdentity.Password, // 接收前端传入的明文密码
        },
    },
}

createdIdentity, resp, err := c.OryAdminApiClient.V0alpha2Api.AdminCreateIdentity(context.Background()).
    AdminCreateIdentityBody(adminCreateIdentityBody).
    Execute()
if err != nil {
    c.Log.Error("用户身份创建失败: %s", err.Error())
    return err
}

注意提前在自定义的models.NewIdentity结构体中添加Password string字段,用于接收前端传入的密码参数。

2. 创建用户后生成有效会话返回客户端

身份创建完成后,不需要走常规登录接口校验密码,直接调用管理端的创建会话接口,传入刚生成的用户ID,即可拿到已激活的有效会话,和正常登录生成的会话权限完全一致。
会话生成代码如下:

// 为新创建的用户生成有效会话
activeSession, _, err := c.OryAdminApiClient.V0alpha2Api.AdminCreateSession(context.Background()).
    AdminCreateSessionBody(models.AdminCreateSessionBody{
        IdentityId: createdIdentity.Id,
    }).
    Execute()
if err != nil {
    c.Log.Error("用户会话创建失败: %s", err.Error())
    return err
}

// 将会话凭证返回给客户端即可
// 客户端后续请求携带 `Authorization: Bearer <session_token>` 或者对应Cookie即可通过鉴权校验
return c.JSON(200, map[string]interface{}{
    "session_token": *activeSession.Token,
    "session":       activeSession,
    "user_info":     createdIdentity,
})

如果你的服务作为BFF层代理ORY接口,直接把接口返回的Set-Cookie头透传给客户端也可以,和前端走自建登录流程拿到的鉴权凭证没有区别。


内容的提问来源于stack exchange,提问作者sorohimm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 23:40:37