SHARE
TWEET

Http4s authentication middleware

mitrakov Aug 24th, 2019 (edited) 98 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Example of Auth Middleware with Http4s.
  2. // See https://pastebin.com/zUjAgTdw for more details.
  3.  
  4. import cats.data.{Kleisli, OptionT}
  5. import cats.effect.Sync
  6. import org.http4s.dsl.Http4sDsl
  7. import org.http4s.headers.Authorization
  8. import org.http4s.server.AuthMiddleware
  9. import org.http4s.{AuthedRoutes, HttpRoutes, Request}
  10.  
  11. object SettingSecuredRoutes {
  12.   def routes[F[_]: Sync](authService: AuthService[F], service: SomeService[F]): HttpRoutes[F] = {
  13.     val dsl = new Http4sDsl[F] {}
  14.     import dsl._
  15.     import cats.implicits._
  16.     import io.circe.syntax._
  17.     import org.http4s.circe.CirceEntityDecoder._
  18.     import org.http4s.circe.CirceEntityEncoder._
  19.  
  20.     val onFailure: AuthedRoutes[String, F] = Kleisli(req => OptionT.liftF(Forbidden(req.authInfo)))
  21.     val authUser: Kleisli[F, Request[F], Either[String, Long]] = Kleisli { request =>
  22.       val either = for {
  23.         token <- request.headers.get(Authorization).map(_.value.toLowerCase.replace("bearer ", "")).toRight(s"Authorization header not found")
  24.         result <- authService.isTokenValid(token).leftMap(_.toString)
  25.       } yield result
  26.       implicitly[Sync[F]].pure(either) // we must wrap it into effect F for possible changes that might require IO operations
  27.     }
  28.  
  29.     AuthMiddleware(authUser, onFailure).apply(AuthedRoutes.of {
  30.       case GET -> Root / "settings" as userId => {
  31.         for {
  32.           result <- service.getByUserId(userId)
  33.           ok <- Ok(result)
  34.         } yield ok
  35.       }
  36.     })
  37.   }
  38. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top