Spring Security Simple REST API - Spring-security Typing CST Test
Loading…
Spring Security Simple REST API — Spring-security Code
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 Language Guide
Spring Security is a comprehensive, customizable authentication and access-control framework for Java applications, particularly for securing Spring-based applications.
Primary Use Cases
- ▸Authentication and user login
- ▸Authorization and role-based access control
- ▸API security with JWT or OAuth2
- ▸Protecting web applications from CSRF, XSS, and other attacks
- ▸Integration with identity providers like LDAP or OAuth2
Notable Features
- ▸Comprehensive authentication and authorization support
- ▸Filter chain architecture for request processing
- ▸Integration with Spring Boot auto-configuration
- ▸Supports OAuth2, JWT, LDAP, SAML, and more
- ▸CSRF, CORS, and session management built-in
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.