Spring security returning 401 (Unauthorized)

It is possible to register and login, but then when I try to make a post from the frontend form it is returning Unauthorized even though I am logged in and the token and header is sent correctly from frontend, probably there is a problem with the authentication in the backend.
I tried to find solution, but most of the solutions are from previous versions of Spring and it is not working anymore.
I tried to permit all from that url .requestMatchers(HttpMethod.POST, "/api/new-post").permitAll() and even this isn’t working, it is still showing unauthorized
Here is my code:

class JwtAuthenticationFilter(private val authenticationManager: AuthenticationManager) : OncePerRequestFilter() {
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain
    ) {
        try {
            val jwt: String = request.getHeader("Authorization").substringAfter("Bearer ")
            val authentication = BearerTokenAuthenticationToken(jwt)
            val authResult = authenticationManager.authenticate(authentication)
            SecurityContextHolder.getContext().authentication = authResult
        } catch (e: Exception) {
            response.status = 401
            return
        }
    }

    override fun shouldNotFilter(request: HttpServletRequest): Boolean {
        return request.servletPath.equals("/api/login") ||
                request.servletPath.equals("/api/register") ||
                request.servletPath.equals("/api/home") ||
                request.servletPath.equals("/api/municipalities") ||
                request.servletPath.equals("/api/user/get")
    }
    
}
@Component
class CustomAuthenticationProvider(private val tokenService: TokenService): AuthenticationProvider {
    override fun authenticate(authentication: Authentication): Authentication? {
        if(authentication !is BearerTokenAuthenticationToken){
            return null
        }

        val jwt: BearerTokenAuthenticationToken = authentication
        val token: String = jwt.token
        val userDetails: UserDetails = tokenService.parseToken(token) ?: throw BadCredentialsException("Invalid token")

        val userId = tokenService.getUserIdFromToken(token) // Implement this method to extract userId from the token.

        return UsernamePasswordAuthenticationToken(
            CustomPrincipal(userDetails, userId),
            "",
            listOf(SimpleGrantedAuthority("USER"))
        )

    }

    override fun supports(authentication: Class<*>?): Boolean {
        return BearerTokenAuthenticationToken::class.java.isAssignableFrom(authentication)

    }
}
@Configuration
@EnableWebSecurity
class SecurityConfig(private val customAuthenticationProvider: CustomAuthenticationProvider) {

    @Bean
    fun authenticationManager(): AuthenticationManager {
        return ProviderManager(listOf(customAuthenticationProvider))
    }

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

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http.securityMatcher("/api/**")
            .authorizeHttpRequests { rmr ->
                rmr
                    .requestMatchers(HttpMethod.POST, "/api/login").permitAll()
                    .requestMatchers(HttpMethod.POST, "/api/register").permitAll()
                    .requestMatchers(HttpMethod.GET, "/api/home").permitAll()
                    .requestMatchers(HttpMethod.GET, "/api/municipalities").permitAll()
                    .requestMatchers(HttpMethod.GET, "/api/user/get").permitAll()
                    .requestMatchers(HttpMethod.POST, "/api/new-post").permitAll()
                    .requestMatchers("/api/**").authenticated()
                    .anyRequest().permitAll()
            }
            .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
            .csrf { it.disable() }

        http.oauth2ResourceServer { oauth2 ->
            oauth2
                .jwt(Customizer.withDefaults())
        }

        http.addFilterAt(jwtAuthenticationFilter(), BasicAuthenticationFilter::class.java)
        return http.build()
    }

}

New contributor

user24816708 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật