Handling server authentication


#1

I am trying to make a POST request to a url like:

http://user:user@1234@testapi.com/resource/json

Where user and user@1234 are username and password required to access server. I am getting 401 error.

What I have tried so far is:

Try 1;

public login(credentials) {
      let username: string = 'user';
      let password: string = 'user@1234';
      let headers: Headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(username + ":" + password));
      headers.append("Content-Type", "application/x-www-form-urlencoded");
      return this.http.post('http://testapi.com/resource/json', loginServiceData, { headers: headers })
        .map((response: Response) => {
          // login successful if there's a jwt token in the response
          let reply = response.json();
          let valid = false;
          let comment = "";
          if (reply) {
            if (reply.error === 0) {
              // store user details and jwt token in local storage to keep user logged in between page refreshes
              valid = true;
            }
            else {
              comment = reply.message;
            }

            return { valid: reply.valid, comment: reply.comment };
          }
        });
  }

Try 2;

public login(credentials) {
          return this.http.post('http://user:user@1234@testapi.com/resource/json', loginServiceData, { headers: headers })
            .map((response: Response) => {
              // login successful if there's a jwt token in the response
              let reply = response.json();
              let valid = false;
              let comment = "";
              if (reply) {
                if (reply.error === 0) {
                  // store user details and jwt token in local storage to keep user logged in between page refreshes
                  valid = true;
                }
                else {
                  comment = reply.message;
                }

                return { valid: reply.valid, comment: reply.comment };
              }
            });
      }

#2

I think the password is only “1234” and username is “user”.

Setting the Basic Authentication stuff as Authorization header looks like the correct way to do this.


#3

The password is user@1234. The authorization header is not getting appended to request headers. When using chrome, I am not able to find the authorization header set by me.


#4

What happens if you switch to https?