denden
denden

Reputation: 1319

Requesting OAuth2 tokens from a node server using react-native

As part of learning about OAuth2 and persistent login with react-native, I'm using the OAuth2 server example found here to figure out how to send info and request validation from the server.

At the moment, I'd just like to be able to log the access_token to the console as I think I can then build on that knowledge on my own. I just can't seem to find an ideal example of how this can fetch correctly.

I think the part I'm not getting is the sending of header and body information.

export default class App extends Component {
  goGetToken() {
    return fetch('http://localhost:3000/oauth/token/?grant_type=password&username=pedroetb&password=password', {
      method: 'POST',
      headers: {
        'Authorization': 'Basic YXBwbGljYXRpb246c2VjcmV0',
        'Content-Type': 'application/application/x-www-form-urlencoded',
      },
    }).then(response => response.json())
      .then(responseJson => {
        console.log(responseJson.access_token);
        return responseJson.access_token;
      })
      .catch(error => {
        console.error(error);
      });
  }

  componentDidMount() {
    this.goGetToken();
  }
  render() {
    return(
      <View></View>
    )
  }
}

The included readme suggests the following, but I can't seem to find an example of sending headers/fetch correctly?

### Obtaining a token

To obtain a token you should POST to `http://localhost:3000/oauth/token`.

#### With *password* grant

You need to include the client credentials in request headers and the user credentials and grant type in request body:

* **Headers**
    * **Authorization**: `"Basic " + clientId:secret base64'd`
        * (for example, to use `application:secret`, you should send `Basic YXBwbGljYXRpb246c2VjcmV0`)

    * **Content-Type**: `application/x-www-form-urlencoded`
* **Body**
    * `grant_type=password&username=pedroetb&password=password`
        * (contains 3 parameters: `grant_type`, `username` and `password`)

Upvotes: 0

Views: 1865

Answers (1)

chiquyet
chiquyet

Reputation: 537

I'm currently work with OAuth 2 in React native and I found a really good blog talking about it. It's also have a github repo for reference. Hope it can help you.

https://medium.com/@alexmngn/the-essential-boilerplate-to-authenticate-users-on-your-react-native-app-f7a8e0e04a42

Upvotes: 1

Related Questions