| // - |
| // ========================LICENSE_START================================= |
| // O-RAN-SC |
| // %% |
| // Copyright (C) 2022: Nordix Foundation |
| // %% |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| // ========================LICENSE_END=================================== |
| // |
| |
| package main |
| |
| import ( |
| "encoding/json" |
| "fmt" |
| "io/ioutil" |
| "net/http" |
| "net/url" |
| ) |
| |
| type Jwttoken struct { |
| Access_token string |
| Expires_in int |
| Refresh_expires_in int |
| Refresh_token string |
| Token_type string |
| Not_before_policy int |
| Session_state string |
| Scope string |
| } |
| |
| var jwt Jwttoken |
| |
| func getToken(auth_code string) string { |
| clientSecret := "Ctz6aBahmjQvAt7Lwgg8qDNsniuPkNCC" |
| clientId := "jwtsecret" |
| realmName := "jwtrealm" |
| keycloakHost := "keycloak" |
| keycloakPort := "8080" |
| keycloakUrl := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName + "/protocol/openid-connect/token" |
| resp, err := http.PostForm(keycloakUrl, |
| url.Values{"code": {auth_code}, "grant_type": {"authorization_code"}, |
| "client_id": {clientId}, "client_secret": {clientSecret}}) |
| if err != nil { |
| fmt.Println(err) |
| panic("Something wrong with the credentials or url ") |
| } |
| defer resp.Body.Close() |
| body, err := ioutil.ReadAll(resp.Body) |
| fmt.Println(string(body)) |
| json.Unmarshal([]byte(body), &jwt) |
| return jwt.Access_token |
| } |
| |
| func noprefix(res http.ResponseWriter, req *http.Request) { |
| // create response binary data |
| data := []byte("Authorization code default") // slice of bytes |
| // write `data` to response |
| res.Write(data) |
| } |
| |
| func callback(res http.ResponseWriter, req *http.Request) { |
| query := req.URL.Query() |
| code := query.Get("code") |
| token := getToken(code) |
| res.WriteHeader(http.StatusOK) |
| res.Write([]byte(token)) |
| } |
| |
| func main() { |
| // create a new handler |
| callbackHandler := http.HandlerFunc(callback) |
| http.Handle("/callback", callbackHandler) |
| noPrefixHandler := http.HandlerFunc(noprefix) |
| http.Handle("/", noPrefixHandler) |
| http.ListenAndServe(":9000", nil) |
| } |