Olá pessoal, uma sugestão de atualização. Como na nova versão do Spring Security não tem o método authenticationManager(), o que pode fazer é injetar o AuthenticationConfiguration no construtor da classe e usar o authenticationManager dele. Ficou assim o código:
@Configuration
@EnableWebSecurity
class SecurityConfiguration (
private val configuration: AuthenticationConfiguration,
private val userDetailsService: UserDetailsService,
private val jwtUtil: JWTUtil
){
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
return http
.csrf { it.disable() }
.authorizeHttpRequests {
it
.requestMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
}
.addFilterBefore(JWTLoginFilter(authenticationManager = configuration.authenticationManager, jwtUtil = jwtUtil), UsernamePasswordAuthenticationFilter().javaClass)
.sessionManagement {
it.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}.build()
}
@Bean
fun encoder(): PasswordEncoder = BCryptPasswordEncoder()
}
O filter, que vai ser apresentado na aula seguinte, ficou assim:
class JWTLoginFilter(
private val authenticationManager: AuthenticationManager?,
private val jwtUtil: JWTUtil,
) : UsernamePasswordAuthenticationFilter(authenticationManager) {
override fun attemptAuthentication(request: HttpServletRequest?, response: HttpServletResponse?): Authentication? {
val (username, password) = ObjectMapper().readValue(request?.inputStream, Credentials::class.java)
val token = UsernamePasswordAuthenticationToken(username, password)
return authenticationManager?.authenticate(token)
}
override fun successfulAuthentication(
request: HttpServletRequest?,
response: HttpServletResponse?,
chain: FilterChain?,
authResult: Authentication?
) {
val username = (authResult?.principal as UserDetails).username
val token = jwtUtil.generateToken(username)
response?.addHeader("Authorization", "Bearer $token")
}
}
Aqui funcionou perfeitamente.