使用 Http4s 构建 Web 服务(二)- Auth

接下来增加一下授权的功能。

basic auth

这里会使用middleware来进行授权的验证。具体关于middleware的描述可以看https://http4s.org/v1/docs/middleware.html
我们可以使用http4s里提供的AuthMiddleware。先看一下它的签名:

    def apply[F[_]: Monad, T](
        authUser: Kleisli[OptionT[F, *], Request[F], T]
    ): AuthMiddleware[F, T]

    def apply[F[_], Err, T](
        authUser: Kleisli[F, Request[F], Either[Err, T]],
        onFailure: AuthedRoutes[Err, F],
    )(implicit F: Monad[F]): AuthMiddleware[F, T]

它有两个apply方法,都需要一个authUser的参数,这个参数的类型是Kleisli,这也是由于HttpRoutes的实现是个Kleisli。

接下来尝试去使用一些这个middleware。首先需要有一个用户相关的Model

  case class User(id: Int, name: String, password: String)

并准备一个简单的验证方法

  def isValidCredentials(credentials: (String, String)): Boolean =
    credentials match {
      // username is admin and password is password is allowed to access
      case (x, y) if x == "admin" && y == "password" => true
      case _ => false
    }

同时精简一下之前的代码,只保留和seller有关的代码。

先实现一下第一个apply方法,可以看到参数只有一个authUser,并且类型是Kleisli[OptionT[F, *], Request[F], T]

  private val basicAuthUser = Kleisli[OptionT[IO, *], Request[IO], User] {
    request => {
      // get credential from header
      val maybeCredentials: Option[(String, String)] = request.headers.get[Authorization].collect {
        case Authorization(BasicCredentials(credentials)) => credentials
      }

      // if there is credential exist then return user information
      maybeCredentials match {
        case Some(creds) if isValidCredentials(creds) => // check user if has permission
          OptionT.liftF(IO(User(1, creds._1, creds._2)))
        case _ =>
          OptionT.none[IO, User]
      }
    }
  }

  private val useBasicAuthMiddleware: AuthMiddleware[IO, User] =
    AuthMiddleware(basicAuthUser)

然后修改withHttpApp的部分

override def run(args: List[String]): IO[ExitCode] = {
  EmberServerBuilder
          .default[IO]
          .withHost(ipv4"0.0.0.0")
          .withPort(port"8085")
          .withHttpApp(useBasicAuthMiddleware(sellerRoutes[IO]).orNotFound) // use AuthMiddleware to include Routes
          .build
          .use(_ => IO.never)
          .as(ExitCode.Success)
}

此时运行一下之前查询seller的请求

curl -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Wed, 01 Nov 2023 05:52:08 GMT
< Connection: keep-alive
< Content-Length: 0
<
* Connection #0 to host localhost left intact

可以看到得到了401 Unauthorized。如果在header里面增加用户的信息再看一下

echo -n admin:password | base64
> YWRtaW46cGFzc3dvcmQ=

curl -H "Authorization:Basic YWRtaW46cGFzc3dvcmQ=" -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
> Authorization:Basic YWRtaW46cGFzc3dvcmQ=
>
< HTTP/1.1 200 OK
< Date: Wed, 01 Nov 2023 07:19:17 GMT
< Connection: keep-alive
< Content-Type: application/json
< Content-Length: 37
<
* Connection #0 to host localhost left intact
{"firstName":"Tom","lastName":"Ming"}%

此时已经能拿到seller的结果了。
那么如果想返回指定的错误信息呢,就可以使用第二个apply方法了。需要传入一个onFailure的参数,而且authUser的类型也发生了变化。下面的是代码:

    val basicAuthUser = Kleisli.apply[IO, Request[IO], Either[String, User]] { request =>
      // auth logic
      val authHeader = request.headers.get[Authorization]
      authHeader match {
        case Some(Authorization(BasicCredentials(credentials))) if isValidCredentials(credentials) =>
          IO(Right(User(1, credentials._1, credentials._2))) // this user normally get from DB
        case Some(_) => IO(Left("Credentials wrong")) // if auth info is wrong
        case None => IO(Left("Unauthorized! Stop!")) // if no auth info
      }
    }

    var onFailure: AuthedRoutes[String, IO] = Kleisli(req => OptionT.liftF(Forbidden(req.context)))

    //middleware
    val useBasicAuthMiddleware: AuthMiddleware[IO, User] = AuthMiddleware(basicAuthUser, onFailure)

如果测试一下的happy path的话,结果和上面是一样的。下面我们测试一下错误的场景

