Spring Boot security latest
Basic Spring Boot Security configuration with basic authentication using in-memory user credentials.
Code Example:
First, make sure you have the necessary dependencies in your
`pom.xml` file:
pom.xml
<dependencies>
<!-- Spring
Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring
Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
Then, create a Spring Boot configuration class, for example,
`SecurityConfig.java`:
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public").permitAll() // Publicly accessible endpoint
.anyRequest().authenticated() // All other endpoints require authentication
.and()
.httpBasic(); // Use basic authentication
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user") // Username
.password("{noop}password") // Password (in this example, plain text, use proper encoding in production)
.roles("USER"); // User role
}
}
In this example, we have a publicly accessible endpoint
`/public` and all other endpoints require authentication using basic
authentication. The username is "user" and the password is
"password".
Comments
Post a Comment