Blog Article

Authentication, Authorization, and Security Basics Every Full-Stack Dev Should Know

By NEERAJ DANG16 September 202616 min read
DGM trends 2027

Authentication, Authorization, and Security Basics Every Full-Stack Dev Should Know

A few months ago, a student in one of our Agra batches showed me the admin panel he had built for a coaching centre. Login worked. The dashboard looked clean. Then I changed one number in the browser address bar, from /api/students/41 to /api/students/42, and the screen filled with another student's phone number, address, and fee history.

I was not logged in as an admin. I was not even logged in as that student.

His app knew who I was. It never checked what I was allowed to see. That single missing line of code is the most common security flaw on the internet today, and it is exactly the kind of thing interviewers now test for.

This guide walks you through authentication, authorization, and the core security habits every full-stack developer needs. No heavy theory. Just the ideas, the code patterns, and the mistakes I keep seeing in real projects.

The Short Answer

Authentication answers the question "Who are you?" It is the process of verifying a user's identity, usually with a password, a one time code, or a passkey.

Authorization answers the question "What are you allowed to do?" It decides whether a verified user can view, edit, or delete a specific resource.

Authentication always comes first. Authorization happens on every single request after that. Most real world breaches in web apps happen because developers get the first part right and forget the second.

Authentication vs Authorization: A Simple Analogy

Think about boarding a train at Agra Cantt station.

When the TTE checks your ticket and your ID card, that is authentication. He is confirming you are the person named on the ticket.

When he checks whether your ticket is for the 3AC coach or the sleeper coach, that is authorization. You are a verified passenger, but that does not mean you can sit anywhere you like.

Blog image

A small but useful detail: the HTTP status code 401 is named "Unauthorized", yet it actually means unauthenticated. Status 403 is the one that means "you are known, but not permitted". Interviewers love this question.

Why Security Is Now a Hiring Skill

Five years ago, many companies treated security as someone else's job. That has changed.

The Verizon 2026 Data Breach Investigations Report, which analysed more than 22,000 confirmed breaches, found that exploitation of vulnerabilities was the top way attackers got in, at 31% of breaches. Credential abuse (stolen or guessed passwords) still accounted for 13%, and phishing for 16%. Most of these entry points trace back to code and configuration decisions that developers make every day.

The OWASP Top 10:2025, the most widely referenced list of web application risks, puts Broken Access Control at number one for the second edition running. Authentication Failures sits at number seven.

In India, the pressure is growing from the legal side too. CERT-In directions already require organisations to report certain cyber incidents within six hours. The Digital Personal Data Protection Rules, 2025, notified in November 2025, require businesses to put reasonable security safeguards around personal data, with most obligations phasing in over eighteen months.

For a fresher, this means one thing. A startup in Noida or a product company hiring remotely will trust you faster if you can explain how you protect user data, not just how you display it.

Part 1: Authentication Done Right

How to store passwords securely

Never store passwords in plain text. Never encrypt them either, because encryption can be reversed. Passwords must be hashed with a slow, salted algorithm designed for the job.

A hash is a one way fingerprint. When a user logs in, you hash what they typed and compare it with the stored hash. You never need to know the original password.

The OWASP Password Storage Cheat Sheet recommends, in order of preference:

Blog image

Here is a simple Node.js example using Argon2id:

import argon2 from "argon2";

// At signup
const hash = await argon2.hash(plainPassword, { type: argon2.argon2id });
await db.users.create({ email, passwordHash: hash });

// At login
const user = await db.users.findByEmail(email);
const isValid = user && (await argon2.verify(user.passwordHash, plainPassword));
if (!isValid) {
  return res.status(401).json({ error: "Invalid email or password" });
}

Notice the error message. It does not say "email not found" or "wrong password". Telling an attacker which part failed helps them discover which emails are registered.

Never use MD5, SHA-1, or plain SHA-256 for passwords. They are fast by design, which is exactly what an attacker wants when guessing billions of combinations.

Modern password rules (most apps still get these wrong)

The US standards body NIST rewrote its guidance in SP 800-63B-4, finalised in August 2025. Many Indian apps still follow the old rules. Here is what current guidance actually says:

  • Length matters most. Passwords used on their own should be at least 15 characters. If the password is one part of multi-factor login, a minimum of 8 is acceptable.
  • Allow long passwords. Support at least 64 characters.
  • Drop the composition rules. Do not force "one uppercase, one number, one symbol". It produces Password@123, which helps nobody.
  • Stop forced rotation. Do not make users change passwords every 90 days. Force a change only when there is evidence of compromise.
  • Check against a blocklist. Reject common and leaked passwords. The free Pwned Passwords API from Have I Been Pwned is a popular way to do this.
  • Allow paste and password managers. Blocking paste pushes people towards weaker passwords.

