使用 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-middlewarehttp4s-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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,172评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,346评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,788评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,299评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,409评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,467评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,476评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,262评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,699评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,994评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,167评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,499评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,149评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,387评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,028评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,055评论 2 352