Creating a JWT secured react app and Kotlin server (part 2)

Time for some code at last! If you haven’t read my last post, please head on back here.

I’m starting things off with a very simple controller that returns HTML responses.

package com.chrisyoung.auth

import org.springframework.http.MediaType
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.set
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestParam


@Controller
class LoginController {
    @GetMapping("/login")
    fun loginForm(model: Model): String {
        model["title"] = "Login"
        return "login"
    }
    @PostMapping("/login", consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE])
    fun login(
            model: Model,
            @RequestParam(name = "username") username: String,
            @RequestParam(name = "password") password: String
    ): String {
        model["title"] = "Login"
        model["username"] = username;
        model["password"] = password;
        return "loggedin"
    }
}

Annotations are extremely powerful in Spring Boot. The @Controller, @GetMapping and @PostMapping annotations are taking care of the routing and request and response handling for us. I admit that they do seem a little bit too magical, but I’ve always enjoyed a bit of magic over a bunch of boilerplate.

in the functions we can see the beautiful strictly typed parameters, including the special parameter “Model” used by the mustache templates below

The application is very simple at this point. The /login route displays a html form with fields for username and password, and when that is submitted, those values are pulled out of the form-encoded request into String-type function parameters which are just displayed on the next page. I’m not actually implementing any login logic here, just request logic. I haven’t started with REST endpoints yet, because I need a couple of actual HTML pages in my auth service for the initial login and the authorisation page.

I also need a couple of templates named to match the return values of the GET and POST mapping above

{{>_header}}
    <h1>Login</h1>
    <form method="POST" action="/login">
        username:
        <input type="text" name="username"/>
        <br/>
        password:
        <input type="password" name="password"/>
        <br/>
        <input type="submit" title="login"/>
    </form>
{{>_footer}}

/resources/templates/login.mustache

{{>_header}}
<h1>Logged in</h1>
<p>username {{username}}</p>
<p>password {{password}}</p>
{{>_footer}}

/resources/templates/loggedin.mustache

Next I’ll add a bit of logic to make it a bit more functional

Creating a JWT secured react app and Kotlin server (part 1)

‘ve been a PHP software developer for as long as I’ve been developing software. My first taste of programming in university was in PHP, and whilst I’ve developed in Java and Javascript at different points in my career – I do a fair bit of javascript at the moment actually – I’ve always come back to PHP. So since change is like a holiday, I wanted to take some time to learn some new things that are rising in popularity. Furthermore as I journey into the micro-services space, I’m dealing daily with Javascript Web Tokens (or JWTs) to authenticate and authorise requests in my PHP services, and I’m also dealing with their creation.

For this project I wanted to capture the handing of authentication and authorisation by building an auth server, a resource server, and a frontend. The SPA frontend will have a landing page, a login function which will redirect to the authorise page on the auth server, which in turn will redirect back to the frontend with a one time code. The frontend will then fetch an auth token (JWT) using the one time code and client credentials. Finally the frontend will request resources from the resource server using the auth token.

For my two backends I wanted to try something completely new. I hadn’t written anything in Java for a very long time, and I’ve heard very good things about Kotlin since it’s introduction. Kotlin is a superset of Java, adding features many consider to be sorely needed such as strict typing and null handling. I’ve seen it used in Android and desktop applications, but also in APIs. I’ll write both my backend APIs (the auth server and the resource server) in Kotlin with the Spring framework, which appears to be the most popular.

Kotlin Programming Language

Whilst it would be possible to write my frontend in Kotlin also, I wanted to explore a more popular web application framework, React. I’ve used react, and React Native a fair bit recently, however developers with a front-end focus have spent more time than I on those projects. I also used Redux heavily last time, and I’d rather try to avoid that by using React hooks instead. I’ll write my react app in Typescript, since I highlighted that strict typing was one of the reasons for choosing Kotlin above.

Getting started

Source control

Where am I going to put this code that I’m writing? In a git repo of course! And I prefer github.com for its ease of use and many features. I toyed with the idea of keeping all three parts in the one repository, given that they’re part of one (fairly limited) project, but the way that tools like travis and coveralls work, each thing really needs it’s own repository. Good thing they’re unlimited!

Initialisation

As a PHP developer, I’m accustomed to using composer to spin up a project, and in a similar way using npm or yarn to initiate a javascript project. This project starts a little differently. Since I’m using Spring Framework, the recommended way to proceed is to download a zip file with your starter project inside. Alright, let’s do that!. I went to https://start.spring.io/ to build a starter package. (First I did some language tutorials at https://kotlinlang.org/, but I’ll let you imagine that part).

