Junior — Middle
Do you have experience implementing authentication mechanisms using Spring Security?
sobes.tech AI
Answer from AI
Yes, I have experience implementing authentication using Spring Security. The process typically includes the following steps:
- Configuring Spring Security to protect URLs and define access rules.
- Setting up the authentication mechanism — for example, through a database using
UserDetailsService. - Implementing a class that loads the user and their roles.
- Configuring a login form or other mechanisms (JWT, OAuth2).
An example of a basic configuration with a login form:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.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();
}
}
This example shows simple authentication with an in-memory user and a login form. In real projects, a database and more complex mechanisms are usually used.