Using a post API request I want to receive a JWT token for the response.
For that, I want to send the username and password as JSON body input to the API. The username and password should be taken dynamically from the user as a JSON payload.
Currently, I am hardcoding the user name and password using strings.NewReader which is not suitable as this is a web application and many users will be using it.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/joho/godotenv"
)
var authToken string
type authorization struct {
AuthorizationToken string `json:"authorizationToken"`
ExpiresTimestamp string `json:"expiresTimestamp"`
}
func main() {
enverr := godotenv.Load(".env")
if enverr != nil {
fmt.Println("Error loading .env file")
os.Exit(1)
}
token()
}
func token() {
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.NewReader(`
{
"name" : "testuser",
"pwd" : "testpwd",
"hName" : "hname"
}
`)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
if err != nil {
panic(err)
}
defer response.Body.Close()
content, _ := ioutil.ReadAll(response.Body)
var result authorization
if err := json.Unmarshal(content, &result); err != nil { // Parse []byte to the go struct pointer
fmt.Println("Can not unmarshal JSON")
}
authToken := result.AuthorizationToken
fmt.Println(PrettyPrint(authToken))
}
func PrettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
CodePudding user response:
You can use http requests body (for POST request)
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
c := Credentials{}
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
err: = decoder.Decode(&c)
if err!=nil{
// handle it
}
// use it
fmt.Println(c.Username, c.Password)
CodePudding user response:
If you are intending to distribute the application as an executable (aka command line in the Unix world), you can either:
Provide the username and password as program arguments,
os.Args
(omitting unchanged code):var inputTemplate = ` { "name" : "USER", "pwd" : "PWD", "hName" : "hname" } ` func token() { authorizationUrl := os.Getenv("authorizationUrl") requestBody := strings.Replace(strings.Replace(inputTemplate, "PWD", os.Args[2], -1), "USER", os.Args[1], -1) response, err := http.Post(authorizationUrl, "application/json", requestBody) // ... }
You should then be able to run your program (once compiled):
./filename user password
Or as better alternative, having sensitive data involved, have the username and password input from standard input with password being echoed (hiding the characters):
import ( // ... "syscall" "golang.org/x/term" ) var inputTemplate = ` { "name" : "USER", "pwd" : "PWD", "hName" : "hname" } ` func token() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter username: ") username := reader.ReadString('\n') // handle error fmt.Print("Enter password: ") pwdbytes := term.ReadPassword(int(syscall.Stdin)) password := string(pwdbytes) authorizationUrl := os.Getenv("authorizationUrl") requestBody := strings.Replace(strings.Replace(inputTemplate, "PWD", password, -1), "USER", username, -1) response, err := http.Post(authorizationUrl, "application/json", requestBody) // ... }