React JS - How to authenticate credentials via a fetch statement

后端 未结 1 1299
北恋
北恋 2021-02-04 17:36

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

相关标签:
1条回答
  • 2021-02-04 18:11

    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:

    1. Calling fetch from a thunk or a saga, but this is out of scope of the question.

    2. 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.

    0 讨论(0)
提交回复
热议问题