My goal is to create a React JS login page that runs off a json Rest service. In Postman, when I enter the URL for the service, set it to run as POST and enter the following JSO
Don't put your authorization token in the body. Put it in the Headers. The first function is going to pass in username, password, and authentication type (ie grant_type=password
). Then my second function is going to use that to authenticate the request. There is no longer a need to pass any user information, because my api knows who is requesting based on the token that is passed in. The current documentation for OAuth 2.0 is here, and you can find more information about using headers with fetch at Mozilla's fetch documentation.
// request the token
// subscribe to this event and use the returned json to save your token to state or session storage
export function requestAccessToken(data) {
const loginInfo = `${data}&grant_type=password`;
return fetch(`${API_URL}Token`, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: loginInfo,
})
.then((response) => response.json());
// in your case set state to returned token
}
// use said token to authenticate request
export function requestUserInfo(token) {
return fetch(`${API_URL}api/participant/userinfo`, {
method: 'GET',
headers: new Headers({
Authorization: `Bearer ${token}`,
}),
})
.then((response) => response.json());
}
I would also recommend:
Calling fetch from a thunk or a saga, but this is out of scope of the question.
No need to put your token in a hidden field. Which is still accessible btw. Just keep it in state. There are other things you can do to secure it a little, but this too, is out of scope of the question.