Spring boot initialiser

Spring boot initialiser

 

I stuck the unzipped files in a folder called auth inside my project folder.

Java Versions

My mac comes with Java 8 / 1.8. That’s not good enough for this project, so I needed to get homebrew to download and install Java 11.

brew tap homebrew/cask-versions

brew cask install java11

Starting the react project was a bit more of a familiar project. I was accustomed to having the latest react-native-cli installed globally with NPM, but now you just run

npx create-react-app frontend

It’s truely a beautiful process, though admittedly the product you get in the end is much lest customised.

Create React App

What IDE am I going to use?

A few years ago I got really attached to Jetbrains PHPstorm for php development. The full featured IDE was everything i needed for debugging testing and writing quality code. Of late working on both PHP and Javascript projects I had taken to using vscode for everything. The PHP plugins provided me most of the IDE-type functionality I desired, and the javascript functionality was out-of-this-world. Since I’ll use vscode for the frontend, I assumed that I could continue to use vscode for Kotlin development too, and certainly there was a fair bit of Java and Kotlin support in the community and in the plugin repo, but ultimately I found it unworkable and decided to switch back to Jetbrains IntelliJ IDEA which, thankfully, is free (that is, the community edition is all I need for this project).

I’m very impressed with the experience of IntelliJ IDEA. Especially given how foreign the Java ecosystem is to me at this point. Managing build, dependencies and run is a lifesaver.

IntelliJ IDEA

IntelliJ IDEA

Of course things weren’t perfect at first – until this popup appeared to save the day

Non-managed pom.xml file found

Adding it meant that the IDE installed all the dependencies for me, and could auto-import.

Screen Shot 2020-08-30 at 2.17.32 pm

Next, I’ll write some actual code. Go to part 2

Android

Screenshot 2017-04-24_20-47-12

I decided I’ve been putting off learning Android development for far too long. I’ve completely avoided the idea like it’s some fad that’s gonna pass when, you know, everyone ditches smartphones. My lack of motivation to try the platform was my absolute lack of ideas as to what to develop. I’m just not one of those people who come up with cool ideas for apps.

Recently though, my personal outrage at a hideous app boiled over and a google search for a public API for the service actually yielded some result. The API doesn’t do exactly what an API should, which kind of explains why the app is so gosh darn awful, but it does work.

The first thing that I discovered when I downloaded and installed Android Developer studio on my mac, was how amazingly similar the interface is to PhpStorm by JetBrains, which I use for developing an app in Symfony2 at work. Obviously they’re based on the same IDE framework, but it really was a shock – they’re almost identical.

Screenshot 2017-04-24_20-46-32

The next delightful surprise – remember I’d stuck my head completely in the sand – was that apps are written in Java. Java! I haven’t touched Java since my university days. I’d have to say that it doesn’t seem like a whole lot has changed with Java, but so much with PHP has changed that the two have come a lot closer together. Honestly, it doesn’t feel that different to programming in PHP except, well, it’s not PHP.

On my workplace’s website I’m listed as a “full stack developer” which means I can’t decide what part of the stack to specialise in so I just try to be reasonable at everything. I’ve taken to programming frontends in angular, which has given me a much more up to date understanding of Javascript for frontend development – but this is Java, and it really bears no resemblance to me. Java feels more like PHP, but I’m writing *frontend* code in in, which just feels all wrong. Nevertheless the IDE, the tutorials and good old Stack Overflow practically guided me through the experience in a couple of days.

Screenshot 2017-04-24_20-46-57

The next surprise – again, I had no idea what was in store – was that I didn’t have to code in that gosh darn Hyper Text Markup Language that I’ve grown to hate. Instead, there’s a cool visual editor that helps you lock everything in place – and it’s not wishy washy about how it works. You can easily view the XML that it outputs, and adjust it yourself if you like that kind of thing. One thing I can’t do, is make anything look any good – so if there’s a drag and drop editor that let’s me assign actions to buttons, then awesome.

As I said, I found the public facing API documentation on the website for the original app. The system honestly scares me. Authentication for the API is either via an API key which you can only acquire by contacting customer support – and only if you’re the owner of the organisation, not an end user. The alternative is to send your username and password in the query string of every single request – which means that the app has to store your password. When you call the Authenticate endpoint – the system does give you a token, but there’s absolutely nothing in the API documentation about how to use that token to authenticate. What shocked me, is what happens when you stick in invalid credentials. The request returns successfully with a 2xx status code, and a user object with null fields. You have to check if one of the fields is null (and it could be null for other reasons) to detect that authentication has actually failed. Crazy.

