Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
Creating a Spring Security project using Java configuration involves several steps. Below is a basic example of setting up Spring Security with form-based authentication using Java-based configuration:
Add Dependencies:
First, make sure you have the necessary Spring Security and Spring Boot dependencies in your pom.xml
:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Security Configuration:
Define a configuration class that extends WebSecurityConfigurerAdapter
:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessURL("/home") .permitAll() .and() .logout() .logoutSuccessURL("/login?logout") .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
Controller:
Create a controller to handle different endpoints:
@Controller public class AppController { @GetMapping("/public/hello") @ResponseBody public String publicHello() { return "Hello, Public!"; } @GetMapping("/secure/hello") @ResponseBody public String secureHello() { return "Hello, Secure!"; } @GetMapping("/login") public String login() { return "login"; // Assumes you have a 'login.html' in your template folder. } @GetMapping("/home") public String home() { return "home"; // Assumes you have a 'home.html' in your template folder. } }
Templates:
Create a login.html
template (and any other templates you may need):
<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <form action="/login" method="post"> <div> <label>Username:</label> <input type="text" name="username"/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div> <input type="submit" value="Login"/> </div> </form> </body> </html>
Application Class:
Create the main application class:
@SpringBootApplication public class SpringSecurityExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringSecurityExampleApplication.class, args); } }
Running:
Run the SpringSecurityExampleApplication
class. When you try to access any endpoint (other than /public/**
), you'll be redirected to the /login
page. Once you provide the credentials (user
/password
), you will be directed to /home
.
This example provides a basic setup for Spring Security using Java configuration. Depending on your requirements, you can expand on this by connecting to a database for user data, using custom authentication providers, adding method-level security, and much more.
Securing Spring application with Java-based Spring Security:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // Configure authentication and authorization here }
Building a secure web application with Spring Security Java config:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin().and() .logout().logoutSuccessUrl("/login"); }
Configuring authentication and authorization in Spring Security using Java:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); }
Securing RESTful APIs with Spring Security Java config:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .httpBasic(); }
Spring Security Java configuration custom login form:
@Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginPage("/custom-login") .permitAll(); }
Java-based Spring Security for Spring Boot projects:
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Role-based access control in Spring Security Java configuration:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .and() .formLogin(); }
Customizing password encoding with Spring Security Java config:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .passwordEncoder(new BCryptPasswordEncoder()) .withUser("user").password("$2a$10$...").roles("USER"); }
Configuring session management with Spring Security Java config:
@Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.ALWAYS); }
@EnableGlobalMethodSecurity(securedEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { // Configure method-level security settings }
@Override protected void configure(HttpSecurity http) throws Exception { http .rememberMe() .key("uniqueAndSecret"); }
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .ldapAuthentication() .userDnPatterns("uid={0},ou=people") .groupSearchBase("ou=groups"); }
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .and() .formLogin(); }