Spring security can be implemented in many ways. Common ways are
a. basic authentication
b. form based authentication
c. digest authentication
d. oauth authentication
e. ldap authentication
f. JWT authentication
g. SAML authentication
Basic authentication is used for test application , apis with low level security is needed. Here username and password is encoded in base4 format. No encryption operation.
How to implement a simple basic authentication.
step1: include gradle dependency "'org.springframework.boot:spring-boot-starter-security'"
Create a spring security configuration class:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityWebConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
httpSecurity.authorizeHttpRequests(
auth -> auth.requestMatchers("/hello").authenticated()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return httpSecurity.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Here the flow will work in this way !
Instead inMemoryUserDetailsManager we can use : JdbcUserDetailsManager to get details from a DB.