My goal is to create a static page with GitHub Pages with a simple button.
When I press this button, I want to create a file in the same repository, in the same branch used for GitHub pages.
I read something about Authorization Token to be used in the fetch request to create the file, so I created my Token, I put it into the index.html of the GitHub pages I'm using to access the repository.
Very soon I received an email from GitHub telling me this token is revoked.
The policy is described here: https://github.blog/2015-02-05-keeping-github-oauth-tokens-safe/
My question now is: how can I accomplish this task?
The snippet I was using is the following:
async function createNewFileFunction() {
const user = { name: 'XXX', surname: 'YYY' };
const token = 'ghp_abcdefghijklmnopqrstuvwxyz1234567890';
const api_url = "https://api.github.com/repos/my_account/my_repo/contents/test.txt?ref=gh-pages";
try {
const response = await fetch(api_url, {
method: 'POST',
headers: {
'Authorization': `token ${token}`,
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(user)
}
);
console.log(await response.json());
} catch (error) {
console.log('Request Failed', error);
}
}
You put the token in the index.html file and this means the world can see the token. That is why you received the message for GitHub as you exposed a token.
GitHub Pages does not support backend code. This means everything is public. You cannot use GitHub Pages to support methods that require a token. The code in a page is executed in the user's browser. You will need to implement backend code or use GitHub Authentication.
Backend code could be a web server, a cloud function like AWS Lambda, or several other services. However, this has a security weakness if you are not using authorization as anyone can call your backend endpoint.
Review these links for GitHub Authentication.