Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Security: Form-Based Authentication

DZone's Guide to

Spring Security: Form-Based Authentication

We go over the details of form-based authentication in the Java Spring Security framework, to help you ensure the security of your application.

· Security Zone ·
Free Resource

Protect your applications against today's increasingly sophisticated threat landscape.

In this post, we will use Spring security to handle form-based authentication. You can also read my previous posts on Basic Authentication and Digest Authentication.

Technologies/Frameworks Used

Spring Boot, Spring Security, Thymeleaf, AngularJS, Bootstrap

Adding Dependencies in pom.xml

In the example below, we will use Spring Boot, Spring Security, Undertow, and thymeleaf and will add their starters as shown.

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
      <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>2.1.2.RELEASE</version>
  </dependency>
</dependencies>

Spring Security Configurations

We will extend the WebSecurityConfigurerAdapter class, which is a convenient base class to create WebSecurityConfigurer.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
            .antMatchers("/static/**", "/", "/index", "/bower_components/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .permitAll();
  }

  @Bean
  public UserDetailsService userDetailsService() {
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    manager.createUser(User.withUsername("gaurav").password("s3cr3t").roles("USER").build());
    return manager;
  }

  @Bean
  SpringSecurityDialect securityDialect() {
    return new SpringSecurityDialect();
  }
}


@EnableWebSecurity annotation enables Spring Security. We have overridden the configure method and configured the security. In the above code, we have disabled the csrf request support (it is enabled by default). We are authorizing all the requests to /index, /,/static folder and sub-folders, bower_components folder and its subfolder that is accessible without authentication, though all others should be authenticated. We are referring /login as our login page for authentication.

In the above code snippet, we are also registering the UserDetailsService. When we enable web-security in Spring, it expects a bean of type UserDetailsService which is used to get UserDetails. For the purpose of this example, I am using InMemoryUserDetailsManager, provided by the Spring.

MVC Configuration

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/viewUsers").setViewName("viewUsers");
    registry.addViewController("/index").setViewName("index");
    registry.addViewController("/").setViewName("index");
    registry.addViewController("/login").setViewName("login");
  }
}


In the above configuration, we are registering several ViewControllers and setting their names. This is all configuration that we need to do to enable Spring Security. You can find the full working project, including the HTML files, on Github.

Rapidly detect security vulnerabilities in your web, mobile and desktop applications with IBM Application Security on Cloud. Register Now

Topics:
security ,spring secruity ,authenciation

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}