So that’s what happens if you send the right fields with the wrong values. Guess what happens when you send the wrong fields? The API documentation says that the default format for responses is JSON, and that you can request XML if you so desire (because you’re insane) and for the most part this is true – but if you happen to not send a mandatory field, or some invalid value that causes an internal server error – you get a HTML Page with the error on it. Just let that sit for a minute. If I want to tell the user why the request failed (admittedly because I malformed the request) then I have to somehow interpret their HTML 500 error page and jam it onto the little phone screen. All I’ve done so far is just dump the raw html onto the screen, because I’m just not touching that.

I recently had to design and implement an API for a SAAS and making sure the app returns the correct status codes and errors in the correct format was possibly more important than getting the API to actually do anything. I honestly can’t see how they missed this.

In any case I had a little bit of fun, and that’s what I set out to do. I might have a go at getting the app good enough to put on the app store – and there are quite a few more features that I’d like to add to it, but I’m pleased that in a couple of days I made an app that functions better than the one my company pays a monthly fee to have access to – even though a couple of days ago I didn’t have a clue how to make an app.

You can check it out here.
https://github.com/darkbluesun/nimbleschedule-android-timeclock

Photographing a walk in the woods

I was delighted yesterday to go for a walk in one of the most beautiful places I’ve ever been. Aira Force is a waterfall in the Lake District in the North of England. I must say it was breathtaking. A great way to spend a Saturday afternoon.

VLUU P1200  / Samsung P1200

I would have taken my Sony DHC-HX1 semi pro camera on such an excursion but – as so often happens – I pulled it out of the case to find it had no charge left. I guess you just need to leave the battery on trickle-charge and take it out when you want to use it.

Anyway I ended up taking a lot of photos with my Galaxy S3. I’ve never been a fan of smartphone cameras for hobby photography, but to be honest taking photos with this phone was really fun. The colour reproduction and lighting were fantastic, and the camera is so clever that you barely have to touch the controls. Yes, I missed having 20x optical zoom (the S3 has nothing) but there was plenty to take in without zoom.

 

20130209_150522

20130209_152552

One design flaw I’ve found about Android phones is that whilst there is now a shortcut to the camera on the lock screen, launching it still requires you to unlock the phone to use it – I believe the iPhone 5 allows you to use the camera without unlocking the phone – this means my wife is already taking photos of that amazing thing while I’m still fiddling with my phone.

But, why complain? The S3 did a fantastic job and meant I didn’t have to haul around my big camera on such a lovely expedition.

20130209_151153

Start here

I’ve decided to re-start my own personal blog page so that I can write about cool things that I discover, hacks that I figure out and problems that I solve. Also I’ll probably complain about lots of little amusing things. This blog will be less ministry-update-dinner and more random-thoughts-and-ideas. My wife and I will still maintain our ministry blog at http://www.youngfam.net/ weekly and we encourage you to read it to stay up do date with what God is doing in our lives here in Carlisle.

Counting the days

June 9th 1:30pm BST / 10:30pm EST

It’s only 9 days now until Ruth and I tie the knot here in Berkhamsted, England. We’re both super excited and thankful we can count the days on our fingers now. Everything seems to be coming together quite well for us as far as wedding planning and preparing for the future.

We will be broadcasting the wedding live over the internet from our church streaming channel:
http://www.ustream.tv/channel/northchurch-baptist-broadcast
Note that this is not going to be a television worthy production, but you will be able to see and hear all the essentials if you want to stay up till 10:30pm EST. You can see another wedding has been recorded as ours will be to get an idea of the quality of coverage – though our ceremony will be quite different!

Ruth and I have been going through The Marriage Preparation Course by the makers of Alpha with our pastor and would happily recommend the course to new couples. http://relationshipcentral.org/marriage-preparation-course

Our first couple of months in Carlisle seem to be shaping up as well. We have both been selected to be involved in TeenStreet - a huge Christian event challenging teenagers to live for Christ – in July and we have both been recruited for the Go conference – where new missionaries come to be equipped before going out into the world. I will be doing audio visual and Ruth will be looking after kids and consulting with families entering the mission field.

We can hardly wait for our new life to begin. We are seeing God’s provision for us every day in having enough money to buy food and bus tickets, to the big things like wedding rings and houses. Ruth’s monthly support income is almost at 100% – we are just seeking God for another £100 – £200. She is also looking for part time teaching work to give us enough to live on. If she is unable to find enough work, my monthly support will need to increase by up to $600 per month to give us spending money for things like groceries and public transport. Please continue to pray that the rest of the figures add up and we can begin serving God without being a burden to the organisation we go with.

Ground work

Having spent another week in Carlisle – this time on my own – what do I have to show for it? I have been working on a project which will allow people to easily give monthly to the ship Logos Hope. There are many people out there – some Christians and some not – who would like to make regular contributions, and the technology needs to catch up. Over the week I have made enough progress for other people to take on the job of testing and implementing it. It feels good to have achieved something in the time that I’ve spent there. Others really appreciated the work I did.

I also had the chance to visit another church in Carlisle, which I really enjoyed. Carlisle Christian Fellowship is a small church that grew up out of house churches. They are fairly modern and charismatic and I’ve seen at least one thing in the news sheet about a kindness evangelism outreach this month. I had the pleasure of going to a men’s dinner at the church and connecting with some of the blokes there. I’m still not sure if this will be where Ruth and I settle, but it’s nice to experience fellowship with believers in a totally different place.

Ruth and I have also been looking at houses, and we think we may have found one close to the city center with all the furniture included. It’s a two bedroom terraced house – very typical English home. Whatever we decide on, OM will take care of all the rental agreements, which is very helpful for us.

 

Time to go

Well the day is finally here. Tonight at 6:45pm I’m hopping on a plane that takes me to the other side of the world. I’m heading to the UK where I will first meet up with my fiancee Ruth and stay with friends of hers while I get over jetlag. Then we’re off to Carlisle to connect with the missions organization we feel led to be a part of. We will have lots of meetings and get to see the house where we will live when we get married (I’ll be staying somewhere else for now). Then we are headed back down to Berkhamsted where Ruth is living to help raise awareness and funding there – whilst making wedding plans. Likely we will make more visits up to Carlisle before we marry but plans are just forming now. In June we will get married, honeymoon and return to Australia for a second ceremony before returning to the UK to start with OM officially on July 2nd.

What are we actually doing? If you’re not familiar with our plans to join OMNIvision and OM Education then please read this post about OMNivision:
Young family: OMNIvision
Ruth will be volunteering as the educational adviser for OM international including the ship ministry – supporting and resourcing the ship’s school, advising parents entering the mission field and recruiting teachers. She will also probably teach part time in some way to keep up with the education system in the UK.

Over the last week I’ve had lots of good times with friends from all different walks of life and with my family. I’ve had to say goodbye to the people I know and love, but I know it is worthwhile to follow the path that God has set before me and before Ruth also. We are both stepping out in faith that God will provide for our need while we respond to his call. I have had my share of doubts over the last few months regarding finances – but God has never let me down yet! Through a number of recent contributions, I now have nearly 70% of my half of our expenses pledged by generous people, and if Ruth is able to find part time work as she plans (definitely pray for this!) then I have almost exactly half right now. See how God is faithful? Yet He rarely provides it well in advance – He provides it at just the right time. The very good news is that for the short term our organisation will help us to make up any shortfall, but we still need our income to increase. Ruth is just in the beginnings of her support raising and we would appreciate your prayers for us in that.

We are delighted to go into this field of ministry with the prayers and best wishes of so many people who I consider friends or family. Regardless of if you give or if you even share our beliefs, we are glad to share with you what God is doing in us and through us as we follow this path.

Love & Blessings,
Ruth & Chris

Engagement

It’s official, Ruth Spencer and I (Chris Young) are engaged! Now we can say that not only will we spend the rest of our lives together, but also that we will respond together to God’s call to mission. We were both already headed the same direction in life – now we can walk side by side.

Ruth and I met each other on board the M.V. Logos Hope – a ship that sails through God’s waiting world bringing knowledge through the good literature in it’s on-board bookstore, help for those in need, and the hope of the gospel of Jesus Christ to people in every port city it visits. I was the Audio/Visual team leader, Ruth was the head teacher. We successfully ignored each other for 18 months of our time, our hearts set on serving God. Ruth has a passion for seeing kids of missionaries develop into healthy adults, and I have the passion to see technology and multimedia draw people to the heart of God.