curl -H "Authorization:Basic xxxxxxxxxxxxxx" -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
> Authorization:Basic YWRtaW46cGFzc3dvcmQ=1
>
< HTTP/1.1 403 Forbidden
< Date: Wed, 01 Nov 2023 07:19:09 GMT
< Connection: keep-alive
< Content-Type: application/json
< Content-Length: 19
<
* Connection #0 to host localhost left intact
"Credentials wrong"%

以及header里没有任何信息的情况

curl -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Date: Wed, 01 Nov 2023 06:56:26 GMT
< Connection: keep-alive
< Content-Type: application/json
< Content-Length: 21
<
* Connection #0 to host localhost left intact
"Unauthorized! Stop!"%

另外这里其实也可以直接使用http4s自己的BasicAuth。增加如下代码:

    val authenticator: BasicAuthenticator[IO, User] = { (credentials: BasicCredentials) =>
      if (credentials.username == "admin" && credentials.password == "password") {
        IO.pure(Some(User(1, credentials.username, credentials.password)))
      } else {
        IO.pure(None)
      }
    }

  val http4sBasicAuth: AuthMiddleware[IO, User] = BasicAuth("Your Realm", authenticator) 

  override def run(args: List[String]): IO[ExitCode] = {
    EmberServerBuilder
      .default[IO]
      .withHost(ipv4"0.0.0.0")
      .withPort(port"8085")
      .withHttpApp(http4sBasicAuth(sellerRoutes[IO]).orNotFound)
      .build
      .use(_ => IO.never)
      .as(ExitCode.Success)
}

运行一下,会发现和之前的效果是一样的

下面试一下Digest的验证方式

这里使用http4s自带的DigestAuth即可。按照之前的BasicAuth的方式,先创建一个Middleware。

val digestAuthMiddlewareApply: AuthMiddleware[IO, User] = DigestAuth[IO, User]("Your Realm", funcPass)

但是此时编译会报错。原因是DigestAuth的apply方法会产生副作用,建议使用applyF。此时查看一下applyF的方法签名,会发现它返回的不再是AuthMiddleware,而是被包了一层的AuthMiddleware。这就意味着我们没办法直接使用它。但是没关系,先把必须的逻辑补全。从参数里看到applyF方法组要一个AuthStore。http4s提供了2种,提供了PlainTextAuthStoreMd5HashedAuthStore,而且很明显的推荐Md5HashedAuthStore,因为密码还是不要使用明文。

例子如下:

  val digestAuthMiddlewareApplyF: IO[AuthMiddleware[IO, User]] =
    DigestAuth.applyF[IO, User]("Your Realm", Md5HashedAuthStore(checkFunction))

还需要提供一个验证的方法。这里写了一个临时的代码,实际上可以先根据用户名取出用户信息,然后再进行验证

  val checkFunction: String => IO[Option[(User, String)]] = (username: String) =>
  // can get user info from DB or somewhere
  username match {
    case "admin" =>
      val digestAuthStore = Md5HashedAuthStore.precomputeHash[IO]("admin", "Your Realm", "password")
      digestAuthStore.flatMap(hash => IO(Some(User(1, "admin", ""), hash)))
  }

必须的方法准备完了,接下来还是要把路由包一下。不过按照之前说的,因为它的返回值不再是AuthMiddleware。所以不能像上面的方式直接写成digestAuthMiddlewareApplyF(sellerRoutes[IO]).orNotFound
所以这里最后写成

    digestAuthMiddlewareApplyF
      .flatMap(wrapper =>
        EmberServerBuilder
          .default[IO]
          .withHost(ipv4"0.0.0.0")
          .withPort(port"8085")
          .withHttpApp(wrapper(sellerRoutes[IO]).orNotFound)
          .build
          .use(_ => IO.never)
      )
      .as(ExitCode.Success)

测试一下

curl --digest -u admin:password -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
* Server auth using Digest with user 'admin'
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Mon, 20 Nov 2023 07:33:16 GMT
< Connection: keep-alive
< WWW-Authenticate: Digest realm="Your Realm",qop="auth",nonce="725fd843136f649151c9f84b8aa41deac88d8cac"
< Content-Length: 0
<
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:8085/sellers?first_name=Tom'
* Found bundle for host: 0x600001c44480 [serially]
* Can not multiplex, even if we wanted to
* Re-using existing connection #0 with host localhost
* Server auth using Digest with user 'admin'
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> Authorization: Digest username="admin", realm="Your Realm", nonce="725fd843136f649151c9f84b8aa41deac88d8cac", uri="/sellers?first_name=Tom", cnonce="ZjY0ZmUzZWYxNjkyNDgyMmQ0M2IxODZkMWI0NmY4OTk=", nc=00000001, qop=auth, response="87e0791530daad3c0cf9ec5c4b6f3c98"
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Mon, 20 Nov 2023 07:33:16 GMT
< Connection: keep-alive
< Content-Type: application/json
< Content-Length: 37
<
* Connection #0 to host localhost left intact
{"firstName":"Tom","lastName":"Ming"}%