Add a second factor

Multi-factor authentication (MFA) means the user proves identity with two different things, such as something they know (a password) and something they have (a phone or security key).

In India, SMS OTP is the familiar option, and it is far better than a password alone. Be aware, though, that NIST now classifies SMS as a restricted authenticator because of SIM swap and interception risks. Authenticator apps (TOTP) and passkeys are stronger choices wherever your users can adopt them.

Passkeys: where login is heading

Passkeys replace passwords with a cryptographic key pair stored on the user's device, unlocked by fingerprint, face, or screen PIN. They are built on the WebAuthn standard and backed by Google, Apple, and Microsoft.

The numbers are persuasive. The FIDO Alliance Passkey Index, released in October 2025 with data from companies including Amazon, Google, Microsoft, and PayPal, reported a 93% sign-in success rate for passkeys against 63% for other methods, and login times of 8.5 seconds compared with 31.2 seconds.

Because a passkey is tied to the real website domain, a fake phishing page simply cannot use it. You do not need to build passkeys from scratch as a beginner, but you should know what they are and why they resist phishing.

Part 2: Keeping Users Logged In (Sessions vs JWT)

Once a user logs in, your app needs a way to remember them on every following request. There are two main approaches.

Server side sessions

The server creates a random session ID, stores the session data (in memory, Redis, or a database), and sends the ID to the browser in a cookie. On each request, the browser sends the cookie back and the server looks up the session.

Strengths: easy to revoke instantly, small cookie, simple mental model. Trade off: the server must store and share session state, which needs planning when you run many servers.

Token based auth with JWT

A JSON Web Token (RFC 7519) is a signed string that carries claims, such as the user ID and role. The server verifies the signature instead of looking anything up.

Strengths: stateless, works well across services and mobile apps. Trade off: hard to revoke before it expires, and easy to misuse.

Blog image

Rules for JWTs that save you from trouble

  1. Keep access tokens short lived. Five to fifteen minutes is a common range. Pair them with a refresh token that rotates on every use.
  2. Never put secrets in the payload. A JWT is signed, not encrypted. Anyone can decode and read it.
  3. Always verify the signature and the algorithm. Reject tokens that claim "alg": "none", and set the expected algorithm explicitly in your code.
  4. Use a long, random signing secret stored in environment variables, never in your Git repository.
  5. Think carefully about storage. A token in localStorage can be stolen by any cross site scripting (XSS) bug. For browser apps, an HttpOnly cookie is usually the safer home.

Whether you use sessions or tokens in cookies, set these flags. The MDN guide to Set-Cookie explains each one in detail.

javascript

res.cookie("sid", sessionId, {
  httpOnly: true,   // JavaScript cannot read it, which blocks most XSS theft
  secure: true,     // sent only over HTTPS
  sameSite: "lax",  // limits cross site request forgery
  maxAge: 1000 * 60 * 60 * 8 // 8 hours
});

Also, create a new session ID right after login. Reusing the old one opens the door to session fixation attacks.

What about OAuth and "Login with Google"?

OAuth 2.0 is a framework that lets one app access another service on the user's behalf, without ever seeing the user's password. OpenID Connect adds an identity layer on top of it, which is what powers "Sign in with Google".

For beginners, the practical advice is simple. Use a well maintained library or a managed identity provider rather than writing the flow yourself, and use the Authorization Code flow with PKCE, which the IETF's OAuth 2.0 Security Best Current Practice (RFC 9700) recommends for all client types.

Part 3: Authorization, the Part Everyone Forgets

Remember the coaching centre app from the start? That bug has a name: IDOR, or Insecure Direct Object Reference. It is a textbook case of broken access control.

Here is the vulnerable version:

// Vulnerable: any logged in user can read any student
app.get("/api/students/:id", requireLogin, async (req, res) => {
  const student = await db.students.findById(req.params.id);
  res.json(student);
});


And the fixed version:

// Safe: check ownership or role before returning data
app.get("/api/students/:id", requireLogin, async (req, res) => {
  const student = await db.students.findById(req.params.id);
  if (!student) return res.status(404).end();

  const isOwner = student.userId === req.user.id;
  const isStaff = ["admin", "counsellor"].includes(req.user.role);

  if (!isOwner && !isStaff) {
    return res.status(404).end(); // do not reveal the record exists
  }
  res.json(student);
});



