Implementing basic authentication

Now that you know the basics related to Basic authentication and how it works, let's review how to implement it in a Spring MVC application.

To begin, we need to include the starter dependency for Spring Security.

It can be included in Gradle as follows:

compile('org.springframework.boot:spring-boot-starter-security')

It can be included in Maven as follows:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

After adding this dependency, Spring Boot will do all of the boring stuff for us, and we won't have to do anything to secure the application. If we don't add any additional configurations, Spring will generate a user for testing, and the password will be printed in the console. This scenario is perfect when we are only in the early stages of development. 

On the other hand, if we require a customized way to allow or restrict access to users, all that we need to do is implement the loadUserByUsername method, which is a part of the UserDetailsService interface.

The implementation is fairly simple; the method retrieves the username provided, and, using that username, you will need to return a UserDetails object with the user information. 

Let's review an example, as follows:

@Service
public class MyCustomUsersDetailService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Customer> customerFound = findByUsername(username);
if (customerFound.isPresent()) {
Customer customer = customerFound.get();
User.UserBuilder builder = User
.withUsername(username)
.password(customer.getPassword())
.roles(ADD_YOUR_ROLES_HERE);
return builder.build();
} else {
throw new UsernameNotFoundException("User not found.");
}
}
}

The findByUsername method is responsible for finding the users that you need in a database or in any other storage. Once you have customized where your users are, you have to work on the authorization for the web pages. This can be done by implementing the WebSecurityConfigurerAdapter interface, as shown in the following code:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.antMatchers("/index").permitAll()
.antMatchers("/guest/**").permitAll()
.antMatchers("/customers/**").hasAuthority("ROLE_CUSTOMER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.successForwardUrl("/home")

.usernameParameter("username").passwordParameter("password")
.permitAll()
.and()
.logout().logoutSuccessUrl("/logout")
.and()
.csrf();
}
}

Let's review the code that has been highlighted in bold:

  • We are configuring a path to grant access to any user, whether or not the request is authenticated
  • A configuration for restricting access to only users with the CUSTOMER role is added for all of the pages under the customers path
  • A login page is configured, as well as the pages to forward successful and failed authentication attempts to
  • The URL /logout is provided, to redirect the user once the logout process has occurred

As you can see, once you have implemented the preceding configuration class, you will have all that you need to secure the web pages in your application.

We mentioned earlier that a good approach to follow is to use HTTPS to encrypt the data that is sent between the browser and the server. To achieve this goal, Spring Boot offers the ability to add the following configuration properties to the application.properties file:

server.port: 8443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: spring
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

Let's review the configurations in this file:

  • As mentioned earlier, HTTPS uses the 8443 port.
  • The next parameter allows for specifying the digital certificate name.
  • The keystore password should also be provided. Note that this value can be provided when executing the application as a parameter. An even better method is to get these values from a configuration server, instead of having them hardcoded in the application.properties file.
  • This parameter is used to specify the store type used when the certificate was generated.
  • The last parameter corresponds to the alias for the digital certificate.

Note that the code should not be modified to enable HTTPS in the application. 

For the sake of testing, a self-signed certificate can be created by using a key tool, which is part of a standard Java installation, as shown in the following screenshot:

Self-signed certificate creation
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.32