JWT Auth
Add the [Authorize]
attribute to controllers or actions to require authentication:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Controllers;
// Can add [Authorize] here to make the controller protected
public class Controller : Controller
{
[Authorize]
[HttpGet]
public IActionResult Index()
{
return Ok("This endpoint is protected");
}
[AllowAnonymous]
[HttpGet]
public IActionResult PublicEndpoint()
{
return Ok("This endpoint is public");
}
}
Accessing User Information
Use the injected IuserService
to access the current user's information:
using Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Controllers;
[Authorize]
public class UserController : Controller
{
[HttpGet("profile")]
public IActionResult GetProfile()
{
var user = this.GetCurrentUser();
return Ok(new {
UserId = user.UserId,
Email = user.Email,
IsAuthenticated = user.IsAuthenticated,
Roles = user.Roles
});
}
}
Role-Based Authorization
To restrict access based on roles:
[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
return Ok("Only administrators can access this endpoint");
}
Or check roles programmatically:
public IActionResult ConditionalAccess()
{
var user = this.GetCurrentUser();
if (user.IsInRole("Admin"))
{
// Admin-specific logic
}
else
{
// Regular user logic
}
return Ok();
}
Example: Securing the Essays Controller
using Kiki.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Models;
using Supabase;
namespace Controllers;
[Authorize]
public class EssaysController : Controller
{
private readonly Supabase.Client _supabase;
public EssaysController(Supabase.Client supabase)
{
_supabase = supabase;
}
// GET
public async Task<IActionResult> Index()
{
var user = this.GetCurrentUser();
// Only retrieve essays belonging to the current user
var result = await _supabase.From<EssayModel>()
.Select("*")
.Filter("user_id", Constants.Operator.Equals, user.UserId)
.Get();
var essays = result.Models;
return View(essays);
}
[HttpPost]
public async Task<IActionResult> Create(EssayModel essay)
{
if (!ModelState.IsValid)
{
return View(essay);
}
var user = this.GetCurrentUser();
essay.UserId = user.UserId;
await _supabase.From<EssayModel>().Insert(essay);
return RedirectToAction(nameof(Index));
}
}