Authentication and Authorization in User Service

Code Dexterous
2 min readJul 12, 2020

Let’s add authentication and authorization in our User Service. I am not going to explain the Spring Security in details you can follow many documentation/blogs to understand it’s core.

But yes we are going to implement it with JWT and see it in action.

Let add some more dependencies to our User Service build.gradle file for the version you can refer maven.

// XML and JSON compatibility

  • compile ‘com.fasterxml.jackson.core:jackson-core’
  • compile ‘com.fasterxml.jackson.core:jackson-databind’
  • compile ‘com.fasterxml.jackson.dataformat:jackson-dataformat-xml’
  • compile ‘org.modelmapper:modelmapper:2.3.8’

// Spring Security

  • compile ‘org.springframework.boot:spring-boot-starter-security’
  • compile ‘io.jsonwebtoken:jjwt:0.9.1’

Create a Model/Domain to hold User’s properties.

Now create UserRepository to perform action from Database.

Create UserService and it’s implementation class UserServiceImpl.

Now create a RestController to server responses for the requests

Let’s Create two Command Object classes just to add a layer between request Model to Database Model.

Now add Spring Security Configuration.

In WebSecurity we have used gatewayIp which only allow all request from API Gateway except that our User-Service will be not be accessible. We have add the configuration of gateway.ip in Config Service/user-service.properties.

config-service/user-service.properties

And this IP we got from our Eureka Service. So in future if our IP changes in Eureka then we have to do same changes in Config Service too. For development it may regular changes but on Server it might changes.

Create Filter

This is the required files to add Spring Security.

This is it for User Service now we have to add Security Check in our Gateway Service too so that we can expose some public URL like login, register etc.

--

--

Code Dexterous

I am full stack developer. Works on different technology and lean to learn more.