401 Unauthorized при регистрации в Spring

Добавил Spring Security в проект, все запросы выполняются успешно, кроме регистрации. Когда пытаюсь зарегистрироваться, создаётся пользователь в базе данных, но не генерируется токен. Но, если пользователь уже существует, то авторизация проходит успешно и токен создаётся. Регистрация прерывается после val authentication: Authentication = authenticationManager!!.authenticate(UsernamePasswordAuthenticationToken(userModel.userLogin, userModel.password))

Метод регистрации:

@PostMapping("/register/*", "/registration/*", "/reg/*")
private fun registration(@RequestBody userModel: UserModel): ResponseEntity<Any> {
    return if (userModel.password.length >= 6 || userModel.userLogin.trim().isNotBlank()) {
        val authedUser = userService.register(userModel)
        if (authedUser != null && authedUser.id >= 0) {
            authedUser.password = "It's a big secret"
            val jwt = tokenAuth(userModel = userModel)
            okResponse(AuthorizationResponse(user = authedUser, tokenData = Token(token = jwt)))
        } else errorResponse(ErrorMessages.ERROR_AUTHENTICATION)
    } else errorResponse(ErrorMessages.ERROR_AUTHENTICATION)
}

private fun tokenAuth(userModel : UserModel) : String{
    val authentication: Authentication = authenticationManager!!
        .authenticate(UsernamePasswordAuthenticationToken(userModel.userLogin, userModel.password))
    SecurityContextHolder.getContext().authentication = authentication
    return tokenProvider!!.generateToken(authentication)
}

Регистрация в сервисе

fun register(user: UserModel): UserModel? {
    if (user.password.trim().isNotEmpty()) {
        user.password = passwordEncoder.encode(user.password)
        user.uuid = UUID.randomUUID().toString()
        return userRepository.save(user)
    }
    return null
}

SecurityConfig

    @Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SpringSecurityConfig : WebSecurityConfigurerAdapter() {
    @Autowired
    private val userDetailsService: UserDetailsService? = null

    @Bean
    fun jwtAuthenticationFilter(): JwtAuthenticationFilter? {
        return JwtAuthenticationFilter()
    }

    @Bean
    fun passwordEncoder(): PasswordEncoder? {
        return BCryptPasswordEncoder()
    }

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

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

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http
            .headers().frameOptions().sameOrigin()
            .and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/auth/login/").permitAll()
            .antMatchers( "/auth/registration/").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint { _: HttpServletRequest?, res: HttpServletResponse, ex: AuthenticationException ->
                res.sendError(
                    HttpServletResponse.SC_UNAUTHORIZED,
                    "UNAUTHORIZED : " + ex.message
                )
            }
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter::class.java)
    }

}

Ответы (0 шт):