In the beginning of 2011 we were in the same group of friends, and when by circumstance all of our other friends left for two weeks, we became good friends. God fostered a healthy friendship between us in a group of four, and at the right time both our feelings developed and I invited her to start a relationship. Of course in doing so I’m sure I barely managed to string a sentence together – I was so nervous, and Ruth hadn’t really seen our friendship in that light before – but after praying about it we decided to ‘go for it’.

We spent three months together as a couple on the ship, then a month apart, then a week together, then two-and-a-half months apart, then two months together in Australia. We’ve had the fun days, the exciting days, the romantic days, the boring days, the stressful days, the hard days and the sad days – and whilst we are neither of us perfect, we believe God put us together for good reasons, some of which we have discovered, and some we have yet to see.

Last Thursday we went to see Somersby falls – because of all the rain recently the waterfalls were in full swing. And when we had gazed a while on the falls and when we were left alone I asked her to marry me. Of course she said yes. I gave her a nice ring which I almost dropped in a puddle!

Ruth will be volunteering as the educational adviser for OM international including the ship ministry – supporting and resourcing the ship’s school, advising parents entering the mission field and recruiting teachers. She will also probably teach part time in some way to keep up with the education system in the UK. I will be joining the OMNIvision team – creating prayer resources featuring the unreached peoples of the world and providing the Audio Visual coverage of evangelistic and missional events across Europe.

It’s a little strange for us to consider starting a life together when neither of us have full time employment. It would be much easier for us to both go and get jobs, but we believe that God is calling us to be a part of the worldwide mission movement, enabling others to go and tell the good news about Jesus. Sometimes I am sad that I can’t accept engagement presents or take any of my furniture or appliances with me into our new life, but we see following God’s plan and purpose for our lives as more important, and ultimately more rewarding. Of course if you would like to bless us in our marriage and our mission, monthly sponsorships of as little as $5 are what we need most. Please contact me if you feel you would like to partner with us.

Chris and Ruth

OMNIvision

In April this year I am planning to move to the UK. “but why?” you might ask. The answer has to do with where God is leading me next in his plan for me. I know I wouldn’t have experienced the wonders that I did whilst traveling on the M.V. Logos Hope if I’d ignored God’s call – and now here I am again ready to head off.

You see, since I became a Christian (in my mid teens) I have had this focus. I want to use technology to help people draw closer to God. I want to get the technology out of the way of what He is saying to the Christian, and to the everyman. Have you ever been in a church service where the words never seem to come up on time? Or the microphone is never switched on at the start? Well I have, and I’ve made those mistakes too. Ultimately while we need the microphone and the screen in a large gathering, we don’t want to think about them instead of God and his purposes.

I’ve been looking for and praying for a way that I can use this passion in a more evangelistic sense. Whilst I love ministering to the saints – I feel a pull to be involved in some way in ministries that reach out to the unsaved. I am drawn to the big evangelistic events and the christian conferences that spur young Christians on to great things for God. I want to use what God has given me to enable others to reach the masses with the good news. I want to be a part of mobilising Christians to share their faith with their fellow students, their co workers, their families and even with people in other countries.

OMNIvision is a UK based division of Operation Mobilisation – an international mission orginisation with over 6100 full time missionaries in more than 110 countries. Whilst OMNIvision’s role in the wider organisation is small and unglorified, it is vital all the same, aiming  to fulfil psalm 96:3 – “Declare his glory among the nations, his marvellous deeds among all peoples”. It’s headquarters and studio is in Carlisle – on the Border of England and Scotland. Whilst they are involved in may of these large events across Europe, their core vision is achieved by creating 5-10 minute documentary videos.

Imagine if Christians around the world were aware of what God is doing in some of the most unreached places in the world. Imagine if they knew what to pray for, how to give and where they could go. OMNIvision’s professional camera crew travel to the places where the gospel is starting to take root and capture on video what is happening. Back at the studio, editors put together a short programme that transports the regular Christian from a cell group setting to the mission field – Seeing the faces, hearing the voices of the people who need Christ’s love. They are given key points to pray for. I will be involved in maintaining the OMNItube website where the videos are available to watch and download. Helping them to reach more people. OMNIvision are keen to have a developer like myself on the team.

I will be going there mid April 2012 and initially staying for 2 years, though I could possibly stay longer. I will be a volunteer, so I will need to provide $1800 per month to cover my accommodation, food, transport, insurance, superannuation and travel home. Of course without an income I need to depend on God to provide the funds for this call, and He does that through faithful sponsors who donate monthly anything from $12 to $100 and higher. If you would like to sponsor me for this amazing call, please contact me.