Spring Security using JWT

This section I am going to cover basic Spring Security using JWT, then we will use this security in the Spring Cloud API Gateway, again I will quickly cover the files regarding Sprint Security as I want to focus on the Spring Cloud part.

We create a Authentication filter by extending the UsernamePasswordAuthenticationFilter class, this class processes an authentication form submission, the form is required to pass two parameters username and password. We override the methods attemptAuthentication and successfulAuthentication both are self explaining, however once the user is successfully (successfulAuthentication method will automatically be called if authenticatyion is accepted) logged in we do create a couple of response headers the JWT token and the User ID.


In the web security setup we use our authentication filter above plus we define some allowed routes, this is pretty standard stuff regarding Spring security, I have a section on Spring security.


Zuul API Gateway Security

Now we have setup basic security we need to implement this into the Zuul API Gateway, some paths will have public access like registration page, login page but other web pages you will need to be authenticated to gain access (JWT token), what we are going to do is implement Spring Security into the Zuul API Gateway application pretty much the same as what we did in the above Users application.


We add some properties that we will use later, the token secret you can configure what you like


The we create authentication filter using the BasicAuthenticationFilter class provided by Spring Security, we override the doFilterInternal, all this does is to get the JWT token from the request and confirm that it is valid, if all is well we return a UsernamePasswordAuthenticationToken.


As we know from the User Authentication that a header is added when the user is logged in and thus we can check this using the above filter, we can see the public web pages for the registeration and login. There is nothing in here that is too complex remember to add the @EnableWebSecurity annotation to enable Spring Security.


You are probably thinking that this was really just basic Spring Security and you would be right, there is nothing special in regards to using Spring Security with Spring Cloud, it all pretty much the same.