When i create a user in my system, it creates an account in firebase auth. Then when I login in my front end, I receive the access token (JWT) that I want to use to authenticate the user with my API, the problem is for my POST /order route, I keep getting this message in my console when I send the request via Postman Securing POST /order
with a 401 unauthorized. I’m not sure why, I set the Jwtdecoder as googles, but i’m still having this problem. I’m also settting the jwt as bearer token in postman. Here’s my controller
import com.delivery.edar.config.JwtUtils
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/order")
class OrderController(val orderService: OrderService) {
// @GetMapping
// fun findOrdersByUser(): Iterable<ViewOrder> = orderRepository.findAll().map { it.toView() };
fun create(
@AuthenticationPrincipal token: JwtAuthenticationToken,
@RequestBody createOrderRequest: CreateOrderRequest
): ResponseEntity<OrderView> {
val firebaseUserId = token.token.claims["user_id"] as? String
?: return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()
val order = orderService.createOrder(createOrderRequest, firebaseUserId)
return ResponseEntity.status(HttpStatus.CREATED).body(order.toView())
}
}
Here’s my security config:
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder
import org.springframework.security.web.SecurityFilterChain
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
fun configure(http: HttpSecurity): SecurityFilterChain {
http
.authorizeHttpRequests { authorize ->
authorize
.requestMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
}
.csrf { it.disable() }
.oauth2ResourceServer {
it.jwt { }
}
.sessionManagement { session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
return http.build()
}
@Bean
fun jwtDecoder(): JwtDecoder {
val jwkUri = "https://www.googleapis.com/service_accounts/v1/jwk/[email protected]"
return NimbusJwtDecoder.withJwkSetUri(jwkUri).build()
}
}