0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · درس

المصادقة والتفويض

طبّق آليات متينة للمصادقة والتفويض على العمليات والمستخدمين الذين يصلون إلى خدمات Erlang الخاصة بكم

المصادقة والتفويض درس مجاني في Erlang OTP: Distributed & Fault-Tolerant Systems Programming على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Erlang OTP: Distributed & Fault-Tolerant Systems Programming، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Erlang OTP: Distributed & Fault-Tolerant Systems Programming 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

AuthN & AuthZ Explained

In distributed systems, knowing who is accessing your services and what they are allowed to do is critical for security. This is where authentication and authorization come in.

  • Authentication (AuthN): Verifies the identity of a user or process. It answers the question, "Who are you?"
  • Authorization (AuthZ): Determines if an authenticated user or process has permission to perform a specific action or access a resource. It answers, "What are you allowed to do?"

They work hand-in-hand to secure your Erlang applications.

Identifying Users

For user authentication, we typically verify credentials like a username and password. In Erlang, you might have a dedicated service (often a GenServer) responsible for managing user accounts and validating login attempts.

This service would receive a login request, check the provided credentials against stored data, and respond with either success or failure. On success, it might issue a session ID or token.

Building an Auth GenServer

Let's create a very basic auth_service using GenServer. For simplicity, it will store a hardcoded user and password. In a real system, you'd integrate with a database and securely hash passwords.

Our auth_service will have a login/2 function that clients can call to authenticate.

Runnable Auth Service

Try running this simple authentication service. You can call auth_service:login("user", "pass") and auth_service:login("wrong", "pass") to see the different responses.

-module(auth_service).
-behaviour(gen_server).

-export([start_link/0, login/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
             terminate/2, code_change/3]).

% Client API
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

login(Username, Password) ->
    gen_server:call(?MODULE, {login, Username, Password}).

% GenServer Callbacks
init([]) ->
    % Store a simple user/pass for demonstration
    Users = #{<<"user">> => <<"pass">>},
    {ok, Users}.

handle_call({login, Username, Password}, _From, State) ->
    case maps:get(Username, State, undefined) of
        Password ->
            {reply, {ok, <<"authenticated">>}, State};
        _ ->
            {reply, {error, <<"invalid_credentials">>}, State}
    end;
