Elixir 语言 Phoenix API 接口版本控制与认证实战

Elixir阿木 发布于 2025-06-19 7 次阅读


Elixir 语言 Phoenix API 接口版本控制与认证实战

随着互联网的快速发展,API(应用程序编程接口)已成为现代软件开发中不可或缺的一部分。在构建API时,版本控制和认证是两个关键问题。本文将围绕Elixir语言的Phoenix框架,探讨如何实现API的版本控制和认证。

准备工作

在开始之前,请确保您已经安装了Elixir和Phoenix。以下是安装步骤:

1. 安装Elixir:

shell

安装Elixir语言


elixir --version


2. 创建一个新的Phoenix项目:

shell

创建一个新的Phoenix项目


mix phx.new api_versioning


3. 进入项目目录:

shell

进入项目目录


cd api_versioning


API版本控制

版本命名规范

在Elixir中,通常使用模块名来表示API版本。例如,`v1`版本可以表示为`Api.V1`,`v2`版本可以表示为`Api.V2`。

创建版本模块

在`lib/api_versioning`目录下,创建一个新的模块`v1.ex`:

elixir

defmodule Api.V1 do


use ApiVersioning.Web, :controller

def index(conn, _params) do


render(conn, "index.json", %{data: "v1 version"})


end


end


同样,创建`v2.ex`模块:

elixir

defmodule Api.V2 do


use ApiVersioning.Web, :controller

def index(conn, _params) do


render(conn, "index.json", %{data: "v2 version"})


end


end


路由配置

在`lib/api_versioning_web/router.ex`文件中,配置路由:

elixir

defmodule ApiVersioning.Web.Router do


use ApiVersioning.Web, :router

pipeline :api do


plug :accepts, ["json"]


end

scope "/api", ApiVersioning.Web do


pipe_through :api

scope "/v1" do


get "/index", Api.V1, :index


end

scope "/v2" do


get "/index", Api.V2, :index


end


end


end


调试API

启动Phoenix项目:

shell

启动Phoenix项目


mix phx.server


在浏览器中访问以下链接,查看不同版本的API:

- `http://localhost:4000/api/v1/index`

- `http://localhost:4000/api/v2/index`

API认证

JWT认证

JWT(JSON Web Token)是一种常用的认证方式。在Elixir中,可以使用`jwt`库来实现JWT认证。

1. 安装`jwt`库:

shell

安装jwt库


mix deps.get jwt


2. 创建认证模块:

在`lib/api_versioning_web/controllers/auth_controller.ex`文件中,创建一个新的模块`auth_controller.ex`:

elixir

defmodule ApiVersioning.Web.Controllers.AuthController do


use ApiVersioning.Web, :controller

alias ApiVersioning.Auth.Guardian

def sign_in(conn, %{"username" => username, "password" => password}) do


with {:ok, token, _claims} <- Guardian.encode_and_sign(username) do


conn


|> put_status(:created)


|> render("token.json", %{token: token})


end


end


end


3. 创建Guardian模块:

在`lib/api_versioning/auth/guardian.ex`文件中,创建一个新的模块`guardian.ex`:

elixir

defmodule ApiVersioning.Auth.Guardian do


use Guardian, otp_app: :api_versioning

def subject_for_token(user, _claims) do


{:ok, to_string(user.id)}


end

def resource_from_token(%{"sub" => id}, _claims) do


user = ApiVersioning.Accounts.get_user!(id)


{:ok, user}


end

def verify_token(token, claims) do


claims


end


end


4. 配置路由:

在`lib/api_versioning_web/router.ex`文件中,添加认证路由:

elixir

scope "/auth" do


post "/sign_in", ApiVersioning.Web.Controllers.AuthController, :sign_in


end


5. 调试认证API:

在浏览器中访问以下链接,进行用户认证:

- `http://localhost:4000/auth/sign_in?username=your_username&password=your_password`

获取JWT令牌后,在请求API时,将令牌添加到`Authorization`头部:

shell

curl -H "Authorization: Bearer your_token" http://localhost:4000/api/v1/index


总结

本文介绍了如何在Elixir语言的Phoenix框架中实现API版本控制和认证。通过创建不同版本的模块和配置路由,我们可以轻松地实现API版本控制。使用JWT认证可以确保API的安全性。希望本文对您有所帮助。