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()
}
}
user24816708 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.