我正在撰寫一個在 keycloak 服務器中創建新客戶端的 API。我使用 gocloak 包與 keycloak 服務器互動。起初我將訪問令牌從 gocloak.Login() func 傳遞給 gocloak.CreateClient() 并得到一個 403 錯誤,之后我使用來自 gocloak.LoginAdmin() 的訪問令牌并且它起作用了,它確實創建了一個新的客戶。那么是什么讓 gocloak.Login() 回傳的訪問令牌失敗了呢?
代碼:
func main() {
newClientID := "new_client"
client := gocloak.NewClient("http://localhost:8080")
// The access token returned from Login() causes 403 error
jwt, _ := client.Login(context.Background(), "my-go-service", "vizhhp0qnDGaiq4k0aOzzn4RaaqSwU2b", "master", "admin", "Pa55w0rd")
_, err := client.CreateClient(context.Background(), jwt.AccessToken, "demorealm", gocloak.Client{ ClientID: &newClientID})
if err != nil {
fmt.Println(err.Error())
}
// And the access token returned from LoginAdmin() works
jwt, _ = client.LoginAdmin(context.Background(), "admin", "Pa55w0rd", "master")
clientID, err := client.CreateClient(context.Background(), jwt.AccessToken, "demorealm", gocloak.Client{ ClientID: &newClientID})
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Printf("Client %s created", clientID)
}
}
結果:
403 Forbidden: unknown_error
Client d869fd8d-e5f0-4567-99de-69ccc4403705 created
uj5u.com熱心網友回復:
要使用允許創建客戶端的Keycloak Admin API,您需要使用admin-cli客戶端。
這就是為什么:
jwt, _ = client.LoginAdmin(context.Background(), "admin", "Pa55w0rd", "master")
之所以有效,是因為 LoginAdmin 呼叫了 admin-cli,而:
jwt, _ := client.Login(context.Background(), "my-go-service", "vizhhp0qnDGaiq4k0aOzzn4RaaqSwU2b", "master", "admin", "Pa55w0rd")
is requesting a token from client "my-go-service", which is not allowed to perform calls to the Admin Rest API. Hence:
403 Forbidden: unknown_error
If you look at the LoginAdmin implementation you can confirm what I have said:
// LoginAdmin performs a login with Admin client
func (client *gocloak) LoginAdmin(ctx context.Context, username, password, realm string) (*JWT, error) {
return client.GetToken(ctx, realm, TokenOptions{
ClientID: StringP(adminClientID),
GrantType: StringP("password"),
Username: &username,
Password: &password,
})
}
where
adminClientID string = "admin-cli"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493423.html
標籤:休息 去 钥匙斗篷 keycloak-rest-api