handle_call(_Request, _From, State) ->
    {reply, {error, unknown_request}, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

What Can You Do?

Once a user is authenticated, the next step is authorization. This means deciding what actions they are allowed to perform. A common way to manage this is through Role-Based Access Control (RBAC).

  • Roles: Groups of permissions (e.g., admin, editor, viewer).
  • Permissions: Specific actions (e.g., create_post, edit_post, delete_post).

Users are assigned roles, and roles are assigned permissions.

Role-Based Access Control

We can extend our auth_service (or a separate service) to manage roles and permissions. It would need to know:

  • Which roles a user has.
  • Which permissions each role grants.

Then, when a service needs to check if a user can perform an action, it asks the authorization service.

Auth Service with RBAC

Here's an updated auth_service that includes a basic RBAC mechanism. It defines roles and permissions and allows checking if a user has a specific permission.

Try calling auth_service:check_permission("user", "read_data") and auth_service:check_permission("user", "delete_data") after logging in.

-module(auth_service).
-behaviour(gen_server).

-export([start_link/0, login/2, check_permission/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
             terminate/2, code_change/3]).

% Client API
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

login(Username, Password) ->
    gen_server:call(?MODULE, {login, Username, Password}).

check_permission(Username, Permission) ->
    gen_server:call(?MODULE, {check_permission, Username, Permission}).

% GenServer Callbacks
init([]) ->
    Users = #{
        <<"user">> => #{
            password => <<"pass">>,
            roles => [<<"viewer">>, <<"editor">>]
        },
        <<"admin">> => #{
            password => <<"admin_pass">>,
            roles => [<<"admin">>, <<"viewer">>]
        }
    },
    Roles = #{
        <<"viewer">> => [<<"read_data">>],
        <<"editor">> => [<<"read_data">>, <<"write_data">>],
        <<"admin">> => [<<"read_data">>, <<"write_data">>, <<"delete_data">>]
    },
    {ok, #{users => Users, roles => Roles}}.

handle_call({login, Username, Password}, _From, State) ->
    Users = maps:get(users, State),
    case maps:get(Username, Users, undefined) of
        #{password := Password} ->
            {reply, {ok, <<"authenticated">>}, State};
        _ ->
            {reply, {error, <<"invalid_credentials">>}, State}
    end;

handle_call({check_permission, Username, Permission}, _From, State) ->
    Users = maps:get(users, State),
    Roles = maps:get(roles, State),
    case maps:get(Username, Users, undefined) of
        #{roles := UserRoles} ->
            HasPermission = lists:any(
                fun(Role) ->
                    case maps:get(Role, Roles, []) of
                        RolePermissions when is_list(RolePermissions) ->
                            lists:member(Permission, RolePermissions);
                        _ -> false
                    end
                end,
                UserRoles
            ),
            {reply, HasPermission, State};
        _ ->
            {reply, false, State} % User not found or not authenticated
    end;

handle_call(_Request, _From, State) ->
    {reply, {error, unknown_request}, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

Securing Your Services

Once you have an authentication and authorization service, other services in your system can use it. A typical flow looks like this:

  1. Client Authenticates: Calls auth_service:login/2.
  2. Receives Session/Token: If successful, the client gets a session ID or token (e.g., a process ID, or a more complex JWT).
  3. Client Makes Authorized Request: When calling another service (e.g., data_service), the client includes its session/token and the action it wants to perform.
  4. Service Authorizes: The data_service calls auth_service:check_permission/2 using the client's identity and the requested action.
  5. Service Responds: If authorized, the action proceeds; otherwise, an error is returned.

Beyond Basic Auth

While our examples are simple, real-world systems need more:

  • Password Hashing: Never store plaintext passwords. Use strong hashing algorithms like bcrypt or pbkdf2.
  • Session Management: Securely generate, store, and validate session tokens. Ensure they expire and can be revoked.
  • Auditing: Log all authentication attempts and authorization checks for security monitoring and forensics.
  • External Identity Providers: Integrate with OAuth2/OpenID Connect for single sign-on.

Erlang's concurrency makes it great for building robust auth services.

AuthN vs AuthZ Check

Consider a user trying to access a secure document in an Erlang application.

Recap: Securing Services

We've covered the fundamentals of authentication and authorization in Erlang:

  • Authentication (AuthN) verifies identity ("Who are you?").
  • Authorization (AuthZ) determines permissions ("What can you do?").
  • We built a simple auth_service using GenServer for both user login and role-based access control (RBAC).
  • Understanding how to integrate these services is key to building secure and robust distributed Erlang applications.

Next, explore how to protect sensitive data itself within your Erlang applications.

الأسئلة الشائعة

هل درس «المصادقة والتفويض» مجاني؟

نعم — نص درس «المصادقة والتفويض» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Erlang OTP: Distributed & Fault-Tolerant Systems Programming، انتقل إلى CoddyKit PRO. تتضمن دورة Erlang OTP: Distributed & Fault-Tolerant Systems Programming 4 دروس في المجموع.

ماذا ستتعلم في «المصادقة والتفويض»؟

طبّق آليات متينة للمصادقة والتفويض على العمليات والمستخدمين الذين يصلون إلى خدمات Erlang الخاصة بكم تتمرن على Erlang OTP: Distributed & Fault-Tolerant Systems Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Erlang OTP: Distributed & Fault-Tolerant Systems Programming؟

لا تُشترط خبرة سابقة. Erlang OTP: Distributed & Fault-Tolerant Systems Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «المصادقة والتفويض»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Erlang OTP: Distributed & Fault-Tolerant Systems Programming هذا؟

نعم. كل درس في Erlang OTP: Distributed & Fault-Tolerant Systems Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. اتصال العقد الآمن (TLS)
  2. المصادقة والتفويض
  3. حماية البيانات الحساسة
  4. تعزيز أمان Cookie التوزيع والوصول إلى العُقد
← العودة إلى Erlang OTP: Distributed & Fault-Tolerant Systems Programming