กลยุทธ์การยืนยันตัวตนและการอนุญาต
รักษาความปลอดภัยให้จุดปลายทาง API ด้วยวิธีการยืนยันตัวตนทั่วไป เช่น JWT และนำกฎการอนุญาตมาใช้
กลยุทธ์การยืนยันตัวตนและการอนุญาต เป็นบทเรียน Elixir & Phoenix: Scalable Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Elixir & Phoenix: Scalable Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Securing Your API Endpoints
When building APIs with Phoenix, securing your endpoints is paramount. This ensures only authorized users can access specific resources and perform actions.
We'll explore two key aspects: Authentication (proving who you are) and Authorization (determining what you can do).
What is Authentication?
Authentication is the process of verifying a user's identity. It's how your API confirms that the person or application making a request is who they claim to be.
- Common methods include username/password, API keys, or tokens.
- Once authenticated, the user's identity is known to the system.
Token-Based Authentication
For APIs, sending username/password with every request is inefficient and insecure. Token-based authentication is a popular solution.
After initial login, the server issues a unique token. The client then sends this token with subsequent requests to prove its identity, without re-sending credentials.
JSON Web Tokens (JWT)
JSON Web Tokens (JWTs) are a common type of token. They are compact, URL-safe means of representing claims to be transferred between two parties.
A JWT is essentially a string with three parts, separated by dots:
- Header: Describes the token type and signing algorithm.
- Payload: Contains the 'claims' (user data, roles, expiration).
- Signature: Verifies the token's integrity and authenticity.
JWT Header and Payload
Both the Header and Payload are JSON objects, Base64Url-encoded. This encoding makes them safe for URL transmission, but it's not encryption – anyone can read them.
Let's see how to encode a simple Header and Payload in Elixir:
alias Jason
alias Base
defmodule JWTExample do
def encode_part(data) do
data
|> Jason.encode!()
|> Base.url_encode64(padding: false)
end
def main do
header = %{"alg" => "HS256", "typ" => "JWT"}
payload = %{"user_id" => 123, "role" => "admin"}
encoded_header = encode_part(header)
encoded_payload = encode_part(payload)
IO.puts "Encoded Header: " <> encoded_header
IO.puts "Encoded Payload: " <> encoded_payload
end
end
JWTExample.main()JWT Signature Explained
The Signature is crucial for security. It's created by taking the encoded Header, the encoded Payload, a secret key, and the algorithm specified in the header, then cryptographically signing them.
This signature ensures the token hasn't been tampered with. If someone changes the header or payload, the signature verification will fail.
Creating & Verifying a JWT
Here's a full Elixir example demonstrating how to combine the parts to create a simple JWT and then verify its integrity. We'll use a secret key for signing.
Notice how `Base.url_decode64` and `:crypto.mac` are used to simulate JWT logic.
alias Jason
alias Base
defmodule JWTService do
@secret_key "my_super_secret_key_123"
def create_token(payload) do
header = %{"alg" => "HS256", "typ" => "JWT"}
encoded_header = encode_part(header)
encoded_payload = encode_part(payload)
signature = sign(encoded_header, encoded_payload)
"#{encoded_header}.#{encoded_payload}.#{signature}"
end
def verify_token(token) do
[encoded_header, encoded_payload, signature] = String.split(token, ".")
expected_signature = sign(encoded_header, encoded_payload)
if signature == expected_signature do
decoded_payload = encoded_payload |> Base.url_decode64!() |> Jason.decode!()
{:ok, decoded_payload}
else
{:error, "Invalid signature"}
end
end
defp encode_part(data) do
data
|> Jason.encode!()
|> Base.url_encode64(padding: false)
end
defp sign(encoded_header, encoded_payload) do
data_to_sign = "#{encoded_header}.#{encoded_payload}"
:crypto.mac(:hmac, :sha256, @secret_key, data_to_sign)
|> Base.url_encode64(padding: false)
end
def main do
payload = %{"user_id" => 456, "role" => "editor", "exp" => 1678886400}
token = create_token(payload)
IO.puts "Generated Token: " <> token
case verify_token(token) do
{:ok, data} -> IO.puts "Verified! Payload: " <> inspect(data)
{:error, reason} -> IO.puts "Verification Failed: " <> reason
end
# Simulate tampering
tampered_payload = %{"user_id" => 456, "role" => "admin", "exp" => 1678886400}
tampered_token = create_token(tampered_payload)
[h, _p, s] = String.split(tampered_token, ".")
# Replace the payload but keep original signature
tampered_token_str = "#{h}." <> (payload |> Jason.encode!() |> Base.url_encode64(padding: false)) <> ".#{s}"
IO.puts "\nTampered Token: " <> tampered_token_str
case verify_token(tampered_token_str) do
{:ok, data} -> IO.puts "Verified (unexpectedly)! Payload: " <> inspect(data)
{:error, reason} -> IO.puts "Tampering Detected: " <> reason
end
end
end
JWTService.main()What is Authorization?
Once a user is authenticated (we know who they are), Authorization determines what actions they are allowed to perform and what resources they can access.
It's about permissions. For example, an 'admin' user might be able to delete posts, while a 'guest' user can only view them.
Role-Based Access Control (RBAC)
A common authorization strategy is Role-Based Access Control (RBAC).
- Users are assigned one or more roles (e.g., 'admin', 'editor', 'viewer').
- Each role has a predefined set of permissions (e.g., 'create_post', 'edit_own_post', 'delete_any_post').
- When a request comes in, the system checks if the authenticated user's role has the necessary permission for the requested action.
Authorization with Phoenix Plugs
In Phoenix, Plugs are an excellent way to implement authorization logic. A Plug is a modular function that processes requests.
You can create a Plug that checks the user's role (often extracted from a JWT payload) before allowing access to a controller action or an entire scope of routes.
For example, a `RequireAdminPlug` would halt the request if the user's role isn't 'admin'.
JWT & Authz Check
Which of the following statements about JWTs and API security are TRUE?
Summary: Secure Your APIs
You've learned the fundamentals of securing API endpoints!
- Authentication confirms identity, often using tokens like JWTs.
- JWTs consist of an encoded Header, Payload, and a cryptographic Signature for integrity.
- Authorization defines what an authenticated user can do, commonly managed with Role-Based Access Control (RBAC).
- Phoenix Plugs are ideal for implementing authorization checks in your API routes.
Keep exploring security best practices to build robust and safe applications!
คำถามที่พบบ่อย
บทเรียน “กลยุทธ์การยืนยันตัวตนและการอนุญาต” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “กลยุทธ์การยืนยันตัวตนและการอนุญาต” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Elixir & Phoenix: Scalable Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “กลยุทธ์การยืนยันตัวตนและการอนุญาต”
รักษาความปลอดภัยให้จุดปลายทาง API ด้วยวิธีการยืนยันตัวตนทั่วไป เช่น JWT และนำกฎการอนุญาตมาใช้ คุณปฏิบัติ Elixir & Phoenix: Scalable Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Elixir & Phoenix: Scalable Backend Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Elixir & Phoenix: Scalable Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “กลยุทธ์การยืนยันตัวตนและการอนุญาต” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Elixir & Phoenix: Scalable Backend Development นี้ได้ไหม
ได้ บทเรียน Elixir & Phoenix: Scalable Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- หลักการและแนวทางปฏิบัติที่ดีในการออกแบบ API
- การนำจุดปลายทาง API และการทำอนุกรมมาใช้
- กลยุทธ์การยืนยันตัวตนและการอนุญาต
- การแบ่งหน้า การกรอง และการกำหนดรุ่น API