JSON Web Token Authorization on the Front End

Emiko N-P.
4 min readJun 8, 2021

--

There are many ways to allow users to log in and out on a web application. In this blog I will discuss how to use JSON web token (JWT) authorization to log-in or sign up a user on the front end using react-redux. This blog will not discuss the back end as that is discussed in depth elsewhere. JWT authorization is a great way to allow user log-in on a web app as it minimizes the need to send user data back and forth from the backend and allows a user to stay logged in through multiple pages. It also requires less data to be stored on the front end, keeping apps streamlined and not bogged down. There are two main steps required to set up JWT authorization on the front end. The first is to set up a component containing the log in or sign up form and associated logic necessary to store the users information as it is imputed. Here is and example of such a component:

class Login extends Component {state = {username: ‘’,password: ‘’,}handleChange = (event) => {this.setState({[event.target.name]: event.target.value})}handleSubmit = (event) => {event.preventDefault()this.props.login(this.state)}render(){return(<div>{this.isLoggedIn()}<h3>Log In</h3><form onSubmit={event => this.handleSubmit(event)}><div><label>Username: </label><input type=”text” name=”username” onChange={event => this.handleChange(event)} value={this.state.username}/></div><br/><div><label>Password: </label><input type=”password” name=”password” onChange={event => this.handleChange(event)} value={this.state.password}/></div><input type=”submit” value=”Log In”/></form></div>)}}const mapDispatchToProps = (dispatch) => {return {login: (user) => dispatch(login(user))}}export default connect(null, mapDispatchToProps)(Login)

As you can see the component renders a form, and stores the form input information in the local state as the user is typing. Then when the form is submitted an action creator method is called that logs in the user. This method is passed into the component as a prop from the mapDispatchToProps method called in the export line using connect. The majority of the work for logging in our user happens in this action creator function. It will look something like this:

export function login(user) {
return (dispatch) => fetch(‘http://localhost:3000/auth', {
method: ‘POST’,headers: {‘Content-Type’: ‘application/json’},body: JSON.stringify({user: user})}).then(resp => resp.json()).then(userData =>{localStorage.setItem(“token”, userData.jwt)dispatch({ type: ‘LOGIN_USER’, user: userData.user })})}

A lot of things are happening here, so let’s break it down line by line. The login function is taking in an argument of our user data, called user in our example. It is then returning a callback function which takes the dispatch function provided by react-redux as an argument. The callback function then calls the fetch method passing it the url and an object often called ‘options’ which contains information about the request being sent, such as the method, headers, and body. In this case the method is ‘POST’ since the user data must be sent to the backend to be saved in the database. The headers used here are standard headers to denote the app type that data is being sent to or from. The body contains the data itself in the form of an object, which is then converted to a JSON string using the JSON stringify method. In this case the object being sent contains the user’s data. Once this Data has been sent, the backend will send back a response containing any necessary user data as well as a newly generated JWT token. In the first ‘then’ function after sending the data using fetch, the response from the back end is converted back from a JSON string into a javascript object that is easier to work with. A second ‘then’ function is then used to deal with logic concerning the returned data. This function does two things. Firstly it stores the JWT token sent from the backend in localStorage on the front end where it can be easily accessed, and secondly it dispatches an action to users controller to save and user data sent back from the back end such as user_id which may be useful later.

Once the authorization token is saved in localStorage it can be accessed where needed without having to access the user’s data and used to easily check if a user is logged in before visiting private pages on the application. Because JWT tokens are automatically encrypted, user’s data is never revealed and does not even have to be saved on the front end all if necessary, making this a secure and quick way to authenticate users. Also because it reduces the need for storing user data JWT authorization helps keep the front end streamlined and not bogged down with excess code. Lastly as has been demonstrated in the example above, JWT authorization can be set up quickly and easily on the front end and because it requires relatively little code, and simply stores the token in localStorage, it is not prone to many bugs. In summary, JWT authorization is a great way to log in users on the front end because it can be set up easily, it is secure, and it reduces the need to store user data on the front end.

--

--

Emiko N-P.
Emiko N-P.

Written by Emiko N-P.

0 Followers

Hello, my name is Emiko. I am an aspiring Software Engineer and student at Flatiron School.

No responses yet