Designs API authorization across any stack: policy-based, role-based, claims/permission-based, and resource-based (ownership) checks. Covers ASP.NET Core, NestJS, Express, FastAPI, Django/DRF, Spring Security, Go middleware, and Casbin/OPA.
Ships in AI for Developers Toolkit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Design authorization the right way in any framework: named policies/permissions over scattered role strings, dedicated handlers for real business rules, resource-based checks for "can this user act on this object", and deny-by-default wiring. Authentication (who you are) is jwt-auth-setup; this is the authorization half (what you may do).
Works on a target: a project, repo, or GitHub URL (clone first: git clone --depth 1 <url> /tmp/repo). Inspect the current setup before generating anything.
| Manifest | Look for | Authorization mechanism |
|---|---|---|
*.csproj | Microsoft.AspNetCore.* | Policies, IAuthorizationHandler, IAuthorizationService |
package.json | @nestjs/core, express, fastify, @casl/ability | Guards + decorators, middleware, CASL abilities |
pyproject.toml, requirements*.txt | fastapi, django, djangorestframework | Depends/Security scopes, DRF permission classes, Django perms |
pom.xml, build.gradle(.kts) | spring-boot-starter-security | SecurityFilterChain, @PreAuthorize, PermissionEvaluator |
go.mod | net/http, gin, echo, chi, casbin | Middleware, Casbin enforcer |
Find existing checks:
grep -rn "AddAuthorization\|RequireRole\|RequireClaim\|\[Authorize\|RequireAuthorization\|IAuthorizationHandler" --include=*.cs <target>
grep -rn "@UseGuards\|CanActivate\|@Roles\|defineAbility\|req.user" --include=*.ts <target> | grep -v node_modules
grep -rn "Depends(\|Security(\|permission_classes\|has_perm\|@permission_required" --include=*.py <target>
grep -rn "@PreAuthorize\|authorizeHttpRequests\|hasRole\|hasAuthority" <target>/src
grep -rn "casbin\|Enforce(\|func.*Middleware" --include=*.go <target>
anyRequest().authenticated()).orders:manage checked in one place, mapped to roles centrally. Changing who can do what is a config change, not a grep.if (user.role == "Admin" || ...) blocks inside controllers.Named policies:
builder.Services.AddAuthorizationBuilder()
.AddPolicy("CanManageOrders", p => p.RequireClaim("permission", "orders:manage"))
.AddPolicy("AdminOnly", p => p.RequireRole("Admin"))
.AddPolicy("Over18", p => p.AddRequirements(new MinimumAgeRequirement(18)))
.SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
Custom requirement + handler (real business rules):
public record MinimumAgeRequirement(int Age) : IAuthorizationRequirement;
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext ctx, MinimumAgeRequirement req)
{
var dob = ctx.User.FindFirst("dob")?.Value;
if (DateTime.TryParse(dob, out var d) && d.AddYears(req.Age) <= DateTime.Today)
ctx.Succeed(req);
return Task.CompletedTask;
}
}
builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
Resource-based (can THIS user act on THIS object) - implement AuthorizationHandler<TRequirement, Order> and call:
var auth = await _authService.AuthorizeAsync(User, order, "OrderOwnerPolicy");
if (!auth.Succeeded) return Results.Forbid();
Wiring endpoints:
app.MapPost("/orders", ...).RequireAuthorization("CanManageOrders");
group.RequireAuthorization("AdminOnly");
app.MapGet("/health", ...).AllowAnonymous(); // explicit opt-out from the fallback policy
APP_GUARD) for authentication, a @Roles() / @Permissions() decorator read via Reflector in a RolesGuard, and a @Public() decorator for opt-outs.@Injectable()
export class PermissionsGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<string[]>('permissions', [ctx.getHandler(), ctx.getClass()]);
if (!required) return true;
const { user } = ctx.switchToHttp().getRequest();
return required.every(p => user?.permissions?.includes(p));
}
}
requirePermission('orders:manage') middleware / preHandler hook; mount auth globally and whitelist public routes.defineAbility, ability.can('update', subject('Order', order))) keeps rules in one place.Security(get_current_user, scopes=["orders:manage"]) with SecurityScopes, or a require_permission("orders:manage") dependency factory; apply router-wide via APIRouter(dependencies=[...]).permission_classes = [IsAuthenticated, IsOrderOwner] with has_permission (endpoint) and has_object_permission (resource). Set DEFAULT_PERMISSION_CLASSES to IsAuthenticated for deny-by-default. Object-level perms in plain Django: django-guardian or rules.class IsOrderOwner(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner_id == request.user.id
Note: DRF calls has_object_permission only via get_object() - custom list queries must filter by owner themselves.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a
.requestMatchers("/health").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()); // deny by default
return http.build();
}
@EnableMethodSecurity + @PreAuthorize("hasAuthority('orders:manage')").@PreAuthorize("@orderSecurity.isOwner(#id, authentication)") with a bean, or a custom PermissionEvaluator for hasPermission(#order, 'write'). @PostAuthorize checks the returned object.RequirePermission("orders:manage")(handler) reading claims from context.Context (set by the auth middleware). Same pattern in gin (r.Group(...).Use(...)), echo, and chi.if order.OwnerID != userID { return ErrForbidden }).Casbin, OPA, Cedar, OpenFGA / SpiceDB (relationship-based, Zanzibar-style). Recommend them only when rules are shared across services or change without deploys; otherwise in-code policies are simpler.
## Current state
<stack, what exists, gaps: anonymous endpoints, inline role strings, missing ownership checks>
## Policy design
<permissions/roles table, which endpoint needs which>
## Code
<policies/guards/permission classes/handlers + endpoint wiring, ready to paste>
## Tests to add
<allowed + denied + other-user's-resource per policy>
"Design authorization policies for my API", "restrict this endpoint to managers", "add a custom authorization rule", "stop users from accessing others' records" (resource-based), "add deny-by-default to my NestJS/Spring/FastAPI app". Pairs with jwt-auth-setup and the api-security-auditor agent.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/ai-dev-toolkit:authorization-setupfrom AI for Developers Toolkit
npx claudepluginhub stefanthecode/ai-for-developers --plugin ai-dev-toolkit45 skills in this plugin
/api-endpoint-scaffolderScaffold HTTP API endpoints in any stack - ASP.NET Core Minimal APIs or controllers, Express, Fastify, NestJS, FastAPI, Django REST Framework, Spring Boot controllers, Go net/http, chi, Gin - one feature per endpoint (REPR style) with request validation, typed responses, route grouping, auth, and OpenAPI metadata. Use this skill whenever the user wants to add an endpoint or route, convert controllers to minimal APIs, structure routes or routers, set up endpoint groups, TypedResults, route handlers, request DTOs/schemas (zod, Pydantic, Bean Validation, binding tags), or asks "how do I add an endpoint / structure my API routes". Always use this skill for endpoint scaffolding; it generates a complete, validated endpoint that matches the project's conventions./architecture-test-generatorGenerate architecture tests / fitness functions that fail the build when architectural rules are violated - layer dependencies, module boundaries, cycles, naming, and visibility conventions - in any stack: NetArchTest or ArchUnitNET (.NET), ArchUnit or Konsist (Java/Kotlin), dependency-cruiser or eslint-plugin-boundaries (TypeScript/JavaScript), import-linter (Python), go-arch-lint or depguard (Go). Use this skill whenever the user wants architecture tests, to enforce layering or the dependency rule, dependency rules as tests, import rules, forbidden imports, no circular dependencies, naming conventions, fitness functions, or asks "how do I stop people breaking the architecture / enforce my layers / keep modules from importing each other". Always use this skill for architecture-test requests; it generates rules matching the project's real structure./async-await-auditorAudit async and concurrent code in any language for correctness and performance bugs - C#/.NET (async/await, Task), JavaScript/TypeScript (Promises, async/await), Python (asyncio), Java/Kotlin (CompletableFuture, virtual threads, coroutines), Go (goroutines, channels, context), Rust (tokio/async). Use this skill whenever the user shares async or concurrent code, or asks about deadlocks, hangs, blocking calls, .Result/.Wait(), async void, ConfigureAwait, floating or unhandled promises, await in a loop vs Promise.all, blocking the event loop, forgotten await, asyncio.gather/TaskGroup, CompletableFuture.join, virtual thread pinning, goroutine leaks, context cancellation, WaitGroup/errgroup, holding a lock across .await, fire-and-forget tasks, cancellation tokens, or "why does my async code hang". Always use this skill for async/concurrency reviews instead of answering from memory; it applies a fixed checklist and rewrites the code./benchmark-setupSet up correct micro-benchmarks in any stack and interpret the results - BenchmarkDotNet (.NET), JMH (Java/Kotlin), pytest-benchmark / pyperf (Python), Vitest bench / tinybench / mitata (JavaScript/TypeScript), Go testing.B + benchstat, Rust criterion. Use this skill whenever the user wants to benchmark code, measure performance, compare two implementations or functions, set up a benchmark harness, or asks "which is faster", "benchmark these two functions", "how do I benchmark this", "is this optimization worth it", or "interpret these benchmark results". Always use this skill for micro-benchmarking requests; it writes correct benchmarks, avoids the classic pitfalls, and explains the numbers./caching-strategy-setupAdd the right caching to an app in any stack - in-process, distributed (Redis/Valkey/Memcached), two-level, or HTTP/output caching - with correct keys, expiration, stampede protection, and invalidation. Covers HybridCache / IMemoryCache / IDistributedCache / output caching in .NET, lru-cache / keyv / cache-manager / ioredis in Node, functools / cachetools / redis-py / Django cache in Python, Spring Cache with Caffeine or Redis in Java/Kotlin, and ristretto / groupcache / singleflight / go-redis in Go. Use this skill whenever the user wants caching, to cache a query/response, Redis caching, @Cacheable, lru_cache, HybridCache, cache-aside, output caching, or asks "how do I cache this / add caching / avoid cache stampede / invalidate this cache". Always use this skill for caching requests; it picks the right layer and wires expiration + invalidation correctly./cicd-pipeline-generatorGenerate a CI/CD pipeline for an app in any stack - GitHub Actions (primary), Azure DevOps, or GitLab CI - with per-stack install/build/test/coverage, dependency caching, lint, vulnerability scan, container build and push, and environment-gated deploy. Covers .NET, Node/TypeScript (npm/pnpm/yarn), Python (pip/uv/poetry), Java/Kotlin (Maven/Gradle), Go, and monorepos with several stacks. Use this skill whenever the user wants a CI/CD pipeline, a GitHub Actions workflow, Azure DevOps YAML, .gitlab-ci.yml, build/test automation, a release or deploy pipeline, caching to speed up CI, or asks "how do I set up CI / pipeline for my app / automate build and deploy / why is my CI slow". Always use this skill for CI/CD requests; it generates a complete, sensible pipeline.Other plugins' skills for the same job