尝试一个错误的密码

curl --digest -u admin:password2 -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
* Server auth using Digest with user 'admin'
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Mon, 20 Nov 2023 07:33:21 GMT
< Connection: keep-alive
< WWW-Authenticate: Digest realm="Your Realm",qop="auth",nonce="e8f8bae26b8614bfc8e5b60c9e6f227e60088695"
< Content-Length: 0
<
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:8085/sellers?first_name=Tom'
* Found bundle for host: 0x6000035e8780 [serially]
* Can not multiplex, even if we wanted to
* Re-using existing connection #0 with host localhost
* Server auth using Digest with user 'admin'
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> Authorization: Digest username="admin", realm="Your Realm", nonce="e8f8bae26b8614bfc8e5b60c9e6f227e60088695", uri="/sellers?first_name=Tom", cnonce="MjdiN2U1NTg1MDc2NWQwZDU0ZTJmMDY1NzBjMDRiZGY=", nc=00000001, qop=auth, response="bc3ca3095712555dffe50501b9b99014"
> User-Agent: curl/8.1.2
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Mon, 20 Nov 2023 07:33:21 GMT
< Connection: keep-alive
* Authentication problem. Ignoring this.
< WWW-Authenticate: Digest realm="Your Realm",qop="auth",nonce="5aee5d04c90e3445c5cc66146f6450a01973a538"
< Content-Length: 0
<
* Connection #0 to host localhost left intact

Jwt

Jwt验证是很常用的一个方式,这里有很多library可以使用,例如http4s-jwt-auth-middleware和http4s-jwt-auth

不过很不幸的是这2个都仅仅支持http4s的版本到0.23.23。而且http4s-jwt-auth-middleware已经1年多没更新了,目前版本知道0.5.0。而http4s-jwt-auth仍然在持续更新。所以我们这里使用http4s-jwt-auth

首先创建一个自己的token来进行测试,key是your_secret_key,id是123,username是admin

可以使用一个简单的python脚本来做

import jwt
import datetime

secret_key = 'your_secret_key'

payload = {
    'user_id': 123,
    'username': 'admin',
    'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}

token = jwt.encode(payload, secret_key, algorithm='HS256')

print(token)

然后增加如下代码

  val authenticate: JwtToken => JwtClaim => IO[Option[User]] =
  token => claim => User(123, "admin", "").some.pure[IO]

val jwtAuth = JwtAuth.hmac("your_secret_key", JwtAlgorithm.HS256)
val jwtAuthMiddleware = JwtAuthMiddleware[IO, User](jwtAuth, authenticate)

然后route用这个新的Middleware包一下,代码如下:

    EmberServerBuilder
      .default[IO]
      .withHost(ipv4"0.0.0.0")
      .withPort(port"8085")
      .withHttpApp(jwtAuthMiddleware(sellerRoutes[IO]).orNotFound)
      .build
      .use(_ => IO.never)
      .as(ExitCode.Success)

测试一下,在header里面带上上面生成的token:

curl -H "Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MTIzLCJleHAiOjE3MDA3MTY0OTB9.CGy6Nn6ObDmDo1laCKf1KwuSetzo3_60qvRgboVHCYc" -v "localhost:8085/sellers?first_name=Tom"
*   Trying 127.0.0.1:8085...
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /sellers?first_name=Tom HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/8.1.2
> Accept: */*
> Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MTIzLCJleHAiOjE3MDA3MTY0OTB9.CGy6Nn6ObDmDo1laCKf1KwuSetzo3_60qvRgboVHCYc
>
< HTTP/1.1 200 OK
< Date: Thu, 23 Nov 2023 04:37:29 GMT
< Connection: keep-alive
< Content-Type: application/json
< Content-Length: 37
<
* Connection #0 to host localhost left intact
{"firstName":"Tom","lastName":"Ming"}%

但是如果token不正确,就会返回403 Forbidden

你可能感兴趣的:(使用 Http4s 构建 Web 服务(二)- Auth)