blob: e4c59bc2f1fefc26aae4efa1dfb06529c24cbe15 [file] [log] [blame]
ktimoney3570d5a2022-05-24 13:54:55 +01001// -
2// ========================LICENSE_START=================================
3// O-RAN-SC
4// %%
5// Copyright (C) 2022: Nordix Foundation
6// %%
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
10//
11// http://www.apache.org/licenses/LICENSE-2.0
12//
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===================================
19//
20
ktimoney8ead72a2022-04-12 15:10:10 +010021package main
22
23import (
24 "encoding/json"
25 "fmt"
26 "io/ioutil"
27 "net/http"
28 "net/url"
29)
30
31type Jwttoken struct {
32 Access_token string
33 Expires_in int
34 Refresh_expires_in int
35 Refresh_token string
36 Token_type string
37 Not_before_policy int
38 Session_state string
39 Scope string
40}
41
42var jwt Jwttoken
43
44func getToken(auth_code string) string {
45 clientSecret := "Ctz6aBahmjQvAt7Lwgg8qDNsniuPkNCC"
46 clientId := "jwtsecret"
47 realmName := "jwtrealm"
48 keycloakHost := "keycloak"
49 keycloakPort := "8080"
50 keycloakUrl := "http://" + keycloakHost + ":" + keycloakPort + "/auth/realms/" + realmName + "/protocol/openid-connect/token"
51 resp, err := http.PostForm(keycloakUrl,
52 url.Values{"code": {auth_code}, "grant_type": {"authorization_code"},
53 "client_id": {clientId}, "client_secret": {clientSecret}})
54 if err != nil {
55 fmt.Println(err)
56 panic("Something wrong with the credentials or url ")
57 }
58 defer resp.Body.Close()
59 body, err := ioutil.ReadAll(resp.Body)
60 fmt.Println(string(body))
61 json.Unmarshal([]byte(body), &jwt)
62 return jwt.Access_token
63}
64
65func noprefix(res http.ResponseWriter, req *http.Request) {
66 // create response binary data
67 data := []byte("Authorization code default") // slice of bytes
68 // write `data` to response
69 res.Write(data)
70}
71
72func callback(res http.ResponseWriter, req *http.Request) {
73 query := req.URL.Query()
74 code := query.Get("code")
75 token := getToken(code)
76 res.WriteHeader(http.StatusOK)
77 res.Write([]byte(token))
78}
79
80func main() {
81 // create a new handler
82 callbackHandler := http.HandlerFunc(callback)
83 http.Handle("/callback", callbackHandler)
84 noPrefixHandler := http.HandlerFunc(noprefix)
85 http.Handle("/", noPrefixHandler)
86 http.ListenAndServe(":9000", nil)
87}