V
V
Vadim2018-06-19 15:04:43
JavaScript
Vadim, 2018-06-19 15:04:43

How to access a password-protected API without setting the password in JS?

Hello. I wrote a backend for a web application that gives JSON and I want to display it on the page. I created an authorization page for accessing JSON and in order to receive it and display it, the following code was written.

fetch('/json', {
        method: 'POST',
        body: new URLSearchParams("password=test")
    })
        .then(res => res.json())
        .then((out) => {
            document.getElementsByTagName('textarea')[0].innerHTML = out.Items.join("\n");
        })
        .catch(err => { throw err; });

The problem is that the password to the authorization page is visible in the clear on the user's side. Here is the handler code that handles this on the server side.body: new URLSearchParams("password=test")
func sendJSONHandler(w http.ResponseWriter, r *http.Request) {
  if r.Method == "GET" {
    http.ServeFile(w, r, "template/api/api.html")
  } else if r.Method == "POST" {
    r.ParseForm()
    if r.Form["password"][0] == apiPassword {
      j := struct {
        Items []string
      }{Items: code.Struct.Field}
      w.Header().Set("Access-Control-Allow-Origin", "*")
      json.NewEncoder(w).Encode(j)
    } else {
      http.ServeFile(w, r, "template/api/api.html")
    }
  }
}

Authorization page code.
<form action="/json" method="post">
  <input class="form-control" type="password" name="password" id="passinput" placeholder="Password" required>
  <input class="btn btn-outline-danger" type="submit" value="ENTER" id="subm">
</form>

How to hide password in JS? Or is there a better solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-06-19
@trigun117

OAuth, jwt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question