Spring Security Basic Authentication
a14-sboot-sc-basic-authentication [TODO]
- Dependency
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Note: If facing any issue while starting the application, try following - Stop the server. - Update maven project (Alt + f5). - Start the server.
- Default user is ‘user’.
- Get auto generated password from log.
- Search in logs for “Using generated security password: “ text to get the auto generated password.
- Configuring user and password in application properties
spring.security.user.name=vivek
spring.security.user.password=welcome
- Customizing default authentication
- Create a Configuration class to override default authetication
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.web.SecurityFilterChain;
@Configuration
public class SpringSecurityConfiguration {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
/*
* All requests must be authorized.
*
* Else return HTTP 403, it doesn't prompt for user creds.
*/
httpSecurity.authorizeHttpRequests(
authorizationManagerRequestMatcherRegistryCustomizer -> authorizationManagerRequestMatcherRegistryCustomizer
.anyRequest().authenticated());
/*
* Prompt for authentication if request is not authorized.
*
* Using default customizer
*/
httpSecurity.httpBasic(Customizer.withDefaults());
/*
* Disabling CSRF as it may cause issue with HTTP methods - POST & PUT.
*
* if enabled, Keep prompting for user credentials for post request.
*/
httpSecurity.csrf(csrf -> csrf.disable());
return httpSecurity.build();
}
}