React Login Page Github

As a web developer, I have always been intrigued by the power and versatility of React. One of the most common features of any web application is user authentication, and in this article, I will guide you through the process of creating a login page using React and integrating it with GitHub for authentication.

GitHub is a popular platform among developers for version control and collaboration. By leveraging GitHub’s authentication system, we can provide a seamless login experience for our users, allowing them to log in with their GitHub credentials.

Setting up the React Project

To get started, make sure you have Node.js and npm installed on your machine. We will be using Create React App, a tool that sets up a new React project with a basic boilerplate.

npx create-react-app react-login-github

This command will create a new directory called react-login-github and set up the initial React project structure for us.

Once the project is created, navigate into the project directory:

cd react-login-github

Installing Dependencies

Next, we need to install some additional dependencies to help us with the login functionality.

npm install react-router-dom axios

We will be using react-router-dom for handling client-side routing and axios for making HTTP requests to GitHub’s authentication API.

Creating the Login Page

Now, let’s create a new component called Login that will serve as our login page.

import React from 'react';
import { Redirect } from 'react-router-dom';
import axios from 'axios';

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: false
    };
  }

  handleLogin = () => {
    axios.get('https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID')
      .then(response => {
        window.location.href = response.data.login_url;
      })
      .catch(error => {
        console.error('Error occurred during authentication:', error);
      });
  }

  render() {
    if (this.state.redirect) {
      return ;
    }
    return (
      <div>
        <h2>Login with GitHub</h2>
        <button onClick={this.handleLogin}>Login</button>
      </div>
    );
  }
}

This code sets up the basic structure of our login page component. The handleLogin function makes an HTTP request to GitHub’s authorization endpoint and redirects the user to the GitHub login page. Once the user logs in and grants access to our application, they will be redirected to the specified callback URL.

Handling the Callback

After the user logs in with GitHub credentials, GitHub will redirect them to the callback URL specified in the GitHub Developer settings. We need to create another component called Callback to handle this redirect.

import React from 'react';
import axios from 'axios';

class Callback extends React.Component {
  componentDidMount() {
    const code = new URLSearchParams(window.location.search).get('code');
    if (code) {
      axios.post('https://github.com/login/oauth/access_token', {
        client_id: 'YOUR_CLIENT_ID',
        client_secret: 'YOUR_CLIENT_SECRET',
        code
      })
      .then(response => {
        const accessToken = new URLSearchParams(response.data).get('access_token');
        if (accessToken) {
          localStorage.setItem('access_token', accessToken);
          this.props.history.push('/dashboard');
        }
      })
      .catch(error => {
        console.error('Error occurred while exchanging code for access token:', error);
      });
    }
  }

  render() {
    return <div>Redirecting...</div>;
  }
}

This code extracts the authorization code from the URL query parameters, exchanges it for an access token by making a POST request to GitHub’s access token endpoint, and stores the access token in the browser’s local storage. Finally, it redirects the user to the dashboard page where they can access protected resources.

Conclusion

In this article, we explored how to create a login page in React and integrate it with GitHub for authentication. By leveraging GitHub’s authentication system, we can provide a secure and convenient login experience for our users. Remember to replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual GitHub application credentials.

Feel free to customize the login page’s UI and add additional features such as signup, password recovery, or OAuth providers other than GitHub. Happy coding!