简体   繁体   中英

Spring security UsernamePasswordAuthenticationToken always returns 403: User credentials have expired

I'm trying to implement a Spring security JWT based authorization inside my kotlin app but on every /authenticate (login) the UsernamePasswordAuthenticationToken finds the user in database but returns 403: User credentials have expired, even for just added user.

SecurityConfiguration class:

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
class SecurityConfiguration(
private val userDetailsService: UserDetailService,
private val jwtAuthorizationFilter: JwtAuthorizationFilter,
) : WebSecurityConfigurerAdapter() {

@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
    http.cors().and()
        .csrf().disable()
         http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter::class.java)
        .authorizeRequests()
        .antMatchers("/api/public/**").permitAll()
        .antMatchers("/api/authenticate").permitAll()
        .anyRequest().authenticated()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}

@Bean
@Throws(Exception::class)
override fun authenticationManagerBean(): AuthenticationManager {
    return super.authenticationManagerBean()
}

@Throws(Exception::class)
public override fun configure(auth: AuthenticationManagerBuilder) {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder())
}

@Bean
fun passwordEncoder() = BCryptPasswordEncoder()

@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", CorsConfiguration().applyPermitDefaultValues())
    return source
 }
}

AuthorizationFilter class

@Component
class JwtAuthorizationFilter(
private val jwtUtil: JtwUtil,
private val userDetailsService: UserDetailsService) : OncePerRequestFilter() {

@Throws(IOException::class, ServletException::class)
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse,
                              filterChain: FilterChain
) {
    val header = request.getHeader(SecurityConstants.TOKEN_HEADER)

    if (StringUtils.isEmpty(header) || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
        filterChain.doFilter(request, response)
        return
    }

    val jwt: String = header.substring(7)
    val username: String? = jwtUtil.extractUsername(jwt)

    if (username != null && SecurityContextHolder.getContext().authentication == null) {
        val userDetails: UserDetails = userDetailsService.loadUserByUsername(username)
        val isValidToken: Boolean = jwtUtil.validateToken(jwt, userDetails)
        if (isValidToken) {
            val usernamePasswordAuthenticationToken = 
    UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities)
            usernamePasswordAuthenticationToken.details = 
    WebAuthenticationDetailsSource().buildDetails(request)
            SecurityContextHolder.getContext().authentication = 
    usernamePasswordAuthenticationToken
        }
    }

    filterChain.doFilter(request, response)
 }
}

UserDetailsService:

@Service
class UserDetailService(private val userRepository: UserRepository): UserDetailsService {
override fun loadUserByUsername(username: String?): UserDetails? {
    try {
        val user: UserTable = userRepository.findByUsername(username)
            ?: throw UsernameNotFoundException("Username $username not found")
        return AppUserDetails(user)

    } catch (e: Exception) {
        throw Exception(e)
    }
}

This is the API I call to try and authorize user in database

@RequestMapping("/api/authenticate")
@RestController
class AuthenticationController(
private val authenticationManager: AuthenticationManager,
private val userDetailsService: UserDetailsService,
private val userDetailService: UserDetailService,
private val jwtUtil: JtwUtil
) {

@PostMapping
fun authenticateUser(@RequestBody authenticationRequest: AuthenticationRequest): 
 ResponseEntity<AuthenticationResponse> {
    try {
        
 authenticationManager.authenticate
 (UsernamePasswordAuthenticationToken(authenticationRequest.username, 
 authenticationRequest.password))

        val userDetails: UserDetails = 
 userDetailsService.loadUserByUsername(authenticationRequest.username)
        val jwt: String = jwtUtil.generateToken(userDetails)

        return ResponseEntity.ok(AuthenticationResponse(jwt))
    } catch (e: BadCredentialsException) {
        throw BadCredentialsException("Incorrect username or password $e")
    }
}

I've debugged the request and found that the authentication fails on this method:
AbstractUserDetailsAuthenticationProvider

错误

Found the issue, might help someone else. In my UserDetails service where I map the User I've hardcoded the method to always returns false

  override fun isCredentialsNonExpired(): Boolean {
    return false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM