Spring Security Login Example
By AmarSivas | | Updated : 2021-03-19 | Viewed : 7773 times

In this tutorial, we learn how to use spring security in form login with example.
Table of Contents:
Maven Dependencies
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
Here we are using
Login Form Example
We will look at an annotation-based example here for testing the login form with spring security.
Login Form Example with annotations
We will focus first on the config part then will look at the reaming classes in order to execute the form login example.
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{WebMvcConfig.class, WebSecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Here
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
Here
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
}
Here we configured the WebMvc Configurations for
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("userpass")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("adminpass")).roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").access("hasRole('ROLE_ADMIN')")
.antMatchers("/home").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/accessDenied");
}
}
We will write now the controller class and for accessing different types of URLs. Please look at the below code for the controller part.
@Controller
public class LoginController {
@GetMapping(value = {"/"})
public String welcome(ModelMap model) {
return "welcome";
}
@GetMapping(value = {"/home"})
public String home(ModelMap model) {
return "home";
}
@GetMapping(value = {"/admin"})
public String admin(ModelMap model) {
return "admin";
}
@GetMapping(value = {"/login"})
public String login(ModelMap model, @RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
if (error != null) {
model.addAttribute("error", "Credentials are invalid.");
}
if (logout != null) {
model.addAttribute("message", "Logged out successfully.");
}
return "login";
}
@GetMapping(value = "/accessDenied")
public String accessDenied(ModelMap model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) authentication.getPrincipal();
System.out.println(userDetail);
model.addAttribute("username", userDetail.getUsername());
}
return "accessDenied";
}
}
Here
Please generate a war file and please deploy the war in some web servers like the tomcat server. Please find the below screenshot for testing of the application.





To find more code related changes you can refer to the repository Spring-Security-Form-login-With-InMem-Example-App