Creating a JWT secured React app and Kotlin server Part 4: React

In the last blog, I finished off my authentication server in Kotlin. Now it’s time to write a web application to connect to the authentication server to get a token, ultimately to use to consume further content. For this project I’ve chosen to go with React. Introduced by Facebook in 2013, it has steadily gained popularity over the years to the point where it feels like everyone is in React. I’ve had some history with React myself at work, as well as React Native, the bridge to running React on mobile devices natively.

React has a pretty neat way to start a new application called “auth-demo-frontend” over at https://reactjs.org/tutorial/tutorial.html

npx create-react-app auth-demo-frontend

This is going to set you up with all the packages you need and a little sample application that you can modify.

Next we want to install react-router so we can navigate around our application with URLs and bootstrap so we can have a consistent look/feel

yarn add react-router bootstrap

Then we can add a navigation bar to our app.js

And create some components:

import React from 'react';
import useGlobal from "../store";
import queryString from 'query-string';
import { oauthConfig } from '../Config/constants';

function Login(props) {
    const [globalState, globalActions] = useGlobal();
    const params = queryString.parse(props.location.search);
    const { code } = params;
    const { security: { user, state, status, error }} = globalState;
    const { authUrl, clientId } = oauthConfig;
    switch (status) {
        case "authFailure": 
            if (!code) {
              window.location.href = "/login";
            }
            return (
Fail: { error }

) case “authenticated”: return (

Auth’d as: {user.username}

) default: //nothing } if (code) { globalActions.getToken(code, state); return (

Authenticating…

) } else { window.location.href=`${authUrl}?state=${state}&clientId=${clientId}`; return (

Redirecting to your authentication provider

) } } export default Login;

Leave a Reply