Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api Invalid Token #34

Open
MattWanjia opened this issue Jun 13, 2024 · 3 comments
Open

Api Invalid Token #34

MattWanjia opened this issue Jun 13, 2024 · 3 comments

Comments

@MattWanjia
Copy link

I am building a new Frontend for the ots api but at each turn i am getting "invalid token" and "unauthorized as response"

what could be the issue i habve attached my code below. This smae request works with postman.

export const getEUDSWithBasicAuth = async (csrfToken) => {
//console.log(csrfToken)
const username = 'administrator';
const password = 'password';
const basicAuth = 'Basic ' + btoa(username + ':' + password);

try {
const response = await api.get('/eud', {
withCredentials: true,
headers: {
'Authorization': basicAuth,
//'XSRF-TOKEN': ${csrfToken},
"XSRF-TOKEN":"ImI5N2ExZTVkZWM5YTVmZWFkYTE0ZmFlMzIzNWRkODA5YTcwODFlMDgi.ZmqvSw.YnmEd_Qx1iYASXa1QdD-ISUB-KE"
}
});

print(response)

return response;

} catch (error) {
console.error("Error status:", error?.response?.status);
console.error("Error data:", error?.response?.data);
throw error;
}
};

@brian7704
Copy link
Owner

OpenTAKServer uses sessions, not basic auth. First you need to make a GET request to /api/login with the Content-Type: application/json header. The response will include an XSRF token. Subsequent requests need to include that token in the XSRF-TOKEN header. Then you need to make a POST to /api/login with the Content-Type: application/json header and a json body with the username and password `{'username': 'administrator', 'password': 'password'}

@MattWanjia
Copy link
Author

MattWanjia commented Jun 14, 2024

`import` axios from "axios";

const API_BASE_URL = "http://192.168.1.107:8080/api";

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 5000,
});

export const getToken = async () => {
  try {
    const response = await api.get("/login", {
      headers: {
        "Content-Type": "application/json"
      }
    });
    return response;
  } catch (error) {
    throw error.response;
  }
};

export const loginUser = async (userData, csrfToken) => {
  try {
    const response = await api.post("/login", userData, {
      headers: {
        "XSRF-TOKEN": csrfToken,
        "Content-Type": "application/json"
      },
    });
    return response;
  } catch (error) {
    throw error.response;
  }
};

export const getEUDS = async (csrfToken) => {
    let user = {
      username: "administrator",
      password: "password"
    }

    try {
    const response = await api.get("/eud", {
      withCredentials: true,
      headers: {
        "XSRF-TOKEN": csrfToken,
      },
    });

    return response;
  } catch (error) {
    console.error("Error status:", error?.response?.status);
    console.error("Error data:", error?.response?.data);
    throw error;
  }
};

here is my api.jsx

"use client";
import React, { useEffect } from "react";
import { useTokenStore } from "@/store/storage";
import {
  getEUDS,
  fetchDevices,
  loginUser,
  getToken,
} from "@/api/api";

export default function Euds() {
  const token = useTokenStore((state) => state.token);

  useEffect(() => {
    //console.log(token);

    fetchEUDs();
  }, []);

  const fetchEUDs = async () => {
    await getToken().then(async (res) => {
      //console.log(res.data);

      let data = {
        username: "administrator",
        password: "password"
      }
      
      await loginUser(data, res.data.response.csrf_token).then(async (response) => {
        //console.log(res.data)
  
        let res1 = await getEUDS(response.data.response.csrf_token);
  
        console.log(res1);
      });
    });
  };

  return <div>Euds</div>;
}

this is my page.

im still getiing an error 401 unauthorized

@brian7704
Copy link
Owner

Your code seems good so I went back to look how the UI logs in. Here is its axios.create()

export default axios.create({
  withCredentials: true,
  withXSRFToken: true,
  maxRedirects: 0,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
});

Try adding those properties to your axios.create() and see if that helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants