Mode:
Duration:
1
Coding works best on desktop or with an external keyboard.
Coding works best on desktop or with an external keyboard.
Demonstrates a simple Spring Boot REST API with basic authentication and role-based access control using Spring Security.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
// SecurityConfig.java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and().httpBasic();
}
}
// TodoController.java
@RestController
@RequestMapping("/todos")
public class TodoController {
@GetMapping
public List<String> getTodos() {
return Arrays.asList("Task 1", "Task 2");
}
}Spring Security is a comprehensive, customizable authentication and access-control framework for Java applications, particularly for securing Spring-based applications.
Origin & Creator
Developed by the Spring community, originally created by Ben Alex in 2003.
Industrial Note
Widely used in enterprise Java applications, microservices, and APIs where robust security is critical.