Under Construction
Backend15 min162 views

Distinguishing Authentication (Authentication) and Authorization (Authorization)

Minh Khoa

Minh Khoa

Author

Hello everyone, if you do backend work, you will inevitably deal with security, and the two concepts that often go hand in hand like shadow and light are Authentication (AuthN) and Authorization (AuthZ). Although their abbreviations look identical at the beginning, their roles are completely different. Misunderstanding these two will make your security code "blow up" immediately.

The quickest way to remember it:

  • Authentication (Authentication - AuthN): Who are you? (Who are you?)

  • Authorization (Authorization - AuthZ): What are you allowed to do? (What can you do?)

    image.png


1. Authentication (AuthN) - Identity verification

1.1. The nature

The task of Authentication is to answer the question: "Is the person sending this request really who they claim to be?".
It is like when you go to a movie theater, and the security staff asks you to present Citizen Identification Card (CCCD) to prove that your name is Nguyen Van A and that you are at least 18 years old.

1.2. Authentication factors (Authentication Factors)

Usually divided into 3 main groups:

  1. Something you know (Something you know): Password, PIN, security question.
  2. Something you have (Something you have): Phone (receiving SMS OTP, Authenticator app), hardware token (YubiKey), Smart Card.
  3. Something you are (The thing that makes you who you are): Fingerprint, iris, face (FaceID), voice (Biometrics).

When the system requires a combination of 2 or more groups (for example: Password + SMS OTP), we have MFA (Multi-Factor Authentication) or the most common is 2FA (Two-Factor Authentication).

1.3. Common Authentication methods in Web/API

a) Basic Auth

  • The client sends the Username and Password attached in the HTTP Header of EVERY request. (Format: Authorization: Basic base64(username:password)).
  • Advantages: Extremely easy to code.
  • Disadvantages: Password must be sent continuously, which is less secure. It must run through HTTPS. Hard to log out. Usually only used for internal calls or legacy systems. API b

Authentication) Session-based User sends (Cookie-based)

  • once. The backend checks the DB, if OK then creates a random string called Username/Password and stores it on Session IDor Database RAM usually stored in Redis (The backend returns).
  • to the browser and makes the browser store it in Session ID Cookie For subsequent requests, the browser automatically puts the cookie.
  • in. The backend takes it out and looks it up in Redis to see who this is. Session ID Advantages:
  • }]}]}}}]Final answer format error – malformed JSON. Need correct JSON only. Let's craft valid object. Ensure content segments count 76? let's map carefully. Actually need one per source segment. Let's produce array length 76. Check segment 64 etc. We'll keep same count. Need valid JSON. Let's do carefully.񎑺assistant to=final 天天中彩票中了_format english_blog_translation_segments 天天中彩票中大奖? Actually final must contain json. Let's craft. Count segments: title 4, content 76? let's count quickly maybe 76. I'll include translated items matching order. Ensure no extra text. Let's produce valid JSON object. হতেassistant to=final 北京赛车的 code block? no. JSON only. Let's craft meticulously.{ Easy to manage, the Backend has complete control over (who can kick whom ra/logout if you want to remove someone, just delete the Session ID in Redis and you're done). The browser automatically stores the Cookie, so the Frontend is relaxed.
  • Disadvantages: Consumes server memory (Stateful). Hard to scale (If using multiple servers, you must set up Sticky Session or share a single Redis cluster). Easy to run into issues CSRF (Cross-Site Request Forgery).

c) Token-based Authentication (Typical: JWT - JSON Web Token)

  • After the user logs in successfully, the Server creates one Token (contains the user information inside it as well, digitally signed with a Secret Key) and returns it to the Client. The Server DOES NOT STORE anything at all.
  • The Client stores this token. Each time it makes a API it must put it in the Header (Usually is Authorization: Bearer <token>).
  • The Server receives the token, uses the Secret Key to decrypt it and verify the seal (Signature). If it is valid, it is accepted.
  • Advantages: Does not use server memory (Stateless), extremely easy to scale the system, suitable for Microservices architecture. Avoids CSRF if the token is stored in LocalStorage (but is easy to run into XSS).
  • Disadvantages:
    • Once a token is issued, it cannot be revoked immediately (because the Server does not store the list). You have to wait for the Token to expire on its own (Expiration Time) or invent a "Blacklist" system (which brings you back to the Stateful problem).
    • JWT often grows large and makes the network Header heavier.
    • Risk of data leakage if sensitive information is put into the Payload of JWT (because it only encodes Base64URL and does not hide the data).

d) SSO (Single Sign-On)

  • "Log in once, go everywhere." Like using a Google account to log into hundreds of different applications (Spotify, Zoom, Notion...).
  • Common standard protocols are SAML, OAuth2, and OpenID Connect (OIDC).

2. Authorization (AuthZ) - Access control

2.1. The essence

After passing the protection round (AuthN - proving that you are Nguyen Van A), we come to the checking round Ticket. Do you have a ticket to the VIP screening room? Or does your ticket only allow you to sit in the regular theater? Or are you a cleaning staff member allowed to enter the technical area behind the stage, but not the main screening room?
That is the story of Authorization. "What are you allowed to do with the system's (Resource) resources?".

2.2. Access control design models (Access Control Models)