Three lines made the difference between a safe app and a data leak.

Common authorization models

Role Based Access Control (RBAC). Users get roles such as student, counsellor, or admin, and each role has fixed permissions. This covers most beginner and small business projects.

Attribute Based Access Control (ABAC). Decisions use attributes, such as "a counsellor can view students only from their own branch". Useful as rules become more detailed.

Ownership checks. The simplest and most important rule: users can act on their own records. Apply it everywhere, even when you also use roles.

Golden rules of authorization

  • Deny by default. A new route should be locked until you deliberately open it.
  • Check on the server, every time. Hiding a button in React is a user experience choice, not a security control. Anyone can call your API directly with Postman or curl.
  • Never trust IDs, roles, or prices sent from the client. Read the user's identity from the verified session or token, not from the request body.
  • Centralise the logic. Write reusable middleware or policy functions instead of scattering if checks across fifty routes.
  • Test with two accounts. Log in as user A, copy a request, and replay it as user B. This one habit catches most access control bugs.

Part 4: Security Basics Beyond Login

Authentication and authorization protect the front door. These habits protect the rest of the house.

Validate every input

Treat all incoming data as untrusted, including form fields, query strings, headers, and uploaded files. Validate type, length, and format on the server using a schema library such as Zod or Joi.

Prevent injection

Never build SQL queries by joining strings with user input. Use parameterised queries or an ORM.

javascript

// Unsafe
db.query(`SELECT * FROM users WHERE email = '${email}'`);

// Safe
db.query("SELECT * FROM users WHERE email = $1", [email]);

The same idea applies to NoSQL databases, where attackers can inject query operators. If you are still choosing a database, our explainer on picking between SQL and NoSQL without the jargon covers the basics.

Stop cross site scripting (XSS)

XSS happens when an attacker's script runs inside your page. React and most modern frameworks escape output by default, so the risk usually comes from shortcuts like dangerouslySetInnerHTML or inserting raw HTML from users. Add a Content Security Policy header as a second layer of defence.

Guard against CSRF

Cross Site Request Forgery tricks a logged in user's browser into sending a request they never intended. SameSite cookies help a lot, and anti CSRF tokens add further protection for sensitive actions like changing a password or making a payment.

Always use HTTPS

Every page, every API, every environment that real users touch. Free certificates from Let's Encrypt removed the cost excuse years ago.

Rate limit login and OTP endpoints

Without limits, attackers can try thousands of passwords or brute force a six digit OTP. Throttle by IP address and by account, and add temporary lockouts or CAPTCHA after repeated failures.

Configure CORS carefully

Allowing every origin with a wildcard while also sending credentials is a classic misconfiguration. List only the frontends you actually trust.

Protect secrets and dependencies

Keep API keys and database passwords in environment variables or a secrets manager. Run npm audit regularly, because Software Supply Chain Failures now sits at number three in the OWASP Top 10:2025. Our guide to deployment and DevOps basics for full-stack developers shows where secrets and dependency checks fit into a release pipeline.

Log the right things

Record failed logins, permission denials, and password resets, so you can spot an attack in progress. Never log passwords, full tokens, or OTPs.

A Quick Security Checklist for Your Next Project

Before you share a project link with a recruiter, run through this list.

  1. Passwords hashed with Argon2id or bcrypt
  2. Generic login error messages
  3. Rate limiting on login, signup, and OTP routes
  4. Cookies set with HttpOnly, Secure, and SameSite
  5. Short lived access tokens, if you use JWT
  6. Ownership or role check on every route that returns user data
  7. Server side validation on every input
  8. Parameterised queries everywhere
  9. HTTPS on all environments
  10. No secrets committed to GitHub
  11. Dependencies audited
  12. Security events logged, sensitive values excluded

If you can tick all twelve, your project is already ahead of most portfolios I review.

Common Mistakes I See in Student Projects

Checking permissions only in the frontend. The admin menu is hidden, but the admin API is wide open.

Storing passwords with plain SHA-256. It looks secure. It is not, because it is far too fast.

JWTs that never expire. A token stolen today should not work next year.

Pushing .env files to public GitHub repositories. Automated bots scan for leaked keys within minutes of a push.

Rolling their own crypto or auth. Use proven libraries. Your job is to configure them correctly, not reinvent them.

