目錄

安裝 Hydra

開始詳細介紹 Hydra 前,先來看看如何安裝。

使用 Homebrew 安裝:

brew tap ory/hydra
brew install ory/hydra/hydra
hydra help

直接下載 binary 即可。

curl https://raw.githubusercontent.com/ory/ory/master/install.sh | bash -s -- -b .
./hydra

# 放到全域空間下
sudo mv ./hydra /usr/local/bin/

Hydra 有提供 Docker Repo 可以直接下載執行:

docker run --rm -it oryd/hydra:v1.8.5 help

Hydra 使用 Golang 撰寫,原始碼就放在 GitHub 上,直接下載再 compile 即可:

export GO111MODULE=on
go mod download
go build

從最後一個 compile 範例可以知道,其實 Hydra 就是一個執行檔而已,上面都是拿到可執行檔的方法。實際要能啟動它,會需要設定多個參數才能正常運作,建議是寫成 Docker Compose 的形式會比較簡單。

官方有提供 Docker Compose 範例檔,我自己整理過之後是長像下面這樣:

version: '3'

services:
  web:
    image: laravel_web_app
    container_name: web.localhost
    hostname: web.localhost
    ports
      - 8000:8000
    depends_on:
      - hydra

  hydra:
    image: oryd/hydra:v1.8.5
    container_name: hydra.localhost
    hostname: hydra.localhost
    ports:
      - 4444:4444
    command:
      serve all --dangerous-force-http
    environment:
      DSN: mysql://root:secret@tcp(mysqld:3306)/hydra?max_conns=20&max_idle_conns=4
      URLS_SELF_ISSUER: http://hydra.localhost:4444
      URLS_LOGIN: http://web.localhost:8080/idp/login
      URLS_CONSENT: http://web.localhost:8080/idp/consent
      URLS_LOGOUT: http://web.localhost:8080/idp/logout
      SECRETS_SYSTEM: youReallyNeedToChangeThis
      OIDC_SUBJECT_TYPES_SUPPORTED: public,pairwise
      OIDC_SUBJECT_TYPE_PAIRWISE_SALT: youReallyNeedToChangeThis
    restart: unless-stopped
    depends_on:
      - hydra-migrate

  hydra-migrate:
    image: oryd/hydra:v1.2.3
    environment:
      - DSN=mysql://root:secret@tcp(mysqld:3306)/hydra?max_conns=20&max_idle_conns=4
    command:
      migrate sql -e --yes
    restart: on-failure

  mysqld:
    image: mysql:5.7
    ports:
      - 3306:3306
    environment:
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: hydra

然後在 hosts 的設定裡加上這兩個:

127.0.0.1	web.localhost
127.0.0.1	hydra.localhost

Hydra 的設計是,當啟動後會開啟兩個 port,分別是 Public 與 Admin。預設 Public 會開在 4444 port,Admin 則是 4445。上面的 Docker Compose 設定是故意把 Admin 藏起來,改用指令存取。

指令控制的做法可以參考 12 Factor 的 Admin processes

啟動後,即可用 http://hydra.localhost:4444 存取 Hydra 的 public 接口。Admin 的用途如新增 client,以下是用 Makefile 作為範例:

CLIENT_ID := some-client
CLIENT_SECRET := some-secret
CLIENT_CALLBACK := http://web.localhost:8080/rp/callback

setup:
	docker-compose exec hydra hydra --endpoint http://127.0.0.1:4445/ clients --skip-tls-verify \
		delete ${CLIENT_ID}
	docker-compose exec hydra hydra --endpoint http://127.0.0.1:4445/ clients --skip-tls-verify \
		create \
		--id ${CLIENT_ID} \
		--secret ${CLIENT_SECRET} \
		--grant-types authorization_code,refresh_token,client_credential \
		--response-types code \
		--scope openid,offline_access \
		--token-endpoint-auth-method client_secret_basic \
		--callbacks ${CLIENT_CALLBACK}

如果上面的指令能正常執行,代表 Hydra 執行正常。但 public 接口的測試則要下一階段才能執行。


到此為此,已完成 Hydra 服務建置,下一次就可以來實作屬於自己的登入與授權機制了。