I would like to use two different authentication methods at the same time. I have researched on the internet, but I couldn't find a solution that suits my need.
My requirements:
/auth/**
and/public/**
=> Permit all for any authentication method, everybody can access these endpoints./api/**
=> All methods under this endpoint will be secured by JWT./orders/**
=> These endpoints will be secured by basic authentication.
My config file:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Configuration
@Order(2)
@AllArgsConstructor
public static class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final JwtRequestFilter jwtRequestFilter;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final PasswordEncoder passwordEncoder;
// Allows any request towards /auth/ and it's deratives and blocks any request
// towards /api/. Requires Bearer tokens to authenticate
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**", "/public/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
@Autowired
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userService)
.passwordEncoder(passwordEncoder.bCryptPasswordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
@Configuration
@AllArgsConstructor
@Order(1)
public static class BasicAuth extends WebSecurityConfigurerAdapter {
private final PasswordEncoder passwordEncoder;
private final CustomBasicAuthenticationEntryPoint customBasicAuthenticationEntryPoint;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder.bCryptPasswordEncoder().encode("user12345!"))
.roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/public/**").permitAll()
.antMatchers("/orders/**").hasRole("ADMIN")
.and()
.httpBasic();
}
}
}
Which part of codes will need change?