Skip to main content

Authentication and Authorization

Level: Intermediate

ℹ️ What You'll Learn
  • Authentication: Verify identity (who are you?) - login with username+password, return token
  • Authorization: Verify permission (can you do this?) - check role/claims, allow/deny access
  • JWT (JSON Web Token): Stateless token (Header.Payload.Signature) encoding user identity and claims
  • JWT payload contains: sub (user ID), name (username), role (Teacher/Admin/Student), iat (issued at), exp (expiration)
  • Token generation: User logs in → Server creates JWT → Server returns token → Client stores token
  • Bearer token: Authorization header Authorization: Bearer {token} sent with every request
  • Token validation: Server verifies signature, checks expiration, extracts user claims
  • [Authorize] attribute: Block action access if user not authenticated (returns 401 Unauthorized if no token)
  • [AllowAnonymous] attribute: Allow unauthenticated access (e.g., login endpoint doesn't need token)
  • Role-based authorization: [Authorize(Roles = "Admin")] only admins can access (returns 403 Forbidden if wrong role)
  • Claims-based authorization: More flexible (claims = user attributes: userId, departmentId, canCreateStudent)
  • School Management roles: SuperAdmin (all access), Admin (school settings), Principal (school reports), Teacher (class students), Student (own data)
  • Login flow: POST /auth/login with credentials → Server validates → Returns JWT token → Client stores in localStorage
  • Protected endpoints: GET /students requires [Authorize], clients send token in header
  • Token expiration: Short-lived tokens (15 min) for security, refresh tokens (1 week) for convenience

Authentication vs Authorization

Authentication = verify identity (who are you?)

Username + Password → Token

Authorization = verify permission (can you do this?)

Role = Admin → Can delete students

JWT (JSON Web Token)

Header.Payload.Signature

Example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMDEiLCJuYW1lIjoiUmF2aSIsInJvbGUiOiJBZG1pbiJ9.
Km8...

Authentication Endpoint

[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest request)
{
// Verify credentials
var user = _authService.ValidateUser(request.Email, request.Password);
if (user == null)
return Unauthorized(); // 401

// Generate token
var token = _tokenService.GenerateToken(user);

return Ok(new { token });
}

Request:

{
"email": "admin@sms.school",
"password": "securePassword123"
}

Response:

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Protected Endpoints

[Authorize] // Requires authentication
[HttpGet]
public async Task<ActionResult<List<Student>>> GetStudents()
{
// Only authenticated users can access
}

[Authorize(Roles = "Admin")] // Requires Admin role
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteStudent(int id)
{
// Only Admin users can delete
}

Bearer token in request header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Role-Based Access

Roles in token payload:

{
"sub": "101",
"name": "Ravi Kumar",
"email": "ravi@school.com",
"role": "Admin"
}

Controller authorization:

[Authorize(Roles = "Admin,Principal")]
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteStudent(int id)
{
// Admin or Principal only
}

Setup Authentication (Program.cs)

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourapp",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
};
});

app.UseAuthentication();
app.UseAuthorization();

Current User Info

[Authorize]
[HttpGet("profile")]
public IActionResult GetProfile()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var userName = User.FindFirst(ClaimTypes.Name)?.Value;
var role = User.FindFirst(ClaimTypes.Role)?.Value;

return Ok(new { userId, userName, role });
}

Key Takeaways

  • Authentication = identify user
  • Authorization = control access
  • JWT = stateless token
  • Roles = permission groups
  • Bearer = token in header
💡 Security Tip

Use HTTPS only. Never send tokens in URL or body.

🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Authentication. Try these prompts:

  • "How do I generate a JWT token?"
  • "What's the difference between Authorize and AllowAnonymous?"
  • "How do I check user role in code?"
  • "Quiz me on authentication"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

nexcoding.in