Detailed error messages in production. Stack traces tell attackers your framework, file paths, and sometimes your database structure.

How to Talk About Security in Interviews

Security questions now appear regularly in full-stack interviews, even for fresher roles. Expect prompts like:

  • Explain the difference between authentication and authorization.
  • How would you store user passwords?
  • Sessions or JWT for this app, and why?
  • How would you stop one user from seeing another user's data?

The strongest answers connect a concept to something you built. "In my project, I added an ownership check after testing with two accounts" beats a textbook definition every time. Our list of full-stack developer interview questions for 2026 covers more of these follow ups.

Security also shapes how you design APIs. If you have not read it yet, our guide on choosing between REST and GraphQL explains how access checks differ in each style.

What to Learn, and in What Order

  1. HTTP fundamentals: methods, status codes, headers, and cookies
  2. Password hashing and a basic login system in Node.js and Express
  3. Sessions first, then JWTs, so you understand the trade offs from experience
  4. Authorization middleware with roles and ownership checks
  5. The OWASP Top 10:2025, one category per week, with a small demo for each
  6. OAuth and OpenID Connect using a trusted library
  7. Passkeys and WebAuthn once the basics feel comfortable

To see where security fits among everything else you need to learn, follow our step by step full-stack developer roadmap for 2026. And if you are about to start your first role, our piece on mistakes new full-stack developers make in their first job is worth a read before day one.

What Is Changing in 2026 and Beyond

Passwordless login is going mainstream. With passkeys supported across Android, iOS, Windows, and major browsers, more Indian apps will offer them alongside OTP.

AI is speeding up attacks. The Verizon 2026 report points to faster weaponisation of known vulnerabilities, which makes patching and dependency hygiene more urgent.

AI generated code needs review. Coding assistants can produce working login flows that quietly skip authorization checks. Reading code critically is becoming as important as writing it.

Privacy compliance is arriving in India. As the DPDP Rules take full effect, companies will expect developers to understand data minimisation, consent, and breach readiness.

The Bottom Line

Authentication proves who someone is. Authorization decides what they can do. Security is the discipline of getting both right, plus the everyday habits that stop small mistakes becoming headlines.

You do not need to become a security specialist to be a strong full-stack developer. You need to hash passwords properly, check permissions on every request, validate input, and use proven tools. Those habits alone put you ahead of a large share of the apps running today.

The student with the coaching centre app fixed his bug in ten minutes. What stayed with him was the lesson: a feature is not finished until you have tried to break it. He now tests every route with two accounts, and he talked about exactly that in the interview that got him his first job.

For the complete picture of skills, salaries, and roles, explore our guide to full-stack development careers in Agra and North India.

Build secure, real world apps with mentors in Agra

At Skillyards, our Full-Stack Web Development training in Agra covers authentication, authorization, and secure API design through live projects, with mentors who review your code the way a senior engineer would. Want a degree alongside job ready skills? Our On-Job Degree programme combines a DBRAU affiliated BCA with hands on full-stack training, paid internships, and placement support.

Frequently Asked Questions

  1. What is the difference between authentication and authorization?
    Authentication verifies who a user is. Authorization decides what that verified user is allowed to access or change.
  2. Which comes first, authentication or authorization? Authentication comes first. The system must know who you are before it can decide what you may do.
  3. Is JWT better than sessions?
    Neither is better in every case. Sessions suit traditional web apps and are easy to revoke. JWTs suit APIs, mobile apps, and multi service systems.
  4. Where should I store JWT tokens in the browser? For most web apps, an HttpOnly, Secure cookie is safer than localStorage, because scripts cannot read it.
  5. Should I use bcrypt or Argon2? Use Argon2id for new projects, as OWASP recommends. bcrypt with a work factor of 10 or more remains acceptable for existing systems.
  6. What is broken access control? It is when users can reach data or actions outside their permissions. It ranks first in the OWASP Top 10:2025.
  7. Are passkeys safer than passwords? Yes. Passkeys cannot be reused across sites or captured by fake phishing pages, and nothing secret is stored on the server.
  8. Do freshers need security knowledge for full-stack jobs? Yes. Interviewers increasingly ask about password storage, sessions, JWTs, and access control, even for entry level roles.
Complete Guide

The Complete Guide to Full-Stack Development Careers in Agra & India

Jump to the parent pillar for the full roadmap.

Explore the Guide

More on this Topic

Community

Discussion