I followed the steps described at https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ and have it pretty much copy-pasted.
I have a login page with the following form:
...
<form class="login_form" id="login_form">
<div class="username_div">
<input type="text" id="username_id" name="username" placeholder="Username"><br>
</div>
<div class="password_div">
<input type="password" id="password_id" name="password" placeholder="Password">
</div>
<div class="btn_div">
<input type="button" id="btn_id" value="Login" class="login_btn" onclick="token()">
</div>
</form>
...
I have a js file which can successfully get the token:
function token() {
fetch('/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'username=test&password=test'
}).then(res => {
return res.json();
}).then(json => {
console.log(json['access_token']);
});
}
Now when I add
window.location.href = "/users/me/";
after the console.log(json['access_token]);
I get a "not authenticated".
As far as I understand I need to somehow pass the token to the fastapi part. How do I do that?
EDIT:
So I got a couple of things confused here. But I am now able to print the user data by using the following code:
function token() {
fetch('/token', {
method: 'POST',
headers: {
'accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=&username=test&password=test&scope=&client_id=&client_secret='
}).then(res => {
return res.json();
}).then(json => {
console.log(json['access_token']);
fetch('/users/me', {
method: 'GET',
headers: {
'accept': 'application/json',
'Authorization': 'Bearer ' + json['access_token']
}
}).then(res => {
return res.json();
}).then(json => {
console.log(json);
});
});
}
I still don't know how to get to a new page (that needs authorization) after adding my credentials in my login page. Could you help me out here?