2 // ========================LICENSE_START=================================
5 // Copyright (C) 2023: Nordix Foundation
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 // ========================LICENSE_END===================================
30 "oransc.org/nonrtric/capifcore/internal/config"
33 //go:generate mockery --name AccessManagement
34 type AccessManagement interface {
35 // Get JWT token for a client.
36 // Returns JWT token if client exits and credentials are correct otherwise returns error.
37 GetToken(clientId, clientPassword, scope string, realm string) (Jwttoken, error)
40 type KeycloakManager struct {
41 keycloakServerUrl string
42 realms map[string]string
45 func NewKeycloakManager(cfg *config.Config) *KeycloakManager {
47 keycloakUrl := "http://" + cfg.AuthorizationServer.Host + ":" + cfg.AuthorizationServer.Port
49 return &KeycloakManager{
50 keycloakServerUrl: keycloakUrl,
51 realms: cfg.AuthorizationServer.Realms,
55 type Jwttoken struct {
56 AccessToken string `json:"access_token"`
57 IDToken string `json:"id_token"`
58 ExpiresIn int `json:"expires_in"`
59 RefreshExpiresIn int `json:"refresh_expires_in"`
60 RefreshToken string `json:"refresh_token"`
61 TokenType string `json:"token_type"`
62 NotBeforePolicy int `json:"not-before-policy"`
63 SessionState string `json:"session_state"`
64 Scope string `json:"scope"`
67 func (km *KeycloakManager) GetToken(clientId, clientPassword, scope string, realm string) (Jwttoken, error) {
69 getTokenUrl := km.keycloakServerUrl + "/realms/" + realm + "/protocol/openid-connect/token"
71 resp, err := http.PostForm(getTokenUrl,
72 url.Values{"grant_type": {"client_credentials"}, "client_id": {clientId}, "client_secret": {clientPassword}})
78 defer resp.Body.Close()
79 body, err := io.ReadAll(resp.Body)
84 if resp.StatusCode != http.StatusOK {
85 return jwt, errors.New(string(body))
88 json.Unmarshal([]byte(body), &jwt)