API Session not work with authbasic

Seelight2 years ago

Hi, I'm trying to log in using the session api.
Before it worked because it sent the TOKEN field, but now it's removed and I'm trying to send the username and password. but it does not work.

URL_PORT_TRACCAR = "{{env('URL_PORT_TRACCAR')}}";
    TOKEN_TRACCAR = "{{Auth::user()->username}}:{{Auth::user()->password_text}}"; 

    var ajax = function (method, url, callback) {
      var xhr = new XMLHttpRequest();
      xhr.withCredentials = true;
      xhr.open(method, url, true);
      xhr.setRequestHeader("Authorization", "Basic " + btoa(TOKEN_TRACCAR));
      xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
              if (isJson(xhr.responseText)){
                callback(JSON.parse(xhr.responseText));
              }else{
                callback(false);
              }
            }
      };
      if (method == 'POST') {
          xhr.setRequestHeader('Content-type', 'application/json');
      }
      xhr.send()
    };

    ajax('GET', URL_PORT_TRACCAR + '/api/server', function(server) {
    ajax('GET', URL_PORT_TRACCAR + '/api/session', function(user) {
        if (user.email!='{{Auth::user()->username}}'){
          ajax('DELETE', URL_PORT_TRACCAR+'/api/session', function(server) {
              openWebsocket();
          });
        }else{
          setTimeout(function(){ 
              openWebsocket();
            }, 1500);
        }
        });
    });
Anton Tananaev2 years ago

Which request is not working and what response are you getting? I'm sure you've done some essential troubleshooting before posting. It would be good if you could share all that information and not just the code.

Seelight2 years ago

/api/session request does not work...
And that query returns

HTTP 404 Not Found - WebApplicationException (SessionResource:117 < ...)
Anton Tananaev2 years ago

I see. That's probably because it doesn't use basic authentication. I would recommend checking the API documentation.

Seelight2 years ago

In the example I am using basic authentication that is sent by headers to the api.

xhr.setRequestHeader("Authorization", "Basic " + btoa(TOKEN_TRACCAR));
Anton Tananaev2 years ago

You should use this instead to create a session:

https://www.traccar.org/api-reference/#tag/Session/paths/~1session/post