Junior — Middle
How is standard authorization implemented within Spring Security?
sobes.tech AI
Answer from AI
In Spring Security, standard authorization is usually implemented through the HttpSecurity configuration in a class annotated with @EnableWebSecurity. The main flow:
- The user enters login and password.
- Spring Security intercepts the request and passes authentication data to the
AuthenticationManager. - The
AuthenticationManagerusesUserDetailsServiceto load the user from the database or another source. - If the data is correct, an
Authenticationobject with the user's rights is created. - After successful authentication, the user gains access to protected resources according to the settings.
Example configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("password"))
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Thus, Spring Security provides a standard authorization process through filters, authentication managers, and access configuration.