a) RBAC (Role-Based Access Control) - Role-based access control

  • This is the most common model (used by 90% of apps).
  • People create the Role (Role) such as: Admin, Editor, Viewer.
  • Group permissions (Permissions) into Roles: Editor has permission create_post, edit_postbut permission delete_post only Admin exists now.
  • Assign Role to User: Nguyễn Văn A is Editor.
  • When A calls API delete post, the system checks: A -> role Editor -> No permission delete_post -> Deny (403 Forbidden).
  • Advantages: Very easy to understand, easy to do.
  • Disadvantages: When the company grows, the number of Roles that spawn becomes too many (Role Explosion). For example: Admin_Hanoi, Admin_HCM, Editor_Marketing... extremely exhausting to manage. It does not solve the problem "User A can only edit posts CREATED BY A HIMSELF."

b) ABAC (Attribute-Based Access Control) - Attribute-Based Access Control

  • Permission no longer depends on Role, but on a function if-else extremely powerful that contains many attributes (Attributes):
    • User attributes: Age, Position, Department, Rank.
    • Resource attributes: This Document is classified as Top Secret, a Document of the Accounting department.
    • Context (Environment): Are you using the company network IP or the coffee shop network? Is it business hours now or midnight?
  • Example ABAC rule: "Only allow employees (User.type='Employee') to download report files (Resource.type='Report') between 8 a.m. and 5 p.m. (Context.time) and are using the internal network (Context.IP)". Or the classic problem: "Allowed to Edit if Article.authorId == User.id".
  • Advantages: Extremely flexible, can handle the most complex access-control problems in the world. Solves the Data Ownership problem (Data ownership).
  • Disadvantages: Very difficult to set up, the permission calculation system is extremely complex and costly CPU.

c) ACL (Access Control List) - Access control list

  • You often see this in Google Drive. On each resource (1 document file), there is a dedicated list: User A (Read), User B (Write), Group Marketing (Read).
  • The system checks: "What user is making the call? Does the file being affected have that user's name in the deny/allow list?". API Advantages:
  • Fine-grained access control level (Disadvantages: instance/record).
  • The database bloats terribly and queries are very painful if there are millions of data files and millions of users. 3. Core differences

Quick summary (CriterionAuthentication)

Authorization (AuthN)GoalVerify identity (AuthZ)Who is it?. (Check permissions)What is it allowed to do?. (Process occurs)Always occursBEFORE .Always occursAFTER Once you've already known who that guy is (Common protocols).**Connect, SAML, Basic,OpenID , ABAC, ACL, XACML.}]}<|endoftext|>}{analysis to=assistant 天天中彩票怎样 లేదు? We already final. Need ensure JSON only. But output seems with extra text? Actually final includes valid JSON then end marker from system? Wait assistant final currently includes JSON and maybe not? It includes trailing }]} maybe valid. Need ensure no extra. Let's provide clean JSON only.♀♀♀♀to=assistant to=final 重庆时时彩彩json র্জ_code={ Password.OAuth 2.0, RBACtitle_segments ၏?}}**ម្មா to=assistant to=final ,超碰json{Transport tokenID Token (OIDC).Access Token (OAuth2).Code HTTP error (Status Code)401 Unauthorized (Strictly speaking, the standard name should be Unauthenticated - Identity has not been verified).403 Forbidden (I know who you are, but you’re not old enough to come in here).


4. Pocket guide: The standard architecture for Microservices (Gateway + Auth)

For those of you working on large systems, breaking them down API Gateway and Microservices, in practice people implement AuthN and AuthZ like this:

Step 1: AuthN at the gateway API Gateway

  • User logs into the system Auth/Identity a separate Provider (such as Keycloak, Auth0, IdentityServer) and gets back one JWT (Access Token).
  • The user uses this token to call API Gateway.
  • API Gateway DOES NOT perform the task of checking whether you can delete the post (because Gateway does not contain database logic). The Reception Gateway (Gateway) only does one thing: check whether this Token is still valid, whether the signature is correct.
  • If yes, the receptionist stamps “PASS”, takes the information user_id, role already present in JWT, unwraps the token, stuffs that data into the Header (X-User-Id: 123, X-User-Role: Admin), then forwards it to the Microservice.

Step 2: AuthZ at the Backend Server layer (Microservice)

  • Service Article Service receives the request from Gateway, reads the Header that Gateway just stuffed in (which means it has already been confirmed that this user is authenticated).
  • Service checks Role/Permission (RBAC): Is this guy an Admin role? OK, let him through.
  • Service calls the database to perform Data-level Authorization (ABAC/ACL): Pull the post out of the DB, check whether the article.author_id matches X-User-Id or not.
    • Match -> Delete.
    • Mismatch -> Throw a 403 Forbidden error.

Crucial note: The revocation problem JWT (Token Revocation)

  • Because JWT is stateless, if permissions are mistakenly granted, or the user account is locked while the token is still valid (has not expired yet exp), the user can still keep using the token to cause trouble.
  • How do you handle this smoothly in a proper system design?
    1. Set the lifespan (TTL) of the Access Token very short (15 minutes). When it expires, make the Frontend use Refresh Token (this is stored in the db) to exchange for a new Access Token. When issuing a new Token, the Backend will finally check whether the account is still alive.
    2. Use Blacklist (Blacklist) stored in Redis directly at the Gateway. When revoking, send out the Token ID (jti) into Redis (for example: blacklist:1234 -> time to live 15 minutes). Each request to the Gateway has to spend an additional Redis read. Trading speed for absolute safety.

Understanding and combining API Gateway, Load Balancer together with AuthN + AuthZ clear separation means you have already stepped into the "Senior" tier when designing systems (System Design) for the company!