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

Docker部署Ory Kratos:按用户名密码Schema创建身份并测试登录

实现用户名密码式身份创建与登录测试

一、修改身份创建代码(添加用户名密码凭证)

先确认你的Ory Kratos已配置支持用户名密码的身份Schema(比如ID为username_password,需确保Schema包含username字段与密码凭证规则)。修改原有代码,新增凭证配置与用户名字段:

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/ory/kratos-client-go"
)

func main() {
	configuration := ory.NewConfiguration()
	configuration.Servers = []ory.ServerConfiguration{
		{URL: "http://localhost:4433"}, // 你的Kratos Admin API地址
	}
	apiClient := ory.NewAPIClient(configuration)

	// 构建创建身份的请求体
	createIdentityBody := *ory.NewCreateIdentityBody(
		"username_password", // 替换为实际的用户名密码Schema ID
		map[string]interface{}{
			"email":    "user6@example.com",
			"username": "user6", // 新增用户名字段,匹配Schema定义
			"name": map[string]string{
				"first": "user6",
				"last":  "user66",
			},
		},
	)
	// 添加密码凭证配置
	passwordConfig := ory.NewIdentityCredentialsPasswordConfig("your_secure_password") // 替换为实际密码
	passwordCredential := ory.NewIdentityCredentials("password", passwordConfig)
	createIdentityBody.SetCredentials(map[string]ory.IdentityCredentials{"password": *passwordCredential})

	// 调用API创建身份
	createdIdentity, r, err := apiClient.IdentityApi.CreateIdentity(context.Background()).CreateIdentityBody(createIdentityBody).Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "创建身份失败: %v\n", err)
		fmt.Fprintf(os.Stderr, "HTTP响应详情: %v\n", r)
		return
	}
	fmt.Printf("已创建身份,ID: %s\n", createdIdentity.Id)
}

关键修改说明

  • 替换Schema ID为你配置的用户名密码类型Schema
  • Traits中新增username字段,需与Schema定义完全匹配
  • 通过SetCredentials显式添加密码凭证,指定用户密码

二、登录测试代码实现

登录流程分为初始化登录流、提交登录凭证两步:

func testLogin() {
	configuration := ory.NewConfiguration()
	configuration.Servers = []ory.ServerConfiguration{
		{URL: "http://localhost:4434"}, // Kratos Public API地址
	}
	apiClient := ory.NewAPIClient(configuration)
	ctx := context.Background()

	// 1. 初始化登录流
	loginFlow, r, err := apiClient.FrontendApi.CreateLoginFlow(ctx).Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "初始化登录流失败: %v\n", err)
		fmt.Fprintf(os.Stderr, "HTTP响应详情: %v\n", r)
		return
	}

	// 2. 构建登录请求体
	loginBody := ory.NewSubmitSelfServiceLoginFlowBody("password")
	loginBody.SetIdentifier("user6") // 填写用户名或邮箱,匹配Schema配置
	loginBody.SetPassword("your_secure_password") // 对应创建身份时的密码
	loginBody.SetFlow(loginFlow.Id)

	// 3. 提交登录请求
	loginResponse, r, err := apiClient.FrontendApi.SubmitSelfServiceLoginFlow(ctx).Flow(loginFlow.Id).SubmitSelfServiceLoginFlowBody(*loginBody).Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "登录失败: %v\n", err)
		fmt.Fprintf(os.Stderr, "HTTP响应详情: %v\n", r)
		return
	}

	// 输出登录成功信息
	if loginResponse.Session != nil {
		fmt.Printf("登录成功!用户ID: %s\n", loginResponse.Session.Identity.Id)
		fmt.Printf("会话有效期至: %s\n", loginResponse.Session.ExpiresAt)
	}
}

三、注意事项

  • 确保Kratos的Admin API(默认4433端口)和Public API(默认4434端口)地址正确
  • 提前确认身份Schema的字段定义,避免Traits或凭证配置不匹配
  • 生产环境中禁止硬编码密码,建议从环境变量或加密配置文件读取
  • 登录测试必须使用Public API,Admin API不处理前端登录流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:15:07