In part 1 , we explored how to setup our spring security project, how to configure spring security to control how thing are handled. We explored inMemory way authentication, authorization. If you don’t recall this please, please go back to part 1.

In this part, we will build upon the authentication mechanism. InMemory authentication can not be used for any genuine purpose. We need to have our own DB and authenticate the user against password stored in there. We will explore that in this part.

So, From part 1 in our project we have a class extending WebSecurityConfigurerAdapter. We will be overriding configure method in there. Same as we did earlier.

If you are trying to go deep, you will hear about authentication Provider classes and how we could have multiple authentication mechanisms in our app. But we just want to get started so we will keep things simple. We will keep things simple. We will get username and password from the user , we will check that in our DB and revert back to user accordingly.

First, lets setup our DB. I am assuming you have MySQL installed in your system. If not refer to their official website it is pretty straight forward.

Add this dependency in pom.xml. This will get you access to Hibernate.

pom.xml

Hibernate is used to map java objects to DB objects. Formally it is called object relational mapping. As we will see later, you can create a student java class and hibernate will create a table for student class automatically. Hibernate also provides us with simple methods to interact with our DB so we don’t have to write JDBC queries by ourselves.

In application.properties configure to connect to your mysql DB instance.

application.properties

Now, we have DB , a tool to interact with that DB. Now lets use hiberate to create a DB table for our user.

User Model

Observer how we have given different annotations. @Entity means hibernate will map this object, @Table means that we explicitly tell name of the table. @Id is used to designate primary key of this table.

At this stage if you run the app, you will see a table created in DB with three columns. Please head on to mysql console and create a dummy entry , so we can authenticate users against this data. This usually happens during user signup. But we wont do this now. Thats why dummy user.

Now lets target creating our setup so we interact with db using hibernate.

  1. Create Repository interface:
    JpaRepository class gives us a lot of methods based on column which we can directly call and fetch data. For example, we can use findByEmail(String email) without actually writing the query we can fetch user. Cause JpaRepository has already implemented that for us.
    We only need to tell which object we are targetting and what is type of primary key.
    This is all you have to do.
Repository class

2. Create Service interface and implmentation class:
Service interface is used to define methods that we wish to use to interact with our DB. These methods will be implemented by another implementation class. Implementation class will use methods provided by repository.

Service interface
Service Implementation class

At this point we have means to interact with our DB and fetch data from it. Now we will configure our AuthenticationManager so that it will use data from db to authenticate instead of inMemory data. From part 1 you know that we do this by extending WebSecurityConfigurerAdapter and overriding its protected void configure(AuthenticationManagerBuilder auth) method.

configure auth method

Here we are telling auth object to use myUserDetailsService. this means that spring security will user myUserDetailsServie class to fetch user data and perform authentication against that data. Now lets create this service, also remember that spring expects us to return data in specific format, for that spring has UserDetails interface. we will need to create a class implementing this interface and return data with that class.

But first lets configure spring so that it does not use default auth mechanism on our http requests. For that override
protected void configure(HttpSecurity http)
method

Spring Authrization

This means that all request starting with /api/v1 will be allowed to pass without spring security checking for default authorization.

MyUserDetailsService

As you can see we mapped user object to MyUserDetails class and returned that object. Now we need to create MyUserDetails class too.

MyUserDetails

Now we have means to interact with db, we have configured spring security authentication mechanism to use data from db. Now we will create a endpoint where will use all of this setup to authenticate a user.

Auth Controller
Authentication request

In this controller, we have a method mapped at api/auth/authenticate address. This method takes input in the form Authentication Reuqest object. This object maps json sent by user to java object. we take this data,and try to fetch user based on email. Spring security needs userId, password to authenticate user. Then finally we use authenticationManager.authenticate method to authenticate user. This internally uses myUserDetailsService and other things we set up earlier. If everything goes well we return “User Authenticated” and if something goes sideways exception is thrown and that is returned to user. How to handle that exception is different thing. Maybe I will write about that too.

--

--

Rohit Satwadhar

I Write about new things that I learn. That is how I remember stuff. These things are mostly tech related.