Monday, November 5, 2018

Spring Boot and Spring Security

Let's now continue our Spring Boot journey by adding Spring Security. First we need to modify our pom.xml as shown below.


If we run our project this time, instead of displaying our page, Spring will redirect us to login page. At this point of time we haven't even created the login page.


So now we will create a login page as shown below. Here we use primefaces as our front end. We will learn it later. For now what we need to do is to make sure that the username is named "username" and password is named "password" as it is required by Spring Security.


Next we have to create a configuration class that extends WebSecurityConfigurerAdapter. We also have to annotate it with @Configuration and @EnableWebSecurity. These two annotations are used together to configure Spring Security. We then need to override the configure() method. Inside configure() method, we define login and logout url, resources that are permitted to access without any authorization, etc.


So now how do we compare username and password with the ones in database? That is the job of a password encoder. As shown below, there are two methods we have to implement, encode() and matches(). Method encode() is used to encode raw password while matches() is used to compare raw password and encoded one. Raw password is supplied by user input while encoded password is the one we fetched from database. Note that we use MD5 as our encoding algorithm.


Next question is how do we get username and password from database? And who gives that password to our password encoder above? That is the job of user detail service. This class implements UserDetailsService and annotated with @Service to make it a Spring service. Here we have to implement method loadUserByUsername(). This method makes a query to database to get a user if any, using supplied username. It then gets the user's roles which we can use later when we deal with authority in an html page. It then returns a Spring Security User object which has username, password, and roles. Next, Spring calls our password encoder class to compare the password.


Now we need to put them all together as shown below. In our WebSecurityConfigurerAdapter class, we have to create a bean of password encoder and object of type user detail. Method configureGlobal() bind them all together. So our WebSecurityConfigurerAdapter looks like this:


Now run the project and our login page will be displayed.


If authentication failed, an error message is displayed.


If succeed, an error is also displayed. This is because we haven't defined our default page.


To define a default page, we have to create a configuration class that extends WebMvcConfigurer. Method addViewControllers() needs to be implemented. In our case we make index.xhtml as the default page.


Now if we start the project again and successfully logging in, the index.xhtml will be displayed.


0 comments:

 

©2009 Stay the Same | by TNB